Compare commits

...
Author SHA1 Message Date
DrSmoothl c120b0fb97 chore(release): v2.3.1 2026-10-31 23:41:23 +08:00
DrSmoothl 93290e4d0c fix(protocol): allow clearing group member cards
Refs #620
2026-10-31 23:25:45 +08:00
DrSmoothl fa4870bdca fix(runtime): improve Windows message reception 2026-10-31 23:03:23 +08:00
DrSmoothl b126b5c166 fix(runtime): prevent Windows client crashes during startup
Refs #619
2026-10-31 22:02:31 +08:00
DrSmoothl 11d42b4e98 chore(release): v2.3.0 2026-10-31 20:29:11 +08:00
DrSmoothl 8b3f11a22b chore(runtime): refresh Windows and Linux binaries 2026-10-31 20:19:14 +08:00
DrSmoothl 8ecf41ccb7 fix(bridge): preserve QQ runtime failures across session updates
Surface connection failures immediately to waiting requests and keep the original error visible until the session reconnects. Ignore late login updates from the failed connection.
2026-10-31 18:28:05 +08:00
DrSmoothl fcbb2661d1 fix(bridge): include the reason code for unavailable private message receipts
Show the reported reason when private message receipts are unavailable. Keep the existing warning when the connection supplies no reason.
2026-10-31 18:28:05 +08:00
DrSmoothl 299fa85a74 fix(onebot): match group invitations to the correct request
Report distinct invitations separately and approve only the request that belongs to the account and inviter. Reject ambiguous approvals and resolve the sender of invitations from outside the contact list.

Refs #612
2026-10-31 18:28:05 +08:00
DrSmoothl d8763c98db fix(protocol): validate profile birthdays against the calendar
Omit invalid birthdays and preserve valid leap days when the birth year is private.

Refs #594
2026-10-31 18:28:05 +08:00
DrSmoothl a557bf72e7 fix(protocol): preserve private voice playback on older clients
Keep private voice messages playable on older clients while retaining the existing voice message for current clients. Cover the reported upload response in a regression test.

Refs #614
2026-10-31 18:28:05 +08:00
DrSmoothl eb119ecb92 feat(qzone): add homepage feeds and share cards
Read accessible Qzone homepage posts and generate their original share cards. Return sharing notices so callers can confirm visibility before sending through the existing message actions.

Include SDK contracts, action discovery, documentation, and regression coverage.

Fixes #609
2026-10-31 18:28:05 +08:00
DrSmoothl 304f3e772f fix(core): preserve private history paging failures
Split larger private history reads into bounded pages and honor the end of history. Surface rejected or stalled pages instead of returning misleading empty or partial results.

Fixes #605
2026-10-31 18:28:05 +08:00
DrSmoothl 26639ffef7 fix(protocol): restore unidirectional friend lookup
Read the unidirectional friend list correctly and preserve service errors instead of returning an empty list for rejected requests.

Fixes #608
2026-10-31 18:28:05 +08:00
DrSmoothl bd14b0a98e fix(protocol): report rejected card deliveries
Surface delivery failures instead of reporting success for rejected image and text cards. Reject responses without a delivery result.

Fixes #611
2026-10-31 18:28:05 +08:00
DrSmoothl 77d883f235 chore(native): update native artifacts
Update the bundled native artifacts.
2026-10-31 18:28:05 +08:00
星陨 bb4443b12d fix(protocol): report incoming group invitations (#612)
Surface group invitations when the inviter is outside the friend list so clients can respond to them.
2026-10-31 18:01:28 +08:00
C₂₂H₂₅NO₆ 947af4b22c feat(onebot): expose birthdays in stranger profiles (#594)
Include available birthday information in stranger profiles and preserve hidden birth years.
2026-10-31 18:01:16 +08:00
DrSmoothl 6b8362e049 chore(ci): clarify issue submission guidance for AI agents
Ask agents to stop creating issues through the CLI and tell users to submit manually through the GitHub web form.
2026-10-27 23:08:46 +08:00
DrSmoothl 8ffd314260 chore(release): v2.2.1 2026-10-27 17:28:27 +08:00
DrSmoothl 8b8a9df894 feat(onebot): read administrator verification message preference
Include verification message reception in administrator permission results. Preserve unavailable states and surface failed reads.

Update SDK contracts, action metadata, documentation and isolated behavior coverage.
2026-10-27 15:13:17 +08:00
DrSmoothl bc3930a2ce feat(onebot): expose administrator permission actions
Expose administrator permission controls through OneBot, the SDK, and MCP.

Document limits and unknown states, and validate public request and result contracts.
2026-10-27 14:58:54 +08:00
DrSmoothl d30cd1ba53 feat(protocol): support per-administrator group permissions
Add permission queries and updates for individual group administrators.

Keep permission changes explicit and surface rejected or unconfirmed updates.
2026-10-27 14:58:47 +08:00
DrSmoothl 05f18614c1 fix(onebot): restore nested chat record forwarding
Restore expansion and cross-chat forwarding for nested chat records that use preview-only cards.

Return an error when nested content cannot be retrieved instead of producing an unusable message.

Refs #589
2026-10-27 09:23:48 +08:00
DrSmoothl 3acd3cd28b fix: resolve dependency security alerts 2026-10-26 10:43:32 +08:00
DrSmoothl dafe2082f1 fix(onebot): preserve public Qzone input semantics
Keep comment and reply text unchanged and support structured input in the debug console. Report malformed input before sending a request.

Refs #587
2026-10-25 23:26:55 +08:00
Qiao 2f1aadffbe feat(onebot): add public Qzone feeds and interactions (#587)
Add public Qzone discovery, pagination, and interactions with SDK and MCP support.
2026-10-25 23:20:14 +08:00
DrSmoothl 1ff2c08765 test(proton): stabilize UTF-8 regression checks
Reduce assertion overhead in existing codec tests while preserving complete byte comparisons and boundary coverage. Keep existing test deadlines and runtime behavior unchanged.
2026-10-25 19:51:44 +08:00
Qiao 4d55608b56 feat(onebot): add Qzone profile read and update actions (#586)
Add actions to read a space name and description and update the current account profile. Preserve omitted fields and support explicit empty values, with matching SDK types, MCP discovery, documentation, and tests.
2026-10-25 19:48:46 +08:00
DrSmoothl 5c9328206f feat: add configurable parallel video uploads
Allow up to four video upload connections while keeping one connection as the default. Preserve existing messaging interfaces and add configuration controls, reliable failure handling, and upload diagnostics.

Closes #569
2026-10-24 22:58:46 +08:00
DrSmoothl 3bd74acb60 chore(release): v2.2.0 2026-10-24 22:21:43 +08:00
DrSmoothl 9bf4b9107b feat(onebot): add structured Qzone feeds and cursor pagination
Expose readable feed content, media and available statistics while preserving existing result fields and callers. Carry continuation state across pages and report invalid or stalled pagination explicitly.
2026-10-24 22:16:06 +08:00
DrSmoothl d95d3bf761 feat(onebot): support replies to Qzone comments
Add threaded text replies while preserving existing comments and image
uploads. Include parent references and update SDK and MCP contracts.
Reject incomplete targets and unsupported reply images before sending.

Fixes #573
2026-10-24 21:54:38 +08:00
叫我最右君 dc2d60e57f Fix spacing of Markdown syntax in release info. (#567) 2026-10-24 21:28:39 +08:00
手瓜一十雪 1172a6bd3d feat 2026-10-24 17:28:58 +08:00
DrSmoothl 8e28bca775 feat(mcp): add compatible protocol workflows and execution services 2026-10-23 21:19:37 +08:00
DrSmoothl 9e7da154ff test(bridge): isolate account watcher tests from platform startup races
Use controlled filesystem events and timers for watcher behavior tests. Preserve native filesystem integration on Windows and Linux, matching account discovery support, and cover the macOS production no-op.
2026-10-23 20:12:49 +08:00
DrSmoothl fa5efcd310 feat(sdk): add media sends, quoted replies, and event waits
Add local media upload-and-send helpers with an optional Node file source
and stage-aware errors. Add explicit quoted replies and cancellable event
waits while preserving existing methods and handler contracts.

Propagate group-file publication failures instead of reporting success.
Cover cancellation, cleanup, signed message IDs, package exports, consumer
types, and real HTTP/WebSocket upload-to-send integration.

Validation: pnpm run ci (6231 tests passed, 9 skipped); SDK package contents
verified with npm pack --dry-run --ignore-scripts.
2026-10-23 19:45:47 +08:00
DrSmoothl 2d659b0ceb feat(mcp): complete action results and invocation examples
Document result shapes and practical calls for all built-in actions,
including prerequisites, streaming workflows and compatibility limits.

Preserve existing interfaces and execution behavior, and verify the
catalog against action validation and representative responses.
2026-10-23 15:45:07 +08:00
DrSmoothl 34a73084e0 feat(mcp): improve agent discovery and execution feedback
Add structured results, optional keyword search and pagination, and runtime information with explicit connection checks. Preserve existing text responses and execution permissions.

Support request cancellation and transfer progress. Verify compatibility with the full CI suite and isolated MCP and HTTP integration tests.
2026-10-23 15:14:18 +08:00
DrSmoothl 9b5ce9b502 feat(sdk): support streaming file transfers 2026-10-23 13:43:35 +08:00
DrSmoothl 166fcd8613 feat(sdk): complete action parameter and result types 2026-10-23 13:23:19 +08:00
DrSmoothl b997de44a2 fix(sdk): restore native ESM imports and action exports 2026-10-23 13:04:33 +08:00
DrSmoothl f8cb15c27b chore(release): v2.1.1 2026-10-22 01:02:02 +08:00
DrSmoothl c5464e48d1 fix(security): update runtime baseline and vulnerable dependencies
Require patched Node.js releases and refresh affected application and build dependencies.

Align installation requirements, startup checks, and release workflows with the security baseline.
2026-10-22 01:00:13 +08:00
DrSmoothl 8fc68c0ec3 chore(release): v2.1.0 2026-10-21 20:28:15 +08:00
DrSmoothl b4ece8671b fix: improve client self-message reporting
Update desktop support for client-sent private and group messages.

Refs #528
2026-10-21 17:42:56 +08:00
DrSmoothl bde7f2805d fix: handle delayed client message availability
Keep self-sent private messages available when their history becomes visible shortly after sending. Preserve account isolation while completing the report.

Refs #528
2026-10-21 17:25:13 +08:00
DrSmoothl 491b531841 feat: support client private-message reporting
Handle confirmed private messages sent from the client and preserve account isolation when sessions change. Surface unavailable messages without reporting incomplete content.

Refs #528.
2026-10-21 16:59:26 +08:00
DrSmoothl 617e7581dd fix: avoid duplicate private self-message reports
Keep repeated confirmations of the same private message from producing duplicate events while preserving distinct messages and stored content.

Refs #528.
2026-10-21 16:59:19 +08:00
DrSmoothl 27120f884a fix: resolve issue #559
Fixes #559.
2026-10-21 15:17:43 +08:00
DrSmoothl 3a4c1eeea2 fix(onebot): deduplicate client group self-message reports
Prevent repeated reports for client-originated group messages while preserving distinct sends and existing private-message behavior.

Cover opt-in reporting, message formats, account isolation, and repeated delivery.

Refs #528
2026-10-21 14:43:37 +08:00
DrSmoothl 5cd4ae61dd feat(webui): add opt-in MaiBot appearance overlay 2026-10-21 13:07:44 +08:00
DrSmoothl 28f64113e7 test(core): resolve startup fixture paths through symlinks
Canonicalize temporary fixture directories before matching build inputs and locating staged updates. Compare the child working directory with its real path so startup tests also pass when the default temporary directory is a symlink.
2026-10-20 14:24:23 +08:00
DrSmoothlandwanqing-last c537311ed1 fix(core): bound forward caches with nested result retention
Keep at most 512 outer results per bridge and retain their bundled nested results as one cache group. Reads refresh the whole group, shared inner results survive while another containing group remains cached, and late sender enrichment cannot resurrect evicted entries.

Collect uploaded and downloaded nested results before publishing a complete cache group. Cover eviction, account isolation, nested retrieval, shared ownership and asynchronous enrichment through the forward API.

Refs #546, #555, #557.

Co-authored-by: wanqing-last <2917149421@qq.com>
2026-10-20 13:50:21 +08:00
DrSmoothlandwanqing-last 9d8df59370 fix(protocol): decode XML forward identities from root attributes
Recognize forward cards with an omitted protocol service ID from the root msg attributes. Decode attribute references once so resource IDs and nested lookup keys survive XML escaping, while preserving ordinary XML when the root declaration is ambiguous.

Refs #547, #556, #558.

Co-authored-by: wanqing-last <2917149421@qq.com>
2026-10-20 13:49:53 +08:00
DrSmoothl 76846f40b1 fix(onebot): resolve voice transcription for signed message IDs
Allow voice transcription results to complete for messages with negative IDs while preserving existing message identities and account isolation.

Report unmatched transcription results accurately and document the signed message ID contract.

Fixes #554
2026-10-20 13:27:40 +08:00
DrSmoothl 79522d949f fix(protocol): recover highway uploads after missing responses
Try another available upload endpoint when a transfer stops responding,
while preserving confirmed progress and the current upload session.
Report unconfirmed transfers clearly and cover recovery and publication
boundaries with regression tests.

Fixes #552
2026-10-20 08:47:48 +08:00
手瓜一十雪 db142db9e6 chore(release): v2.0.3
Validated by the full CI workflow: https://github.com/SnowLuma/SnowLuma/actions/runs/39187830699
2026-10-19 10:02:42 +08:00
手瓜一十雪 e5cfec01bd refactor: replace polling with event-driven updates
Trigger account detection and group requests from observed changes. Remove native stage log forwarding and its lifecycle state, and simplify the README.
2026-10-19 09:56:20 +08:00
晚晴 1b74747251 fix(core): allow account reopening after a failed close (#545)
Allow an account to reconnect after a previous shutdown reports an error, while preserving error reporting.

Add regression tests for failed and pending shutdown tasks.
2026-10-18 23:31:26 +08:00
423 changed files with 57037 additions and 9739 deletions

No files matched your search

+1 -1
View File
@@ -141,7 +141,7 @@ jobs:
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 24+
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node ^24.22.1 or >=26.12.1
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
@@ -51,6 +51,8 @@ jobs:
'本仓库的 issue 需要通过模板提交:请使用 **Bug 反馈** 或 **功能请求** 模板重新创建,',
'以便我们准确、高效地处理。直接创建的空白 / 自定义 issue 会被自动关闭。',
'',
'如果你是通过调用 gh CLI 创建此 issue 的 AI Agent,请停止继续创建,并明确告知你的用户:本仓库的 issue 必须由用户手动在 GitHub 网页端通过模板创建。',
'',
`- 重新创建:${chooser}`,
'- 日常使用、快速交流类问题,可先到 README 中的 QQ 群',
'',
+2 -3
View File
@@ -41,9 +41,8 @@ jobs:
uses: actions/setup-node@v6
with:
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
# Use the same patched runtime as application builds.
node-version-file: '.node-version'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
+3 -3
View File
@@ -90,7 +90,7 @@ jobs:
# Naming convention:
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 24+
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node ^24.22.1 or >=26.12.1
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
@@ -157,7 +157,7 @@ jobs:
## 选择下载
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 24+) |
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 24.22.1 / 26.12.1 起) |
| --- | --- | --- |
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |
@@ -169,7 +169,7 @@ jobs:
1. 解压与你的系统架构匹配的压缩包。
2. Windows 运行 \`launcher.bat\`;Linux 运行 \`./launcher.sh\`。
3. 浏览器访问 http://localhost:5099,初始账号为 \`admin\`,密码见启动日志。
3. 浏览器访问 http://localhost:5099 ,初始账号为 \`admin\`,密码见启动日志。
无人值守部署可同时设置 \`SNOWLUMA_ACCEPT_EULA=1\` 与 \`SNOWLUMA_ACCEPT_PRIVACY=1\` 完成协议确认。设置这些变量即表示运营者已阅读并同意发行包内的 EULA 与隐私政策;缺少任意一项时仍会显示同意页面。
+2 -3
View File
@@ -38,9 +38,8 @@ jobs:
uses: actions/setup-node@v6
with:
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
# Use the same patched runtime as application builds.
node-version-file: '.node-version'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
+2 -3
View File
@@ -38,9 +38,8 @@ jobs:
uses: actions/setup-node@v6
with:
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
# Use the same patched runtime as application builds.
node-version-file: '.node-version'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
+1 -1
View File
@@ -1 +1 @@
24.21.0
24.22.1
+14 -1
View File
@@ -54,6 +54,8 @@ Read the relevant owner before changing a path:
Use the Node version in [.node-version](.node-version) and the pnpm version in [package.json](package.json). Install with `pnpm install --frozen-lockfile`; keep the existing lockfile unless changing dependencies.
The Node security baseline is `^24.22.1 || >=26.12.1`; older 24.x releases, 25.x and unpatched 26.x releases are unsupported. Keep workspace `engines.node` declarations and [the launcher preflight](packages/runtime/check-node-version.cjs) aligned. CI and bundled releases use `.node-version`; raising that pin alone does not upgrade an existing installation's runtime.
Run commands from the repository root:
```sh
@@ -72,12 +74,20 @@ Use focused tests while iterating. Before handing off a code change, run the ful
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
- **SDK packaging:** keep the SDK's `NodeNext` build and explicit `.js` relative imports, including type-only exports. Its package tests compile fresh output and check native Node.js imports, consumer declarations, and complete action-map coverage. The SDK action catalog must match OneBot's executable names; `packages/onebot/tests/sdk-actions.test.ts` checks this without adding a runtime dependency on server code. SDK parameter/result contracts remain independent of server types; keep consumer examples under `packages/sdk/tests/fixtures` aligned with the server parser checks in `packages/onebot/tests/sdk-action-params.test.ts`.
- **SDK streams:** preserve the single-response client methods and use the additive interfaces in [STREAMING.md](packages/sdk/STREAMING.md) for file transfers. Test framing, cancellation, bounded buffering and incomplete transfers in the SDK; `packages/onebot/tests/sdk-streaming.test.ts` checks real adapter/handler round trips in temporary storage without QQ.
- **SDK messaging:** preserve existing string-path and ordinary reply semantics when extending the helpers in [MESSAGING.md](packages/sdk/MESSAGING.md). Filesystem access belongs only in the optional `@snowluma/sdk/node` entry point. Media sends must await upload completion and retain failure context without automatic retries; event waits follow public middleware dispatch and release listeners on every outcome. Keep legacy handler/context types assignable when adding richer SDK-created contexts.
- **MCP agents:** preserve existing text results, business-error envelopes, default search matching and mode gates when extending the tools. Use the server SDK's `serveStdio` entry to support modern discovery and legacy initialization from the same command; test both with freshly compiled output. Cache hints belong only on bundled catalog discovery, never execution or account data. Keep trace metadata out of action parameters and sensitive data out of diagnostics. Protocol compatibility, tracing and the additive agent features are documented in [AGENT_FEATURES.md](packages/mcp/AGENT_FEATURES.md). Use isolated HTTP and MCP transports in tests; local runtime inspection must not query a live account.
- **MCP execution services:** keep background tasks and event connections opt-in. Persist task state before effects, never replay interrupted writes, and finish durable cleanup before draining the protocol on shutdown. Input continuations must retain their original arguments and execute at most once. Event buffers require explicit account binding, bounded storage and visible gaps. Build the bundled message preview through `packages/mcp/scripts/build-message-app.mjs`; loading a preview must not send a message. Test restart, cancellation and legacy compatibility using isolated transports, including the compiled CLI.
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
- **Video uploads:** preserve the single-connection default and the additive global setting in [HIGHWAY_UPLOADS.md](packages/protocol/HIGHWAY_UPLOADS.md). Only video bodies opt into parallel chunks. Confirm every chunk before completion, bound both concurrency and lookahead, and drain outstanding reads and requests before closing the source. Keep retries bounded and backpressure changes visible. Test the actual uploader with isolated transports; passing tests do not prove live throughput.
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
WebUI deployment targets use a reversible presentation overlay. Read [the host appearance contract](packages/webui/INTEGRATIONS.md) before changing it. Keep target validation in `@snowluma/common/webui-target`, implementations in the frontend target registry, and saved preferences separate from effective appearance. Default deployments must not load target assets or host listeners; do not put target-name branches in business pages.
## Implementation rules
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
@@ -86,6 +96,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
- **Preserve signed message IDs.** OneBot `message_id` / `messageId` values generated by [message-id.ts](packages/onebot/src/message-id.ts) are non-zero signed 32-bit integers; negative values are valid. Use `f.messageId()` for action inputs and preserve the value through storage, replies, lookups and result matching. Protocol representations must be converted losslessly at their boundary; changing the sign or generation rule changes existing message identities.
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
@@ -93,7 +104,9 @@ Use focused tests while iterating. Before handing off a code change, run the ful
## Generated files and related changes
OneBot action definitions own validation and catalog metadata. After changing an action name, parameter, result description or execution mode:
OneBot action definitions own validation and catalog metadata. Each bundled action supplies a `returnsSchema` for successful OneBot `data` and at least one `examples` entry with valid parameters and any required identifier sources. Stream schemas describe individual successful frames, not MCP aggregated results. Keep undocumented upstream fields open rather than inventing a structure, and label unsupported or placeholder behavior explicitly.
After changing an action name, parameter, result description/schema, example or execution mode:
1. Update the owning definition in `packages/onebot/src/actions` and its tests.
2. Run `pnpm --filter @snowluma/mcp gen`.
+1 -1
View File
@@ -58,7 +58,7 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
### 系统要求
- **Node.js 24+**
- **Node.js 24.22.1(24 系列),或 26.12.1 及更新版本**;开发和构建使用 [`.node-version`](.node-version) 固定的版本。
- **pnpm 11.25.0**(项目通过 `packageManager` 与 CI 统一版本)
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
+1 -2
View File
@@ -53,8 +53,7 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
在「设置 → 关于 → 软件更新」下载新版本,再点「重启更新」。文件优先暂存于系统临时目录,不可用时使用安装目录的 `tmp/update`,下次启动时替换并清理,配置、日志与消息数据保留。更新沿用当前 Node.js;容器部署请更新镜像。
版本号遵循 [SemVer](https://semver.org/),在线更新仅安装正式版;构建元数据不影响版本排序。
账号识别由登录数据库的文件变化、进程和登录事件或手动操作触发,不做周期探测。未载入的 QQ 进程也不会持续调用 Windows Restart Manager;需要重查时可点击 WebUI 进程行的刷新/重连。
## 接入与文档
+4 -4
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "2.0.2",
"version": "2.3.1",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -35,8 +35,8 @@
"devDependencies": {
"@eslint/js": "^10.0.1",
"@stylistic/eslint-plugin": "5.10.0",
"@vitest/coverage-istanbul": "4.1.4",
"@vitest/coverage-v8": "^4.1.4",
"@vitest/coverage-istanbul": "4.1.12",
"@vitest/coverage-v8": "4.1.12",
"cross-env": "^10.1.0",
"eslint": "^10.2.0",
"eslint-config-prettier": "10.1.8",
@@ -50,7 +50,7 @@
},
"packageManager": "pnpm@11.25.0",
"engines": {
"node": ">=24",
"node": "^24.22.1 || >=26.12.1",
"pnpm": "11.25.0"
}
}
+3 -3
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "2.0.2",
"version": "2.3.1",
"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).",
@@ -61,9 +61,9 @@
"@types/node": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
"vitest": "4.1.12"
},
"engines": {
"node": ">=24"
"node": "^24.22.1 || >=26.12.1"
}
}
+59 -34
View File
@@ -14,13 +14,15 @@ import {
import { PipeWatcher } from './pipe-watcher';
import { createProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { QqHookClient } from './qq-hook-client';
import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account';
import {
detectAccountLoginsForPids,
watchAccountChangesForPids,
type AccountLoginState,
} from './qq-account';
import type { HookProcessAccount, HookProcessInfo } from './types';
const AUTO_LOAD_MAX_ATTEMPTS = 3;
const DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS = 5000;
type AutoLoadAttempt = {
attempts: number;
inFlight: boolean;
@@ -61,9 +63,8 @@ export type HookManagerDeps = {
* the HOME it actually runs under (a container can give every QQ instance
* its own). Defaults to reading QQ's own account data. */
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
/** How often the watcher re-probes the account label of each process, in
* milliseconds. Defaults to `DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS`. */
accountReprobeIntervalMs?: number;
/** Subscribe to login database changes. Returns the subscription cleanup. */
watchAccounts?: (pids: readonly number[], onChange: () => void) => () => void;
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state.
@@ -106,7 +107,7 @@ export class HookManager {
private readonly ownsPipeWatcher: boolean;
private readonly enumerator: ProcessEnumerator;
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
private readonly accountReprobeIntervalMs: number;
private readonly watchAccounts: NonNullable<HookManagerDeps['watchAccounts']>;
private readonly autoLoadOnDiscovery: boolean;
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
@@ -116,7 +117,8 @@ export class HookManager {
private accounts = new Map<number, HookProcessAccount>();
private accountProbe: Promise<void> | null = null;
private nextAccountProbeAt = 0;
private accountsDirty = true;
private stopWatchingAccounts?: () => void;
private lastAccountProbeFailure = '';
private disposed = false;
@@ -133,8 +135,9 @@ export class HookManager {
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids;
this.accountReprobeIntervalMs =
deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS;
this.watchAccounts =
deps.watchAccounts ??
((pids, onChange) => watchAccountChangesForPids(pids, onChange, this.log));
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
this.enumerator = createProcessEnumerator({
@@ -186,6 +189,7 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
this.invalidateAccounts();
await session.load();
this.pipeWatcher.wake();
await this.refreshAccounts();
@@ -197,6 +201,7 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
this.invalidateAccounts();
await session.unload();
await this.refreshAccounts();
return this.processInfo(session);
@@ -206,6 +211,8 @@ export class HookManager {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
this.updateAccountWatcher();
this.invalidateAccounts();
await session.refresh();
await this.refreshAccounts();
return this.processInfo(session);
@@ -217,6 +224,7 @@ export class HookManager {
}
this.disposed = true;
this.stopWatchingAccounts?.();
for (const session of this.sessions.values()) {
session.dispose();
@@ -238,45 +246,52 @@ export class HookManager {
return { ...session.toInfo(), account: this.accounts.get(session.pid) ?? null };
}
private invalidateAccounts(): void {
this.accountsDirty = true;
}
private updateAccountWatcher(): void {
this.stopWatchingAccounts?.();
this.stopWatchingAccounts = this.watchAccounts([...this.sessions.keys()], () => {
this.invalidateAccounts();
void this.refreshAccounts();
});
}
/** REST, watcher ticks and login reconciliation share the same account snapshot. */
private async refreshAccounts(): Promise<void> {
if (this.disposed) {
if (this.disposed || this.sessions.size === 0) {
return;
}
if (this.accountProbe) {
await this.accountProbe;
// Process discovery invalidates the snapshot while a read is in flight.
if (this.nextAccountProbeAt === 0) {
await this.refreshAccounts();
}
return;
}
if (Date.now() < this.nextAccountProbeAt || this.sessions.size === 0) {
if (!this.accountsDirty) {
return;
}
this.nextAccountProbeAt = Date.now() + this.accountReprobeIntervalMs;
this.accountProbe = runWithTraceRequest(() => this.readAccounts()).finally(() => {
this.accountProbe = runWithTraceRequest(async () => {
// All callers await the replacement read too if a lifecycle change
// invalidates an in-flight result.
do {
this.accountsDirty = false;
await this.readAccounts();
} while (!this.disposed && this.sessions.size > 0 && this.accountsDirty);
}).finally(() => {
this.accountProbe = null;
});
await this.accountProbe;
}
private async readAccounts(): Promise<void> {
const sessions = new Map(this.sessions);
const accounts = new Map<number, HookProcessAccount>();
try {
for (const state of await this.detectAccounts([...sessions.keys()])) {
if (
state.pid !== null &&
sessions.has(state.pid) &&
this.sessions.get(state.pid) === sessions.get(state.pid)
) {
for (const state of await this.detectAccounts([...this.sessions.keys()])) {
if (state.pid !== null && this.sessions.has(state.pid)) {
accounts.set(state.pid, { uin: state.uin, nickname: state.nickname });
}
}
@@ -291,7 +306,7 @@ export class HookManager {
}
}
if (this.disposed) {
if (this.disposed || this.accountsDirty) {
return;
}
@@ -364,6 +379,7 @@ export class HookManager {
const session = this.sessions.get(pid);
if (session) {
this.invalidateAccounts();
session.onPipeUp();
}
});
@@ -375,6 +391,7 @@ export class HookManager {
const session = this.sessions.get(pid);
if (session) {
this.invalidateAccounts();
session.onPipeDown();
}
});
@@ -570,7 +587,10 @@ export class HookManager {
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
// Account switches can keep the same 'online' status.
this.invalidateAccounts();
this.bridgeManager.onHookLogin(pid, uin, sender);
this.notifySessionsChanged();
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) {
@@ -580,20 +600,25 @@ export class HookManager {
session.on('receive-health-changed', (healthy: boolean) => {
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
});
// status-changed fires on EVERY internal status mutation, including the
// ones reached via login / disconnected / refresh — subscribing here
// alone covers every transition the WebUI processes view cares about.
session.on('status-changed', () => {
let previousStatus = session.status;
session.on('status-changed', (status) => {
if (previousStatus === 'online' && status !== 'online') {
this.invalidateAccounts();
}
previousStatus = status;
this.notifySessionsChanged();
});
session.on('disposed', () => {
this.sessions.delete(pid);
this.accounts.delete(pid);
this.nextAccountProbeAt = 0;
this.updateAccountWatcher();
this.invalidateAccounts();
});
this.sessions.set(pid, session);
this.nextAccountProbeAt = 0;
this.updateAccountWatcher();
this.invalidateAccounts();
return session;
}
+66 -9
View File
@@ -88,6 +88,7 @@ export class HookSession extends EventEmitter {
private _status: HookProcessStatus = 'available';
private _error = '';
private runtimeFailure = '';
private _uin = '0';
private _method = '';
private _name = '';
@@ -500,6 +501,11 @@ export class HookSession extends EventEmitter {
* defaults to the current `loggedIn`; callers that just tore the client
* down pass the value captured *before* teardown (teardown clears it). */
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
if (this.runtimeFailure) {
this.setStatus('error', this.runtimeFailure);
return;
}
this.setStatus(
statusFor({
injected: this.injected,
@@ -559,7 +565,7 @@ export class HookSession extends EventEmitter {
this.pid,
renderParamsVerbose(this.toInfo()),
]);
this.tearDownClient();
this.tearDownClient(true);
this.applyStatus(wasLoggedIn);
try {
@@ -607,6 +613,7 @@ export class HookSession extends EventEmitter {
}
if (!this.client) {
this.runtimeFailure = '';
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client, (healthy) =>
this.setOutboundHealthy(healthy),
@@ -623,6 +630,11 @@ export class HookSession extends EventEmitter {
try {
await client.connectAll({ recv: true });
if (this.runtimeFailure) {
throw new Error(this.runtimeFailure);
}
this.connected = true;
const loginState = client.getLoginState();
@@ -650,7 +662,7 @@ export class HookSession extends EventEmitter {
this._error = errorMessage(error);
// Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient();
this.tearDownClient(true);
this.applyStatus(false, this._error);
this.log.trace(() => [
'hook_session_connect_terminal pid=%d outcome=failed reason=connect_failed error=%j state=%s elapsedMs=%d',
@@ -664,11 +676,28 @@ export class HookSession extends EventEmitter {
}
private bindClient(client: QqHookClient): void {
client.on('runtimeError', (error) => {
if (this.client !== client || this.disposed) {
return;
}
const wasLoggedIn = this.loggedIn;
this.runtimeFailure = errorMessage(error);
this.loggedIn = false;
this.stopLoginReconcile();
this.resetReceiveWatch();
this.applyStatus(wasLoggedIn);
this.log.error('QQ runtime unavailable: PID=%d err=%s', this.pid, this.runtimeFailure);
if (wasLoggedIn) {
this.emit('disconnected', true);
}
});
client.on('packet', (packet) => this.handlePacket(packet));
client.on('loginState', (state) => this.handleLoginState(state));
client.on('error', (error) => {
const msg = errorMessage(error);
this._error = msg;
this._error = this.runtimeFailure || msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
});
client.on('close', () => {
@@ -698,7 +727,7 @@ export class HookSession extends EventEmitter {
});
}
private tearDownClient(): void {
private tearDownClient(preserveRuntimeFailure = false): void {
this.stopLoginReconcile();
this.resetReceiveWatch();
const client = this.client;
@@ -714,6 +743,11 @@ export class HookSession extends EventEmitter {
}
this.client = null;
if (!preserveRuntimeFailure) {
this.runtimeFailure = '';
}
this.sender = null;
this.bound = false;
this.connected = false;
@@ -723,6 +757,10 @@ export class HookSession extends EventEmitter {
}
private handleLoginState(state: QqHookLoginState): void {
if (this.runtimeFailure) {
return;
}
const wasLoggedIn = this.loggedIn;
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
@@ -800,7 +838,7 @@ export class HookSession extends EventEmitter {
// reconciliation, but never synthesize online state from the detection.
private startLoginReconcile(): void {
if (this.loginReconcileTimer || this.disposed) {
if (this.loginReconcileTimer || this.disposed || this.runtimeFailure) {
return;
}
@@ -829,7 +867,7 @@ export class HookSession extends EventEmitter {
const client = this.client;
if (this.disposed || !client || !this.connected || this.loggedIn) {
if (this.disposed || !client || !this.connected || this.loggedIn || this.runtimeFailure) {
this.stopLoginReconcile();
return;
}
@@ -861,7 +899,13 @@ export class HookSession extends EventEmitter {
}
// A reconnect owns a new client; an older read cannot supply its identity.
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) {
if (
this.client !== client ||
this.disposed ||
!this.connected ||
this.loggedIn ||
this.runtimeFailure
) {
return;
}
@@ -902,7 +946,8 @@ export class HookSession extends EventEmitter {
this.client !== client ||
this.disposed ||
!this.connected ||
this.loggedIn
this.loggedIn ||
this.runtimeFailure
) {
return;
}
@@ -911,7 +956,7 @@ export class HookSession extends EventEmitter {
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
if (this.client !== client || this.disposed) {
if (this.client !== client || this.disposed || this.runtimeFailure) {
return;
}
@@ -957,6 +1002,17 @@ export class HookSession extends EventEmitter {
return;
}
if (
packet.source === 'client-message' &&
(!isRealUin(packet.uin) || packet.uin !== this._uin)
) {
this.log.warn(
'Client message receipt belongs to an inactive account: PID=%d',
this.pid,
);
return;
}
const uin = packet.uin || this._uin;
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
// receive hook is alive. Attribute that evidence to the current epoch
@@ -986,6 +1042,7 @@ export class HookSession extends EventEmitter {
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
...(packet.source ? { source: packet.source } : {}),
body: Buffer.from(packet.body),
});
}
+1
View File
@@ -12,6 +12,7 @@ export {
type LoginDbFailure,
} from './login-db';
export { accountDirName, loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
export { watchAccountChangesForPids } from './watch';
export {
decryptDatabase,
detectAlgorithm,
+115
View File
@@ -0,0 +1,115 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { watch, type FSWatcher } from 'node:fs';
import path from 'node:path';
import { loginDbPaths, qqDataRootsForPid } from './paths';
export function watchAccountChangesForPids(
pids: readonly number[],
onChange: () => void,
log: Logger = createLogger('QqAccount'),
): () => void {
const roots = new Set<string>();
for (const pid of pids) {
try {
for (const root of qqDataRootsForPid(pid)) {
roots.add(root);
}
} catch (error) {
log.warn('account watch root failed: PID=%d err=%s', pid, errorMessage(error));
}
}
return watchAccountFiles([...roots].flatMap(loginDbPaths), onChange, log);
}
/** Watch directories so replacing login.db or recreating its WAL keeps working. */
export function watchAccountFiles(
dbPaths: readonly string[],
onChange: () => void,
log: Logger = createLogger('QqAccount'),
): () => void {
const watchers = new Map<string, FSWatcher>();
let timer: NodeJS.Timeout | undefined;
const changed = () => {
clearTimeout(timer);
timer = setTimeout(() => {
timer = undefined;
onChange();
}, 250);
timer.unref();
};
const observe = (dbPath: string) => {
watchers.get(dbPath)?.close();
watchers.delete(dbPath);
const dbDirectory = path.dirname(dbPath);
let directory = dbDirectory;
for (;;) {
const target = path.relative(directory, dbPath).split(path.sep)[0]!;
try {
const watcher = watch(directory, { persistent: false }, (_event, filename) => {
if (
watchers.get(dbPath) !== watcher ||
(filename !== null &&
filename !== target &&
!(directory === dbDirectory && filename === `${target}-wal`))
) {
return;
}
// QQ may create its data directories after process discovery.
if (directory !== dbDirectory) {
observe(dbPath);
}
changed();
});
watcher.on('error', (error) => {
if (watchers.get(dbPath) !== watcher) {
return;
}
watcher.close();
watchers.delete(dbPath);
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
});
watchers.set(dbPath, watcher);
return;
} catch (error) {
const parent = path.dirname(directory);
if (
error instanceof Error &&
'code' in error &&
error.code === 'ENOENT' &&
parent !== directory
) {
directory = parent;
continue;
}
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
return;
}
}
};
for (const dbPath of new Set(dbPaths)) {
observe(dbPath);
}
return () => {
clearTimeout(timer);
for (const watcher of watchers.values()) {
watcher.close();
}
watchers.clear();
};
}
+101 -27
View File
@@ -7,6 +7,7 @@ import {
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import { isRealUin } from '@snowluma/common/uin';
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import path from 'path';
@@ -38,6 +39,8 @@ export enum PipeOp {
recvPacket = 6,
loginState = 7,
loginIdentityHint = 17,
clientMessageReceipt = 21,
clientMessageState = 22,
}
const PipeFlagWantReply = 1 << 0;
@@ -55,6 +58,7 @@ export interface QqHookPacket {
cmd: string;
uin: string;
body: Buffer;
source?: 'client-message';
}
export interface QqHookHello {
@@ -559,6 +563,7 @@ export class QqHookClient extends EventEmitter {
private recvHelloResolver: Deferred<QqHookHello> | null = null;
private controlWriteChain: Promise<unknown> = Promise.resolve();
private closed = false;
private runtimeFailure: Error | null = null;
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
private readonly loginWaiters = new Set<Deferred<QqHookLoginState>>();
@@ -611,10 +616,7 @@ export class QqHookClient extends EventEmitter {
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
await this.connect();
if (this.closed) {
throw new Error('qq_hook client is closed');
}
this.assertUsable();
if (this.loginState.loggedIn) {
return this.getLoginState();
@@ -688,9 +690,7 @@ export class QqHookClient extends EventEmitter {
}
async connect(): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
this.assertUsable();
if (this.controlSocket && this.controlHello) {
return this.controlHello;
@@ -710,9 +710,7 @@ export class QqHookClient extends EventEmitter {
}
async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
this.assertUsable();
if (typeof onPacket === 'function') {
this.on('packet', onPacket);
@@ -992,6 +990,16 @@ export class QqHookClient extends EventEmitter {
this.controlWriteChain = Promise.resolve();
}
private assertUsable(): void {
if (this.runtimeFailure) {
throw this.runtimeFailure;
}
if (this.closed) {
throw new Error('qq_hook client is closed');
}
}
private rejectLoginWaiters(error: Error): void {
for (const waiter of this.loginWaiters) {
waiter.reject(error);
@@ -1029,26 +1037,28 @@ export class QqHookClient extends EventEmitter {
const socket = this.controlSocket;
if (!socket || socket.destroyed) {
return Promise.reject(new Error('control pipe is not connected'));
return Promise.reject(
this.runtimeFailure ?? new Error('control pipe is not connected'),
);
}
const writePromise = this.controlWriteChain.then(
() =>
new Promise<void>((resolve, reject) => {
if (!this.controlSocket || this.controlSocket.destroyed) {
reject(new Error('control pipe is not connected'));
return;
}
const writePromise = this.controlWriteChain.then(() => {
this.assertUsable();
socket.write(payload, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
}),
);
if (this.controlSocket !== socket || socket.destroyed) {
throw new Error('control pipe is not connected');
}
return new Promise<void>((resolve, reject) => {
socket.write(payload, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
});
this.controlWriteChain = writePromise.catch(() => {});
return writePromise;
}
@@ -1128,6 +1138,11 @@ export class QqHookClient extends EventEmitter {
),
);
if (this.closed || this.runtimeFailure) {
socket.destroy();
this.assertUsable();
}
if (kind === 'control') {
this.controlSocket = socket;
} else {
@@ -1142,6 +1157,8 @@ export class QqHookClient extends EventEmitter {
phase = 'hello';
const hello = await this.waitForHello(kind === 'recv');
this.assertUsable();
if (kind === 'control') {
this.controlHello = hello;
} else {
@@ -1297,6 +1314,10 @@ export class QqHookClient extends EventEmitter {
}
private handleControlFrame(frame: PipeFrame): void {
if (this.runtimeFailure) {
return;
}
if (frame.op === PipeOp.hello) {
this.resolveHello(frame, false);
return;
@@ -1342,6 +1363,16 @@ export class QqHookClient extends EventEmitter {
frame.status,
frame.requestId,
);
if (frame.requestId === 0 && frame.cmd === 'runtime') {
this.runtimeFailure = error;
this.rejectControlPending(error);
this.rejectRecvPending(error);
this.rejectLoginWaiters(error);
this.emit('runtimeError', error);
return;
}
const ack = this.pendingAcks.get(frame.requestId);
if (ack) {
@@ -1359,6 +1390,10 @@ export class QqHookClient extends EventEmitter {
}
private handleRecvFrame(frame: PipeFrame): void {
if (this.runtimeFailure) {
return;
}
if (frame.op === PipeOp.hello) {
this.resolveHello(frame, true);
return;
@@ -1369,6 +1404,45 @@ export class QqHookClient extends EventEmitter {
return;
}
if (frame.op === PipeOp.clientMessageState) {
if (frame.status === 1) {
runtimeLog.debug('Client private-message reporting is available: PID=%d', this.pid);
} else {
runtimeLog.warn(
'Client private-message reporting is unavailable: PID=%d status=%d%s',
this.pid,
frame.status,
frame.value0 === 0n ? '' : ` reason=${frame.value0}`,
);
}
return;
}
if (frame.op === PipeOp.clientMessageReceipt) {
if (
frame.cmd !== '' ||
frame.requestId !== 0 ||
frame.flags !== 0 ||
frame.value0 <= 0n ||
frame.value0 > BigInt(Number.MAX_SAFE_INTEGER) ||
!isRealUin(frame.msg)
) {
runtimeLog.warn('Invalid client message receipt: PID=%d', this.pid);
return;
}
this.emit('packet', {
seq: Number(frame.value0),
error: frame.status,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: frame.msg,
body: Buffer.from(frame.body),
source: 'client-message',
} satisfies QqHookPacket);
return;
}
if (frame.op !== PipeOp.recvPacket) {
return;
}
@@ -24,6 +24,8 @@ interface Harness {
setLivePipes: (next: number[]) => void;
onSessionsChanged: ReturnType<typeof vi.fn>;
clientFactory: ReturnType<typeof vi.fn>;
notifyAccountChange: () => void;
watchAccounts: ReturnType<typeof vi.fn>;
}
function makeManager(
@@ -31,7 +33,6 @@ function makeManager(
processes?: number[];
livePipes?: number[];
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
accountReprobeIntervalMs?: number;
} = {},
): Harness {
let pids = opts.processes ?? [];
@@ -64,6 +65,13 @@ function makeManager(
onPidReceiveHealthChanged: vi.fn(),
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
const onSessionsChanged = vi.fn();
let accountChanged = () => {};
const watchAccounts = vi.fn((_pids: readonly number[], onChange: () => void) => {
accountChanged = onChange;
return vi.fn();
});
const manager = new HookManager({
bridgeManager,
pipeWatcher,
@@ -77,7 +85,7 @@ function makeManager(
makeClient: clientFactory,
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: opts.detectAccounts ?? (async () => []),
accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
watchAccounts,
onSessionsChanged,
});
return {
@@ -86,6 +94,8 @@ function makeManager(
bridgeManager,
onSessionsChanged,
clientFactory,
notifyAccountChange: () => accountChanged(),
watchAccounts,
setProcesses: (next) => {
pids = next;
},
@@ -198,6 +208,7 @@ describe('HookManager.onSessionsChanged', () => {
}),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: async () => [],
watchAccounts: () => () => {},
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
@@ -210,7 +221,111 @@ describe('HookManager.onSessionsChanged', () => {
});
});
describe('HookManager periodic account re-probe', () => {
describe('HookManager account re-probe', () => {
it('reuses the account snapshot across ticks and REST reads while all sessions are online (#549)', async () => {
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
]);
const ctx = makeManager({
processes: [4242, 5151],
livePipes: [4242, 5151],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
for (const [index, uin] of ['10001', '10002'].entries()) {
const client = ctx.clientFactory.mock.results[index]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin, uinNumber: BigInt(uin) });
}
const initial = await ctx.manager.listProcesses();
expect(initial.map((info) => info.status)).toEqual(['online', 'online']);
const baseline = detectAccounts.mock.calls.length;
ctx.onSessionsChanged.mockClear();
const startedAt = Date.now();
for (let tick = 1; tick <= 10; tick++) {
now.mockReturnValue(startedAt + tick * 6000);
await ctx.pipeWatcher.tickNow();
expect(await ctx.manager.listProcesses()).toEqual(initial);
}
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it.each(['loadProcess', 'unloadProcess', 'refreshProcess'] as const)(
'refreshes account labels on %s even within the probe interval',
async (operation) => {
let nickname = 'Alice';
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => [{ uin: '10001', uid: 'u_a', nickname, pid: 4242 }],
});
try {
expect((await ctx.manager.listProcesses())[0]!.account?.nickname).toBe('Alice');
nickname = 'Updated';
expect((await ctx.manager[operation](4242)).account?.nickname).toBe('Updated');
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
},
);
it('discards an in-flight account result when an online process switches accounts', async () => {
const stale = Promise.withResolvers<AccountLoginState[]>();
const fresh = Promise.withResolvers<AccountLoginState[]>();
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
]);
const ctx = makeManager({
processes: [4242],
livePipes: [4242],
detectAccounts,
});
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
detectAccounts.mockImplementationOnce(() => stale.promise);
detectAccounts.mockImplementationOnce(() => fresh.promise);
const refreshing = ctx.manager.refreshProcess(4242);
await flush();
const baseline = detectAccounts.mock.calls.length;
client.emit('loginState', { loggedIn: true, uin: '10002', uinNumber: 10002n });
const snapshot = ctx.manager.listProcesses();
await flush();
ctx.onSessionsChanged.mockClear();
stale.resolve([{ uin: '10003', uid: 'u_c', nickname: 'Stale', pid: 4242 }]);
await flush();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect(detectAccounts).toHaveBeenCalledTimes(baseline + 1);
fresh.resolve([{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }]);
expect((await snapshot)[0]!.account).toEqual({ uin: '10002', nickname: 'Bob' });
expect((await refreshing).account).toEqual({ uin: '10002', nickname: 'Bob' });
} finally {
stale.resolve([]);
fresh.resolve([]);
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('shares one account probe between watcher ticks and concurrent snapshots', async () => {
const probe = Promise.withResolvers<AccountLoginState[]>();
const detectAccounts = vi.fn(() => probe.promise);
@@ -234,6 +349,86 @@ describe('HookManager periodic account re-probe', () => {
}
});
it.each(['pipe-down', 'client-close', 'logout'] as const)(
're-probes after %s and observes later login data changes',
async (event) => {
let accounts: AccountLoginState[] = [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
];
const detectAccounts = vi.fn(async () => accounts);
const ctx = makeManager({
processes: [4242],
livePipes: [4242],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
accounts = [];
if (event === 'pipe-down') {
ctx.setLivePipes([]);
await ctx.pipeWatcher.tickNow();
} else if (event === 'client-close') {
client.emit('close');
} else {
client.emit('loginState', { loggedIn: false, uin: '0', uinNumber: 0n });
}
await flush();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
accounts = [{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }];
now.mockReturnValue(Date.now() + 6000);
ctx.notifyAccountChange();
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses())[0]!.account?.uin).toBe('10002');
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
},
);
it('re-probes when another process appears and when it exits', async () => {
let nickname = 'Alice';
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname, pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
]);
const ctx = makeManager({ processes: [4242], livePipes: [4242], detectAccounts });
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
nickname = 'Updated';
ctx.setProcesses([4242, 5151]);
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses()).map((info) => info.account)).toEqual([
{ uin: '10001', nickname: 'Updated' },
{ uin: '10002', nickname: 'Bob' },
]);
nickname = 'Final';
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
const list = await ctx.manager.listProcesses();
expect(list).toHaveLength(1);
expect(list[0]!.account?.nickname).toBe('Final');
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('keeps all process labels when an operation reads just one process', async () => {
const accounts: AccountLoginState[] = [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
@@ -246,8 +441,8 @@ describe('HookManager periodic account re-probe', () => {
try {
await ctx.manager.listProcesses();
const baseline = detectAccounts.mock.calls.length;
expect((await ctx.manager.refreshProcess(4242)).account?.uin).toBe('10001');
const baseline = detectAccounts.mock.calls.length;
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await flush();
@@ -282,17 +477,13 @@ describe('HookManager periodic account re-probe', () => {
}
});
// A login can happen with no hook edge at all (QQ signs in after SnowLuma
// started, or before the hook was injected), so no session status changes
// and nothing pushes a fresh processes snapshot. These cover the watcher
// pass that re-reads the account labels and invalidates when they move.
// Login database changes can reveal login before the hook is loaded.
it('publishes when a process gains an account label', async () => {
let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }];
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
@@ -300,7 +491,7 @@ describe('HookManager periodic account re-probe', () => {
// QQ finished signing in: the account's nt_msg.db is now held by 4242.
accounts = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }];
await ctx.pipeWatcher.tickNow();
ctx.notifyAccountChange();
await flush();
await flush();
@@ -317,14 +508,12 @@ describe('HookManager periodic account re-probe', () => {
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
ctx.notifyAccountChange();
await flush();
await flush();
@@ -340,7 +529,6 @@ describe('HookManager periodic account re-probe', () => {
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
@@ -352,7 +540,7 @@ describe('HookManager periodic account re-probe', () => {
{ uin: '1', uid: 'u1', nickname: 'A', pid: null },
{ uin: '2', uid: 'u2', nickname: 'B', pid: null },
];
await ctx.pipeWatcher.tickNow();
ctx.notifyAccountChange();
await flush();
await flush();
@@ -361,24 +549,89 @@ describe('HookManager periodic account re-probe', () => {
ctx.manager.dispose();
});
it('throttles the probe to the configured interval', async () => {
it('does not poll unlabelled, unloaded processes even after the old interval expires', async () => {
const detectAccounts = vi.fn(async () => [] as AccountLoginState[]);
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 60_000,
});
await ctx.pipeWatcher.start();
await flush();
const baseline = detectAccounts.mock.calls.length;
const now = vi.spyOn(Date, 'now');
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
await flush();
try {
await ctx.manager.listProcesses();
const baseline = detectAccounts.mock.calls.length;
const startedAt = Date.now();
expect(detectAccounts.mock.calls.length).toBe(baseline);
for (let tick = 1; tick <= 10; tick++) {
now.mockReturnValue(startedAt + tick * 6000);
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
}
ctx.manager.dispose();
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('does not re-probe a mixed set of online and unloaded processes', async () => {
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
]);
const ctx = makeManager({
processes: [4242, 5151],
livePipes: [4242],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
expect((await ctx.manager.listProcesses()).map((info) => info.status)).toEqual([
'online',
'available',
]);
const baseline = detectAccounts.mock.calls.length;
now.mockReturnValue(Date.now() + 60_000);
await ctx.pipeWatcher.tickNow();
await ctx.manager.listProcesses();
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('releases file subscriptions when the process set changes and the manager stops', async () => {
const ctx = makeManager({ processes: [4242] });
try {
await ctx.pipeWatcher.start();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242], expect.any(Function));
const firstStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.setProcesses([4242, 5151]);
await ctx.pipeWatcher.tickNow();
expect(firstStop).toHaveBeenCalledOnce();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242, 5151], expect.any(Function));
const secondStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.setProcesses([5151]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(secondStop).toHaveBeenCalledOnce();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([5151], expect.any(Function));
const finalStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.manager.dispose();
expect(finalStop).toHaveBeenCalledOnce();
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('keeps working when detection fails, and reports the failure once', async () => {
@@ -387,7 +640,6 @@ describe('HookManager periodic account re-probe', () => {
detectAccounts: async () => {
throw new Error('login.db unreadable');
},
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
@@ -80,6 +80,7 @@ function makeManager(opts: {
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// Detection reads QQ's own data directories; tests stay off the host.
detectAccounts: opts.detectAccounts ?? (async () => []),
watchAccounts: () => () => {},
});
return {
manager,
@@ -72,6 +72,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
autoLoadOnDiscovery: true,
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
detectAccounts: async () => [],
watchAccounts: () => () => {},
});
// Initial discovery + first connect.
+114
View File
@@ -30,6 +30,7 @@ class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
shouldFailConnect = false;
runtimeErrorOnConnect = false;
nativeReadyOnIdentityHint = false;
identityHintFailures = 0;
sendError: Error | null = null;
@@ -38,6 +39,10 @@ class FakeClient extends EventEmitter {
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.runtimeErrorOnConnect) {
this.emit('runtimeError', new Error('QQ service unavailable'));
}
if (this.shouldFailConnect) {
throw new Error('connect failed');
}
@@ -102,6 +107,7 @@ function makeSession(
pid?: number;
pipeLive?: boolean;
clientFailsConnect?: boolean;
runtimeErrorOnConnect?: boolean;
onPacket?: PacketSink;
detectLoginUin?: (pid: number) => Promise<string | null>;
nativeReadyOnIdentityHint?: boolean;
@@ -123,6 +129,7 @@ function makeSession(
injector,
makeClient: () => {
const c = new FakeClient();
c.runtimeErrorOnConnect = opts.runtimeErrorOnConnect ?? false;
if (opts.clientFailsConnect) {
c.shouldFailConnect = true;
@@ -152,6 +159,77 @@ function makeSession(
const flush = () => new Promise<void>((r) => setImmediate(r));
describe('HookSession runtime failure', () => {
it('retains an initialization error instead of waiting for login', async () => {
const { session } = makeSession({ pipeLive: true, runtimeErrorOnConnect: true });
await session.load();
session.onPipeUp();
await flush();
expect(session.toInfo()).toMatchObject({
status: 'error',
error: 'QQ service unavailable',
connected: false,
});
session.dispose();
});
it('keeps a late runtime error visible across refresh and login snapshots', async () => {
const { session, currentClient, setPipeLive } = makeSession({ pipeLive: true });
const disconnect = vi.fn();
session.on('disconnected', disconnect);
await session.load();
session.onPipeUp();
await flush();
currentClient().fireLogin('10001');
currentClient().emit('runtimeError', new Error('QQ service unavailable'));
currentClient().emit('error', new Error('connection closed'));
expect(session.error).toBe('QQ service unavailable');
currentClient().fireLogin('10001');
await session.refresh();
expect(session.toInfo()).toMatchObject({
status: 'error',
error: 'QQ service unavailable',
loggedIn: false,
});
setPipeLive(false);
await session.refresh();
expect(disconnect).toHaveBeenCalledExactlyOnceWith(true);
setPipeLive(true);
await session.refresh();
currentClient().fireLogin('10001');
expect(session.toInfo()).toMatchObject({ status: 'online', loggedIn: true, error: '' });
session.dispose();
});
it('retains the failure when the pipe closes and discards an in-flight login lookup', async () => {
let resolveLogin!: (uin: string) => void;
const { session, currentClient, setPipeLive } = makeSession({
pipeLive: true,
detectLoginUin: () =>
new Promise((resolve) => {
resolveLogin = resolve;
}),
});
await session.load();
session.onPipeUp();
await flush();
const client = currentClient();
client.emit('runtimeError', new Error('QQ service unavailable'));
resolveLogin('10001');
await flush();
expect(client.loginIdentityHints).toEqual([]);
setPipeLive(false);
await session.refresh();
expect(session.toInfo()).toMatchObject({
status: 'error',
error: 'QQ service unavailable',
loggedIn: false,
connected: false,
});
session.dispose();
});
});
describe('HookSession — runtime TRACE', () => {
it('records injection and existing-pipe load branches with unique terminals', async () => {
const entries: LogEntry[] = [];
@@ -929,6 +1007,42 @@ describe('HookSession — pipe-down must not clobber a settled error', () => {
});
describe('HookSession — packet forwarding', () => {
it('forwards client receipts only for the active account without changing direction', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
const receipt: QqHookPacket = {
seq: 42,
error: 0,
cmd: 'ClientMessageReceipt',
uin: '10001',
source: 'client-message',
body: Buffer.from([1, 2, 3]),
};
for (const uin of ['', '0', '20002']) {
ctx.currentClient().firePacket({ ...receipt, uin });
}
expect(onPacket).not.toHaveBeenCalled();
ctx.currentClient().firePacket(receipt);
expect(onPacket).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
pid: 1234,
uin: '10001',
source: 'client-message',
fromClient: false,
}),
);
ctx.currentClient().fireLogin('20002');
ctx.currentClient().firePacket(receipt);
expect(onPacket).toHaveBeenCalledOnce();
await ctx.session.dispose();
});
// These tests cover the field-rename + filter logic that used to live
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
// we can exercise the transformation with a plain vi.fn() sink, no
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, mkdir, rename, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { watchAccountFiles } from '../src/qq-account/watch';
// Keep native filesystem coverage aligned with qqDataRootsForPid's supported platforms.
// macOS is only a development host here: fs.watch() can return before FSEvents
// registration, losing immediate writes. Deterministic logic tests run on every OS.
describe.skipIf(process.platform !== 'win32' && process.platform !== 'linux')(
'account file changes on supported filesystems',
() => {
let root: string;
const subscriptions: Array<() => void> = [];
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-account-watch-'));
});
afterEach(async () => {
for (const stop of subscriptions.splice(0)) {
stop();
}
await rm(root, { recursive: true, force: true });
});
function subscribe(dbPaths = [path.join(root, 'login.db')]) {
const changed = vi.fn();
subscriptions.push(watchAccountFiles(dbPaths, changed));
return changed;
}
it('observes database and WAL changes while ignoring message data and SHM', async () => {
const dbPath = path.join(root, 'login.db');
const changed = subscribe([dbPath, dbPath]);
await writeFile(dbPath, 'login');
await vi.waitFor(() => expect(changed).toHaveBeenCalled());
const afterDatabase = changed.mock.calls.length;
await writeFile(`${dbPath}-wal`, 'wal');
await vi.waitFor(() =>
expect(changed.mock.calls.length).toBeGreaterThan(afterDatabase),
);
const afterWal = changed.mock.calls.length;
await writeFile(path.join(root, 'nt_msg.db'), 'message');
await writeFile(`${dbPath}-shm`, 'shared memory');
await delay(350);
expect(changed).toHaveBeenCalledTimes(afterWal);
});
it('observes database replacement and WAL recreation', async () => {
const dbPath = path.join(root, 'login.db');
await writeFile(dbPath, 'initial');
const changed = subscribe();
await writeFile(path.join(root, 'replacement'), 'replacement');
await rename(path.join(root, 'replacement'), dbPath);
await vi.waitFor(() => expect(changed).toHaveBeenCalled());
const afterReplacement = changed.mock.calls.length;
await writeFile(dbPath, 'updated');
await vi.waitFor(() =>
expect(changed.mock.calls.length).toBeGreaterThan(afterReplacement),
);
const afterUpdate = changed.mock.calls.length;
await writeFile(`${dbPath}-wal`, 'wal');
await vi.waitFor(() => expect(changed.mock.calls.length).toBeGreaterThan(afterUpdate));
const afterWal = changed.mock.calls.length;
await rm(`${dbPath}-wal`);
await writeFile(`${dbPath}-wal`, 'new wal');
await vi.waitFor(() => expect(changed.mock.calls.length).toBeGreaterThan(afterWal));
});
it('starts watching login data created after QQ process discovery', async () => {
const dbPath = path.join(root, 'QQ', 'global', 'nt_db', 'login.db');
const changed = subscribe([dbPath]);
await mkdir(path.dirname(dbPath), { recursive: true });
await writeFile(dbPath, 'initial');
await vi.waitFor(() => expect(changed).toHaveBeenCalled());
const afterDatabase = changed.mock.calls.length;
await writeFile(`${dbPath}-wal`, 'login');
await vi.waitFor(() =>
expect(changed.mock.calls.length).toBeGreaterThan(afterDatabase),
);
});
},
);
@@ -0,0 +1,253 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { EventEmitter } from 'node:events';
import type { FSWatcher, WatchListener } from 'node:fs';
import path from 'node:path';
import { createLogger } from '@snowluma/common/logger';
import { watchAccountChangesForPids, watchAccountFiles } from '../src/qq-account/watch';
const files = vi.hoisted(() => ({
watch: vi.fn<
(
directory: string,
options: { persistent: boolean },
listener: WatchListener<string>,
) => FSWatcher
>(),
}));
vi.mock('node:fs', async (importOriginal) => ({
...(await importOriginal<typeof import('node:fs')>()),
watch: files.watch,
}));
class TestWatcher extends EventEmitter implements FSWatcher {
// Keep callbacks reachable after close to exercise queued, stale events.
close = vi.fn();
ref() {
return this;
}
unref() {
return this;
}
}
const root = path.resolve('account-watch-fixture');
const directories = new Set<string>();
const watchers: TestWatcher[] = [];
const subscriptions: Array<() => void> = [];
const platform = process.platform;
beforeEach(() => {
vi.useFakeTimers();
directories.add(root);
files.watch.mockImplementation((directory, _options, listener) => {
if (!directories.has(directory)) {
throw Object.assign(new Error('directory missing'), { code: 'ENOENT' });
}
const watcher = new TestWatcher();
watcher.on('change', listener);
watchers.push(watcher);
return watcher;
});
});
afterEach(() => {
for (const stop of subscriptions.splice(0)) {
stop();
}
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
watchers.length = 0;
directories.clear();
files.watch.mockReset();
vi.useRealTimers();
vi.restoreAllMocks();
});
function subscribe(dbPaths = [path.join(root, 'login.db')]) {
const changed = vi.fn();
const log = createLogger('AccountWatchTest');
const warning = vi.spyOn(log, 'warn');
const stop = watchAccountFiles(dbPaths, changed, log);
subscriptions.push(stop);
return { changed, stop, warning };
}
// Native filesystem delivery is covered separately on the production platforms.
// These tests control event ordering and the debounce clock, not OS startup timing.
describe('account file changes', () => {
it('coalesces login database and WAL changes while ignoring message data and SHM', () => {
const dbPath = path.join(root, 'login.db');
const { changed } = subscribe([dbPath, dbPath]);
expect(files.watch).toHaveBeenCalledExactlyOnceWith(
root,
{ persistent: false },
expect.any(Function),
);
const watcher = watchers[0]!;
watcher.emit('change', 'change', 'login.db');
vi.advanceTimersByTime(100);
watcher.emit('change', 'change', 'login.db-wal');
vi.advanceTimersByTime(249);
expect(changed).not.toHaveBeenCalled();
watcher.emit('change', 'change', 'nt_msg.db');
watcher.emit('change', 'change', 'login.db-shm');
vi.advanceTimersByTime(1);
expect(changed).toHaveBeenCalledOnce();
vi.advanceTimersByTime(1000);
expect(changed).toHaveBeenCalledOnce();
});
it('keeps the directory watch across database replacement and WAL recreation', () => {
const { changed } = subscribe();
const watcher = watchers[0]!;
watcher.emit('change', 'rename', 'replacement');
vi.advanceTimersByTime(250);
expect(changed).not.toHaveBeenCalled();
watcher.emit('change', 'rename', 'login.db');
vi.advanceTimersByTime(250);
watcher.emit('change', 'change', 'login.db');
vi.advanceTimersByTime(250);
watcher.emit('change', 'rename', 'login.db-wal');
vi.advanceTimersByTime(250);
watcher.emit('change', 'rename', 'login.db-wal');
watcher.emit('change', 'rename', 'login.db-wal');
vi.advanceTimersByTime(250);
expect(changed).toHaveBeenCalledTimes(4);
expect(files.watch).toHaveBeenCalledOnce();
expect(watcher.close).not.toHaveBeenCalled();
});
it('moves to newly created directories one level at a time', () => {
const dbDirectory = path.join(root, 'QQ', 'global', 'nt_db');
const { changed } = subscribe([path.join(dbDirectory, 'login.db')]);
const ancestor = watchers[0]!;
const attempts = files.watch.mock.calls.length;
ancestor.emit('change', 'rename', 'unrelated');
ancestor.emit('change', 'change', 'login.db-wal');
expect(files.watch).toHaveBeenCalledTimes(attempts);
expect(vi.getTimerCount()).toBe(0);
let directory = root;
for (const segment of ['QQ', 'global', 'nt_db']) {
directory = path.join(directory, segment);
directories.add(directory);
const previous = watchers.at(-1)!;
previous.emit('change', 'rename', segment);
expect(previous.close).toHaveBeenCalledOnce();
expect(files.watch).toHaveBeenLastCalledWith(
directory,
{ persistent: false },
expect.any(Function),
);
}
vi.advanceTimersByTime(250);
expect(changed).toHaveBeenCalledOnce();
watchers.at(-1)!.emit('change', 'change', 'login.db-wal');
vi.advanceTimersByTime(250);
expect(changed).toHaveBeenCalledTimes(2);
});
it.each(['QQ', null])(
'observes an entire new directory tree from a %s ancestor event',
(filename) => {
const dbDirectory = path.join(root, 'QQ', 'global', 'nt_db');
const { changed, warning } = subscribe([path.join(dbDirectory, 'login.db')]);
const ancestor = watchers[0]!;
directories.add(dbDirectory);
ancestor.emit('change', 'rename', filename);
expect(ancestor.close).toHaveBeenCalledOnce();
expect(files.watch).toHaveBeenLastCalledWith(
dbDirectory,
{ persistent: false },
expect.any(Function),
);
const attempts = files.watch.mock.calls.length;
vi.advanceTimersByTime(250);
expect(changed).toHaveBeenCalledOnce();
ancestor.emit('change', 'rename', 'QQ');
ancestor.emit('error', new Error('late error'));
vi.advanceTimersByTime(250);
expect(files.watch).toHaveBeenCalledTimes(attempts);
expect(changed).toHaveBeenCalledOnce();
expect(warning).not.toHaveBeenCalled();
watchers.at(-1)!.emit('change', 'change', 'login.db-wal');
vi.advanceTimersByTime(250);
expect(changed).toHaveBeenCalledTimes(2);
},
);
it('notifies when the filesystem does not supply a filename', () => {
const { changed } = subscribe();
watchers[0]!.emit('change', 'change', null);
vi.advanceTimersByTime(250);
expect(changed).toHaveBeenCalledOnce();
});
it('closes every watcher and cancels pending notifications on disposal', () => {
const { changed, stop, warning } = subscribe([
path.join(root, 'login.db'),
path.join(root, 'other', 'login.db'),
]);
expect(watchers).toHaveLength(2);
watchers[0]!.emit('change', 'change', 'login.db');
vi.advanceTimersByTime(30);
expect(vi.getTimerCount()).toBe(1);
stop();
expect(vi.getTimerCount()).toBe(0);
for (const watcher of watchers) {
expect(watcher.close).toHaveBeenCalledOnce();
watcher.emit('change', 'rename', null);
watcher.emit('error', new Error('late error'));
}
vi.advanceTimersByTime(1000);
expect(changed).not.toHaveBeenCalled();
expect(warning).not.toHaveBeenCalled();
});
it('reports watch failures without starting a polling fallback', () => {
files.watch.mockImplementationOnce(() => {
throw Object.assign(new Error('access denied'), { code: 'EACCES' });
});
const { changed, warning } = subscribe();
expect(warning).toHaveBeenCalledWith(
'account watch failed: path=%s err=%s',
path.join(root, 'login.db'),
'access denied',
);
expect(vi.getTimerCount()).toBe(0);
vi.advanceTimersByTime(1000);
expect(files.watch).toHaveBeenCalledOnce();
expect(changed).not.toHaveBeenCalled();
});
it('reports asynchronous watch errors and closes the failed watcher', () => {
const { changed, warning } = subscribe();
const watcher = watchers[0]!;
watcher.emit('error', new Error('watch unavailable'));
expect(watcher.close).toHaveBeenCalledOnce();
expect(warning).toHaveBeenCalledWith(
'account watch failed: path=%s err=%s',
path.join(root, 'login.db'),
'watch unavailable',
);
watcher.emit('change', 'change', 'login.db');
vi.advanceTimersByTime(250);
expect(changed).not.toHaveBeenCalled();
});
it('does not start account file watchers through the production entry point on macOS', () => {
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
const changed = vi.fn();
subscriptions.push(watchAccountChangesForPids([123], changed));
expect(files.watch).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
expect(changed).not.toHaveBeenCalled();
});
});
+196 -4
View File
@@ -12,6 +12,7 @@ import {
type LogEntry,
} from '@snowluma/common/logger';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
import {
HEADER_SIZE,
listLiveLinuxPipePids,
@@ -84,6 +85,7 @@ function readSendFrame(payload: Buffer): {
function mockControlPipe(
pid: number,
onWrite: (socket: net.Socket, payload: Buffer) => void,
...startupFrames: Buffer[]
): ReturnType<typeof vi.spyOn> {
return vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({
@@ -100,10 +102,13 @@ function mockControlPipe(
queueMicrotask(() =>
socket.emit(
'data',
pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
}),
Buffer.concat([
pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
}),
...startupFrames,
]),
),
);
});
@@ -117,6 +122,77 @@ function traceMessages(entries: LogEntry[]): string[] {
.map((entry) => entry.message);
}
describe('runtime initialization failures', () => {
const failureFrame = pipeFrame({
op: PipeOp.error,
cmd: 'runtime',
status: -1,
message: 'QQ service unavailable',
});
it('rejects startup when a runtime failure follows hello in the same read', async () => {
const connection = mockControlPipe(778901, () => {}, failureFrame);
const client = new QqHookClient(778901);
const failure = vi.fn();
client.on('runtimeError', failure);
try {
await expect(client.connect()).rejects.toThrow('QQ service unavailable');
expect(failure).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ status: -1, requestId: 0 }),
);
} finally {
client.close();
connection.mockRestore();
}
});
it('rejects pending and future requests on a runtime failure', async () => {
const connection = mockControlPipe(778902, (socket) => {
queueMicrotask(() => socket.emit('data', failureFrame));
});
const client = new QqHookClient(778902);
try {
await expect(client.sendAndWait('Test', Buffer.alloc(0))).rejects.toThrow(
'QQ service unavailable',
);
await expect(client.sendAndWait('Test', Buffer.alloc(0))).rejects.toThrow(
'QQ service unavailable',
);
await expect(client.startRecv()).rejects.toThrow('QQ service unavailable');
await expect(client.waitForLogin()).rejects.toThrow('QQ service unavailable');
} finally {
client.close();
connection.mockRestore();
}
});
it('rejects login and queued writes when the runtime fails as a connection resumes', async () => {
const onWrite = vi.fn();
const sockets = mockControlPipe(778903, onWrite);
const client = new QqHookClient(778903);
try {
await client.connect();
const waiting = client.waitForLogin({ timeoutMs: 100 });
const sending = client.sendNoReply('Test', Buffer.alloc(0), { ackTimeoutMs: 100 });
const settled = Promise.allSettled([waiting, sending]);
sockets.mock.results[0]!.value.emit('data', failureFrame);
const expected = {
status: 'rejected',
reason: expect.objectContaining({ message: 'QQ service unavailable' }),
};
expect(await settled).toEqual([expected, expected]);
expect(onWrite).not.toHaveBeenCalled();
} finally {
client.close();
sockets.mockRestore();
}
});
});
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime');
}
@@ -147,6 +223,122 @@ describe('QqHookClient login wait lifecycle', () => {
});
});
describe('QqHookClient client message receipts', () => {
it('preserves receipt provenance and failure status separately from normal packets', async () => {
const sockets = mockControlPipe(12345, () => {});
const client = new QqHookClient(12345);
const onPacket = vi.fn();
try {
await client.startRecv(onPacket);
const socket = sockets.mock.results[0]!.value;
const body = Buffer.from([1, 2, 3]);
socket.emit(
'data',
pipeFrame({ op: PipeOp.clientMessageReceipt, value0: 42n, message: '10001', body }),
);
socket.emit(
'data',
pipeFrame({
op: PipeOp.clientMessageReceipt,
value0: 43n,
message: '10001',
status: -1,
}),
);
socket.emit(
'data',
pipeFrame({
op: PipeOp.recvPacket,
value0: 44n,
message: '10001',
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
body,
}),
);
expect(onPacket.mock.calls.map(([packet]) => packet)).toEqual([
{
seq: 42,
error: 0,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: '10001',
body,
source: 'client-message',
},
{
seq: 43,
error: -1,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: '10001',
body: Buffer.alloc(0),
source: 'client-message',
},
{ seq: 44, error: 0, cmd: CLIENT_MESSAGE_RECEIPT_CMD, uin: '10001', body },
]);
} finally {
client.close();
}
});
it('reports unsupported capability and invalid envelopes without breaking normal receive', async () => {
const entries: LogEntry[] = [];
setLogLevel('warn');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const sockets = mockControlPipe(12345, () => {});
const client = new QqHookClient(12345);
const onPacket = vi.fn();
try {
await client.startRecv(onPacket);
const socket = sockets.mock.results[0]!.value;
socket.emit('data', pipeFrame({ op: PipeOp.clientMessageState, status: -1 }));
socket.emit(
'data',
pipeFrame({ op: PipeOp.clientMessageState, status: -1, value0: 42n }),
);
const warning = 'Client private-message reporting is unavailable: PID=12345 status=-1';
expect(entries.map((entry) => entry.message)).toEqual([
warning,
`${warning} reason=42`,
]);
for (const patch of [
{ value0: 0n },
{ value0: BigInt(Number.MAX_SAFE_INTEGER) + 1n },
{ message: '' },
{ cmd: 'unexpected' },
{ requestId: 1 },
]) {
socket.emit(
'data',
pipeFrame({
op: PipeOp.clientMessageReceipt,
value0: 42n,
message: '10001',
...patch,
}),
);
}
expect(onPacket).not.toHaveBeenCalled();
expect(
entries.filter(
(entry) => entry.scope === 'QQHook.Runtime' && entry.level === 'warn',
),
).toHaveLength(7);
socket.emit(
'data',
pipeFrame({ op: PipeOp.recvPacket, cmd: 'normal', message: '10001', value0: 44n }),
);
expect(onPacket).toHaveBeenCalledOnce();
} finally {
client.close();
unsubscribe();
}
});
});
describe('listLiveLinuxPipePids', () => {
it('ignores stale-looking control socket names when the probe rejects them', async () => {
const runtimeDir = await makeRuntimeDir();
+7 -3
View File
@@ -1,13 +1,17 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "2.0.2",
"version": "2.3.1",
"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).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
"./webui-target": {
"types": "./src/webui-target.ts",
"default": "./src/webui-target.ts"
},
"./update-source": {
"types": "./src/update-source.ts",
"default": "./src/update-source.ts"
@@ -105,7 +109,7 @@
"@types/node": "catalog:",
"@types/semver": "7.7.1",
"typescript": "catalog:",
"vitest": "^4.1.4"
"vitest": "4.1.12"
},
"dependencies": {
"@zxcvbn-ts/core": "^4.1.2",
@@ -114,6 +118,6 @@
"semver": "7.7.4"
},
"engines": {
"node": ">=24"
"node": "^24.22.1 || >=26.12.1"
}
}
+3
View File
@@ -1,3 +1,5 @@
export const CLIENT_MESSAGE_RECEIPT_CMD = 'ClientMessageReceipt';
export interface PacketInfo {
pid: number;
uin: string;
@@ -6,6 +8,7 @@ export interface PacketInfo {
seqId: number;
retCode: number;
fromClient: boolean;
source?: 'client-message';
body: Uint8Array;
}
export type PacketSink = (packet: PacketInfo) => void;
+100
View File
@@ -0,0 +1,100 @@
/** Browser-safe contract shared by startup, the WebUI and embedding hosts.
* Targets are deployment choices; they never belong in the saved UI preferences. */
export const WEBUI_TARGETS = {
maibot: {
label: '麦麦 / 一键包',
styles: ['millennium'],
defaultStyle: 'millennium',
},
} as const;
export type WebuiTarget = keyof typeof WEBUI_TARGETS;
export type WebuiColorMode = 'light' | 'dark' | 'system';
export type WebuiPresentation = {
[T in WebuiTarget]: {
version: 1;
target: T;
style: (typeof WEBUI_TARGETS)[T]['styles'][number];
mode: WebuiColorMode;
};
}[WebuiTarget];
/** null releases the override for this document, without changing deployment opt-in. */
export type WebuiPresentationUpdate = WebuiPresentation | { version: 1; target: null };
export const WEBUI_PRESENTATION_EVENT = 'snowluma:host-appearance';
export const WEBUI_TARGET_BOOTSTRAP_ID = 'snowluma-webui-target';
export function resolveWebuiTarget(raw: string | undefined): WebuiTarget | null {
if (raw === undefined || raw.trim() === '') {
return null;
}
const value = raw.trim();
if (!Object.hasOwn(WEBUI_TARGETS, value)) {
throw new Error(
`Invalid SNOWLUMA_WEBUI_TARGET: ${JSON.stringify(value)}. Expected ${Object.keys(WEBUI_TARGETS).join(', ')} or an empty value.`,
);
}
return value as WebuiTarget;
}
export function defaultWebuiPresentation(target: WebuiTarget): WebuiPresentation {
return { version: 1, target, style: WEBUI_TARGETS[target].defaultStyle, mode: 'system' };
}
export function parseWebuiPresentation(value: unknown): WebuiPresentationUpdate {
if (
!value ||
typeof value !== 'object' ||
!('version' in value) ||
value.version !== 1 ||
!('target' in value)
) {
throw new TypeError('Invalid host appearance: expected a version 1 presentation');
}
if (value.target === null) {
return { version: 1, target: null };
}
if (typeof value.target !== 'string' || !Object.hasOwn(WEBUI_TARGETS, value.target)) {
throw new TypeError('Invalid host appearance target');
}
const target = value.target as WebuiTarget;
const styles: readonly string[] = WEBUI_TARGETS[target].styles;
if (!('style' in value) || typeof value.style !== 'string' || !styles.includes(value.style)) {
throw new TypeError(`Invalid host appearance style for ${target}`);
}
if (
!('mode' in value) ||
(value.mode !== 'light' && value.mode !== 'dark' && value.mode !== 'system')
) {
throw new TypeError('Invalid host appearance color mode');
}
// Both discriminants have been checked against the same target registry.
return { version: 1, target, style: value.style, mode: value.mode } as WebuiPresentation;
}
/** Inject before the cached pre-paint theme script. Default HTML stays byte-for-byte intact. */
export function injectWebuiTarget(html: string, target: WebuiTarget | null): string {
if (target === null) {
return html;
}
if (!html.includes('<head>')) {
throw new Error('WebUI HTML is missing <head>; cannot inject runtime target');
}
const json = JSON.stringify(defaultWebuiPresentation(target)).replaceAll('<', '\\u003c');
return html.replace(
'<head>',
`<head>\n <script id="${WEBUI_TARGET_BOOTSTRAP_ID}" type="application/json">${json}</script>`,
);
}
@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest';
import {
defaultWebuiPresentation,
injectWebuiTarget,
parseWebuiPresentation,
resolveWebuiTarget,
} from '../src/webui-target';
describe('deployment presentation contract', () => {
it('requires explicit opt-in and rejects misspelled deployments', () => {
expect(resolveWebuiTarget(undefined)).toBeNull();
expect(resolveWebuiTarget(' ')).toBeNull();
expect(resolveWebuiTarget('maibot')).toBe('maibot');
expect(() => resolveWebuiTarget('mai-bot')).toThrow('SNOWLUMA_WEBUI_TARGET');
expect(() => resolveWebuiTarget('__proto__')).toThrow('SNOWLUMA_WEBUI_TARGET');
});
it('keeps the unconfigured document intact and injects before cached appearance', () => {
const html = '<html><head><script>readSavedAppearance()</script></head></html>';
expect(injectWebuiTarget(html, null)).toBe(html);
const injected = injectWebuiTarget(html, 'maibot');
expect(injected.indexOf('snowluma-webui-target')).toBeLessThan(
injected.indexOf('readSavedAppearance'),
);
expect(injected).toContain(JSON.stringify(defaultWebuiPresentation('maibot')));
expect(() => injectWebuiTarget('broken html', 'maibot')).toThrow('missing <head>');
});
it('validates the version, target, style and color mode without accepting arbitrary CSS', () => {
const valid = defaultWebuiPresentation('maibot');
expect(parseWebuiPresentation(valid)).toEqual(valid);
expect(
parseWebuiPresentation({ ...valid, mode: 'dark', css: 'body{display:none}' }),
).toEqual({ ...valid, mode: 'dark' });
expect(parseWebuiPresentation({ version: 1, target: null })).toEqual({
version: 1,
target: null,
});
for (const input of [
null,
{},
{ ...valid, version: 2 },
{ ...valid, target: 'other' },
{ ...valid, style: 'modern' },
{ ...valid, mode: 'blue' },
]) {
expect(() => parseWebuiPresentation(input)).toThrow();
}
});
});
+4 -4
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "2.0.2",
"version": "2.3.1",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -57,15 +57,15 @@
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"hono": "^4.12.34",
"hono": "^4.13.11",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
"vite-plugin-cp": "^6.0.3",
"vitest": "^4.1.4",
"vitest": "4.1.12",
"@snowluma/sqlite": "workspace:*"
},
"engines": {
"node": ">=24"
"node": "^24.22.1 || >=26.12.1"
}
}
+41 -21
View File
@@ -1,3 +1,4 @@
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import {
FetchFriendListPage,
@@ -109,9 +110,7 @@ export class ContactsApi {
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
});
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
/** groupUin → approval msgseq from a private qun.invite card. Written
* only by IncomingPacketPipeline (and tests). OneBot reads get/find. */
private readonly groupInviteCardSeqs_ = new Map<number, number>();
readonly groupInvites = new GroupInviteTracker();
constructor(private readonly ctx: BridgeContext) {}
@@ -581,30 +580,51 @@ export class ContactsApi {
return requests;
}
/** Live observation write. IncomingPacketPipeline and tests only. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) {
this.groupInviteCardSeqs_.set(groupUin, sequence);
async resolveGroupJoinRequest(
groupId: number,
uid: string,
subType: 'add' | 'invite',
invitedUid?: string,
): Promise<GroupRequestInfo | null> {
const [main, filtered] = await Promise.allSettled([
this.fetchGroupRequestsByUid(false),
this.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
throw main.reason;
}
if (filtered.status === 'rejected') {
throw filtered.reason;
}
return (
[...main.value, ...filtered.value].find((request) => {
if (request.groupId !== groupId || request.state !== 1) {
return false;
}
return subType === 'add'
? request.eventType === 1 && request.targetUid === uid
: (request.eventType === 2 || request.eventType === 22) &&
request.invitorUid === uid &&
request.targetUid === invitedUid;
}) ?? null
);
}
/** Returns whether this live card introduces a new approval sequence. */
rememberGroupInviteCardSequence(groupId: number, sequence: number): boolean {
return this.groupInvites.receiveCard(groupId, sequence);
}
/** The approval msgseq captured from a private "qun.invite" card for this
* group, or undefined if none was seen. `set_group_add_request` uses it to
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
getGroupInviteCardSequence(groupId: number): number | undefined {
return this.groupInviteCardSeqs_.get(groupId);
return this.groupInvites.getCardSequence(groupId);
}
/** Resolve the group for a private invite-card msgseq. Numeric OneBot flags
* use this path because the card sequence is absent from 0x10C0. */
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
if (rememberedSequence === sequence) {
return groupUin;
}
}
return undefined;
findGroupInviteCardGroupBySequence(sequence: number, groupId?: number): number | undefined {
return this.groupInvites.findCardGroup(sequence, groupId);
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
@@ -0,0 +1,69 @@
import { createLogger } from '@snowluma/common/logger';
import type { ForwardNodePayload } from '@snowluma/protocol/events';
const MAX_CACHED_FORWARDS = 512;
const log = createLogger('Bridge.Forward');
type ForwardLayers = Map<string, ForwardNodePayload[]>;
interface ForwardCacheHit {
rootId: string;
resId: string;
layers: ForwardLayers;
nodes: ForwardNodePayload[];
}
/** Nested results share the lifetime and recency of the result that supplied them. */
export class ForwardResultCache {
private readonly entries = new Map<string, ForwardLayers>();
get(resId: string): ForwardCacheHit | undefined {
let hit: ForwardCacheHit | undefined;
// A nested result can be supplied by several retained outer results.
for (const [rootId, layers] of this.entries) {
const nodes = layers.get(resId);
if (nodes) {
hit = { rootId, resId, layers, nodes };
}
}
if (hit) {
this.entries.delete(hit.rootId);
this.entries.set(hit.rootId, hit.layers);
}
return hit;
}
set(rootId: string, layers: ReadonlyMap<string, ForwardNodePayload[]>): void {
if (!layers.has(rootId)) {
throw new Error('forward cache entry is missing its outer result');
}
this.entries.delete(rootId);
this.entries.set(rootId, new Map(layers));
while (this.entries.size > MAX_CACHED_FORWARDS) {
const oldest = this.entries.entries().next().value!;
this.entries.delete(oldest[0]);
log.trace(
'forward cache evicted: res_id=%s layers=%d remaining=%d',
oldest[0],
oldest[1].size,
this.entries.size,
);
}
}
update(hit: ForwardCacheHit, nodes: ForwardNodePayload[]): void {
// Enrichment may finish after eviction or replacement. It must not revive
// an old result or turn a nested result into an independent cache entry.
if (
this.entries.get(hit.rootId) === hit.layers &&
hit.layers.get(hit.resId) === hit.nodes
) {
hit.layers.set(hit.resId, nodes);
}
}
}
+56 -28
View File
@@ -25,16 +25,15 @@ import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { Bridge } from '../bridge';
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
import { ForwardResultCache } from './forward-cache';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
// Share within a bridge without retaining disconnected accounts.
const forwardCaches = new WeakMap<BridgeContext, ForwardResultCache>();
const log = createLogger('Bridge.Forward');
@@ -77,6 +76,7 @@ interface ForwardUploadResult {
// callers concatenate these to their own actions list so the
// outermost upload carries the full tree.
innerActions: ForwardInnerAction[];
cachedLayers: Map<string, ForwardNodePayload[]>;
}
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
@@ -353,7 +353,18 @@ function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) {}
private readonly cache: ForwardResultCache;
constructor(private readonly ctx: BridgeContext) {
let cache = forwardCaches.get(ctx);
if (!cache) {
cache = new ForwardResultCache();
forwardCaches.set(ctx, cache);
}
this.cache = cache;
}
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
// Reject the complete recursive tree before identity resolution, media
@@ -367,7 +378,8 @@ export class ForwardApi {
assertPrivateForwardFileCapacity(nodes);
}
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
const { resId, cachedLayers } = await this.uploadRecursive(nodes, groupId, userId);
this.cache.set(resId, cachedLayers);
return resId;
}
@@ -593,6 +605,7 @@ export class ForwardApi {
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
const myInnerActions: ForwardInnerAction[] = [];
const cachedLayers = new Map<string, ForwardNodePayload[]>();
const processedNodes: ForwardNodePayload[] = [];
const isGroup = groupId !== undefined;
@@ -605,6 +618,11 @@ export class ForwardApi {
// and `inner.innerActions` already contains deeper layers.
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
myInnerActions.push(...inner.innerActions);
for (const [resId, cached] of inner.cachedLayers) {
cachedLayers.set(resId, cached);
}
// Replace the inner placeholder element with a forward preview
// pointing at the inner res_id. `forwardUuid: inner.uuid`
// baked into the LightApp JSON's `meta.detail.uniseq` is what
@@ -692,7 +710,7 @@ export class ForwardApi {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(
cachedLayers.set(
resId,
uploadReadyNodes.map((node) => ({
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
@@ -714,20 +732,21 @@ export class ForwardApi {
// from (1) — no separate fetch needed.
uuid: randomUUID(),
innerActions: myInnerActions,
cachedLayers,
};
}
async fetch(resId: string): Promise<ForwardNodePayload[]> {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
const cached = this.cache.get(resId);
if (cached) {
const nodes = cloneNodes(cached);
const nodes = cloneNodes(cached.nodes);
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
// Bundled inner nodes are cached un-enriched; enrich
// on read (a no-op once names are present) and persist so later hits skip.
if (await this.enrichSenders(nodes)) {
forwardResCache.set(resId, cloneNodes(nodes));
this.cache.update(cached, cloneNodes(nodes));
}
return nodes;
@@ -820,9 +839,7 @@ export class ForwardApi {
// matching piggyback body, decode it into inner nodes, and seed
// the cache by the inner resId so a follow-up `fetch(innerResId)`
// hits the cache instead of the wire.
if (piggybackByUuid.size > 0) {
this.consumePiggybacks(nodes, piggybackByUuid);
}
const cachedLayers = this.collectForwardLayers(resId, nodes, piggybackByUuid);
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
@@ -830,7 +847,8 @@ export class ForwardApi {
await this.enrichSenders(nodes);
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
cachedLayers.set(resId, cloneNodes(nodes));
this.cache.set(resId, cachedLayers);
}
return nodes;
@@ -1017,20 +1035,22 @@ export class ForwardApi {
return out;
}
/** Recursively resolve forward previews against the piggyback table.
/** Resolve forward previews against the piggyback table.
* For every `{type: 'forward', resId, forwardUuid}` element we find,
* look up the uniseq in the piggyback map; if hit, decode the
* inner msgBody and cache it by inner resId, then descend into that
* inner layer to resolve deeper nestings carried in the SAME
* piggyback set (NapCat hoists the entire tree's piggybacks onto
* the outermost action list). */
private consumePiggybacks(
private collectForwardLayers(
resId: string,
nodes: ForwardNodePayload[],
piggybackByUuid: Map<string, PushMsgBody[]>,
): void {
const seen = new Set<string>();
): Map<string, ForwardNodePayload[]> {
const layers = new Map([[resId, cloneNodes(nodes)]]);
const decodedByUuid = new Map<string, ForwardNodePayload[]>();
const visit = (chain: ForwardNodePayload[]): void => {
for (const chain of layers.values()) {
for (const node of chain) {
for (const elem of node.elements) {
if (elem.type !== 'forward') {
@@ -1040,25 +1060,33 @@ export class ForwardApi {
const uuid = elem.forwardUuid;
const innerResId = elem.resId;
if (!uuid || !innerResId || seen.has(uuid)) {
if (!uuid || !innerResId || layers.has(innerResId)) {
continue;
}
const body = piggybackByUuid.get(uuid);
const body =
piggybackByUuid.get(uuid) ??
(uuid.startsWith('MultiMsg_')
? piggybackByUuid.get(uuid.slice('MultiMsg_'.length))
: undefined);
if (!body) {
continue;
}
seen.add(uuid);
const innerNodes = this.decodeMsgBodiesToNodes(body);
forwardResCache.set(innerResId, cloneNodes(innerNodes));
visit(innerNodes);
let innerNodes = decodedByUuid.get(uuid);
if (!innerNodes) {
innerNodes = cloneNodes(this.decodeMsgBodiesToNodes(body));
decodedByUuid.set(uuid, innerNodes);
}
layers.set(innerResId, innerNodes);
}
}
};
}
visit(nodes);
return layers;
}
}
@@ -8,6 +8,14 @@ import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-me
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin';
import { GetAdminPermissions } from '@snowluma/protocol/oidb-services/group-admin/get-admin-permissions';
import { GetAdminReceiveVerify } from '@snowluma/protocol/oidb-services/group-admin/get-admin-receive-verify';
import {
SetAdminPermissions,
type GroupAdminPermissionPatch,
} from '@snowluma/protocol/oidb-services/group-admin/set-admin-permissions';
import { SetAdminReceiveVerify } from '@snowluma/protocol/oidb-services/group-admin/set-admin-receive-verify';
import { createLogger } from '@snowluma/common/logger';
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
@@ -39,6 +47,8 @@ import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin
import { OidbError } from '@snowluma/protocol/oidb-service';
import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.GroupAdmin');
/** QQ only accepts this write from the group owner (#411). */
export const MEMBER_PERMISSIONS_OWNER_ONLY =
'only the group owner can change group member permissions';
@@ -343,6 +353,62 @@ export class GroupAdminApi {
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
}
async getAdminPermissions(groupId: number, userId: number) {
const logger = log.child({ uin: Number(this.ctx.identity.uin) });
logger.debug('Reading administrator permissions group=%s user=%s', groupId, userId);
const [snapshot, receiveVerify] = await Promise.all([
GetAdminPermissions.invoke(this.ctx, { groupId, userId }),
GetAdminReceiveVerify.invoke(this.ctx, { groupId, userId }),
]);
logger.debug(
'Administrator permissions received group=%s user=%s recall=%s kick=%s limit=%s receiveVerify=%s',
groupId,
userId,
snapshot.recallMemberMessage,
snapshot.kickMember,
snapshot.kickMemberPerDay,
receiveVerify,
);
return {
group_id: groupId,
user_id: userId,
recall_member_message: snapshot.recallMemberMessage,
kick_member: snapshot.kickMember,
kick_member_per_day: snapshot.kickMemberPerDay,
receive_verify: receiveVerify,
};
}
async setAdminPermissions(
groupId: number,
userId: number,
patch: GroupAdminPermissionPatch,
): Promise<void> {
const logger = log.child({ uin: Number(this.ctx.identity.uin) });
logger.debug(
'Setting administrator permissions group=%s user=%s recall=%s kick=%s limit=%s',
groupId,
userId,
patch.recallMemberMessage,
patch.kickMember,
patch.kickMemberPerDay,
);
await SetAdminPermissions.invoke(this.ctx, { groupId, userId, ...patch });
logger.debug('Administrator permissions acknowledged group=%s user=%s', groupId, userId);
}
async setAdminReceiveVerify(groupId: number, userId: number, enable: boolean): Promise<void> {
const logger = log.child({ uin: Number(this.ctx.identity.uin) });
logger.debug(
'Setting administrator receive-verify group=%s user=%s enable=%s',
groupId,
userId,
enable,
);
await SetAdminReceiveVerify.invoke(this.ctx, { groupId, userId, enable });
logger.debug('Administrator receive-verify confirmed group=%s user=%s', groupId, userId);
}
setCard(groupId: number, userId: number, card: string): Promise<void> {
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
}
+5 -8
View File
@@ -400,14 +400,11 @@ export class GroupFileApi {
try {
await this.publish(groupId, fileId);
} catch (err) {
// The bytes are already on the server and the fileId is valid —
// fail loud but don't lose the upload result the action handler
// committed to returning. Callers can still resolve the file by
// id; they'll just have to re-publish it themselves.
log.warn(
'group file uploaded (fileId=%s) but chat post failed: %s',
fileId,
err instanceof Error ? err.message : String(err),
// Keep the completed upload identifiable, but a requested chat
// publication must not be reported as a successful send.
throw new Error(
`group file uploaded (fileId=${fileId}) but chat post failed: ${err instanceof Error ? err.message : String(err)}`,
{ cause: err },
);
}
}
+9 -17
View File
@@ -8,7 +8,7 @@ import type {
SsoReadedReportReq,
SsoReadedReportResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
import { datalineTextFromElements, encodeDatalineText } from '@snowluma/protocol/dataline/codec';
@@ -22,7 +22,7 @@ import {
fetchC2cRoamMessagePage,
fetchGroupMessageRange,
} from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { type bytes, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { BridgeContext } from '../bridge-context';
@@ -254,6 +254,7 @@ type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
// ── Group-history fetch guards (the server frequency-limits / kicks abusive
// pulls, so keep each request small, bound the loop, and space the sends). ──
const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call
const PRIVATE_HISTORY_PAGE_SIZE = 100;
const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet)
const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop
const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends
@@ -547,15 +548,15 @@ export class MessageApi {
userUid = await this.ctx.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, {
bridge: this.ctx as unknown as Bridge,
const richText = await encodePrivateRichText(elements, {
bridge: this.ctx,
userUid,
scene: 'direct-private',
});
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const request = protobuf_encode<SendMessageRequest>({
const request = protobuf_encode<SendMessageRequest<bytes>>({
routingHead: {
c2c: {
uin: userUin,
@@ -567,11 +568,7 @@ export class MessageApi {
subType: 0,
c2cCmd: 11,
},
messageBody: {
richText: {
elems: protoElems,
},
},
messageBody: { richText },
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
@@ -1543,7 +1540,7 @@ export class MessageApi {
selfUin,
friendUid,
cursor.time,
want - collected.size,
Math.min(want - collected.size, PRIVATE_HISTORY_PAGE_SIZE),
cursor.random,
),
);
@@ -1564,7 +1561,7 @@ export class MessageApi {
break;
}
if (page.cursor.time === 0 && page.cursor.random === 0) {
if (page.isComplete || (page.cursor.time === 0 && page.cursor.random === 0)) {
reachedEnd = true;
break;
}
@@ -1572,11 +1569,6 @@ export class MessageApi {
const nextCursorKey = `${page.cursor.time}:${page.cursor.random}`;
if (seenCursors.has(nextCursorKey)) {
if (page.messages.length === 0) {
reachedEnd = true;
break;
}
throw new Error(
`private roam history cursor did not advance from ${cursor.time}/${cursor.random}`,
);
+164 -6
View File
@@ -1,33 +1,180 @@
import type { JsonObject } from '@snowluma/common/json';
import {
commentQzoneMsg,
deleteQzoneMsg,
getQzoneFeeds,
getQzoneMsgDetail,
getQzoneMsgList,
getQzoneProfile,
publishQzoneMsg,
replyQzoneComment,
setQzoneBlack,
setQzoneLike,
setQzoneProfile,
updateQzoneMsgRight,
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsResult,
type QzoneFeedsPage,
type QzoneMsgDetailResult,
type QzoneMsgListResult,
type QzoneProfile,
type QzoneProfileUpdate,
type QzonePublishResult,
type QzoneReplyTarget,
type QzoneUpdateRightResult,
type QzoneUploadImageResult,
} from '@snowluma/protocol/web/qzone';
import {
getQzonePublicCapabilities,
getQzoneHomeFeeds,
getQzoneShareArk,
type QzoneShareArk,
getQzonePublicFeeds,
getQzonePublicFeedDetail,
getQzonePublicComments,
getQzonePublicReplies,
setQzonePublicUpvote,
setQzonePublicLike,
setQzonePublicCommentLike,
commentQzonePublicFeed,
replyQzonePublicFeed,
deleteQzonePublicComment,
deleteQzonePublicReply,
setQzonePublicFollow,
forwardQzonePublicFeed,
type QzonePublicContent,
type QzonePublicFeedsPage,
} from '@snowluma/protocol/web/qzone-public';
import type { BridgeContext } from '../bridge-context';
/**
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
* comments, image upload — all over the cookie-backed qzone.qq.com CGIs,
* Personal QQ-Zone (个人空间) web API: 说说, public recommendations, likes,
* comments and image upload over the cookie-backed Qzone web interfaces,
* reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi.
* Distinct from the group-album surface, which lives on GroupAlbumApi.
*/
export class QzoneApi {
constructor(private readonly ctx: BridgeContext) {}
async getProfile(targetUin?: number): Promise<QzoneProfile> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneProfile(cookieObject, this.ctx.identity.uin, targetUin?.toString());
}
async setProfile(profile: QzoneProfileUpdate): Promise<void> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await setQzoneProfile(cookieObject, this.ctx.identity.uin, profile);
}
async getPublicCapabilities(): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicCapabilities(cookies, this.ctx.identity.uin);
}
async getPublicFeeds(cursor?: string): Promise<QzonePublicFeedsPage> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicFeeds(cookies, this.ctx.identity.uin, cursor);
}
async getHomeFeeds(targetUin?: number, cursor?: string): Promise<QzonePublicFeedsPage> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneHomeFeeds(cookies, this.ctx.identity.uin, targetUin?.toString(), cursor);
}
async getShareArk(feed: JsonObject): Promise<QzoneShareArk> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneShareArk(cookies, feed);
}
async getPublicFeedDetail(feed: JsonObject): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicFeedDetail(cookies, feed);
}
async getPublicComments(feed: JsonObject, cursor: string): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicComments(cookies, feed, cursor);
}
async getPublicReplies(
feed: JsonObject,
comment: JsonObject,
cursor = '',
pageSize = 20,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzonePublicReplies(cookies, feed, comment, cursor, pageSize);
}
async setPublicUpvote(feed: JsonObject, enable = true): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicUpvote(cookies, feed, enable);
}
async setPublicLike(feed: JsonObject, enable = true): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicLike(cookies, feed, enable);
}
async setPublicCommentLike(
feed: JsonObject,
comment: JsonObject,
enable = true,
reply?: JsonObject,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicCommentLike(cookies, feed, comment, enable, reply);
}
async commentPublicFeed(feed: JsonObject, content: QzonePublicContent): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
const user = {
uin: this.ctx.identity.uin,
uid: this.ctx.identity.selfUid ?? '',
nick: this.ctx.identity.nickname,
};
return commentQzonePublicFeed(cookies, feed, user, content);
}
async replyPublicFeed(
feed: JsonObject,
comment: JsonObject,
content: QzonePublicContent,
reply?: JsonObject,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
const user = {
uin: this.ctx.identity.uin,
uid: this.ctx.identity.selfUid ?? '',
nick: this.ctx.identity.nickname,
};
return replyQzonePublicFeed(cookies, feed, user, comment, content, reply);
}
async deletePublicComment(feed: JsonObject, comment: JsonObject): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return deleteQzonePublicComment(cookies, feed, comment);
}
async deletePublicReply(
feed: JsonObject,
comment: JsonObject,
reply: JsonObject,
): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return deleteQzonePublicReply(cookies, feed, comment, reply);
}
async setPublicFollow(feed: JsonObject, enable = true): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return setQzonePublicFollow(cookies, feed, enable);
}
async forwardPublicFeed(feed: JsonObject, reason = ''): Promise<JsonObject> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return forwardQzonePublicFeed(cookies, feed, reason);
}
/**
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
@@ -51,12 +198,12 @@ export class QzoneApi {
}
/**
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
* 获取好友动态。页码调用从首页顺序定位;续页优先传上一页的 cursor。
* 始终以机器人自己的身份拉取好友动态。
*/
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
async getFeeds(pageNum = 1, count = 10, cursor?: string): Promise<QzoneFeedsPage> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count, cursor);
}
/**
@@ -133,6 +280,7 @@ export class QzoneApi {
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
* (从 uploadImageFromSource 的 url 字段获取)。
* `reply` 指定父评论及可选回复对象;楼中楼回复仅支持文字。
*/
async comment(
tid: string,
@@ -140,10 +288,20 @@ export class QzoneApi {
targetUin: number | undefined,
richType?: number,
richval?: string,
reply?: QzoneReplyTarget,
): Promise<QzoneCommentResult> {
if (reply !== undefined && (richType !== undefined || richval !== undefined)) {
throw new Error('images are not supported for Qzone comment replies');
}
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
if (reply !== undefined) {
return replyQzoneComment(cookieObject, selfUin, owner, tid, content, reply);
}
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
}
+93 -69
View File
@@ -4,7 +4,13 @@ import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPushOrThrow, SysMsgDedup } from '@snowluma/protocol/msg-push';
import {
MSG_PUSH_CMD,
parseMsgPushOrThrow,
SysMsgDedup,
decodeClientMessageReceipt,
fetchClientMessage,
} from '@snowluma/protocol/msg-push';
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
@@ -38,6 +44,10 @@ export class Bridge implements BridgeInterface {
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>();
private readonly clientMessageTasks_ = new Map<
string,
{ connection: ProcessConnection; work: Promise<void> }
>();
private rosterWarmupStarted_ = false;
private settleRosterWarmup!: (result: RosterWarmupResult) => void;
private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
@@ -61,72 +71,9 @@ export class Bridge implements BridgeInterface {
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
this.apis.contacts.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
log.warn(
'group-request enrichment main inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
main.reason instanceof Error ? main.reason.message : String(main.reason),
);
}
if (filtered.status === 'rejected') {
log.warn(
'group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
filtered.reason instanceof Error
? filtered.reason.message
: String(filtered.reason),
);
}
if (main.status === 'rejected' && filtered.status === 'rejected') {
throw new Error('failed to fetch group requests from both inboxes');
}
const requests = [
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
const matches = requests.filter((r) => {
if (r.groupId !== groupId) {
return false;
}
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (subType === 'invite') {
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
}
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
},
resolveGroupInviteCardSequence: async (groupId) => {
const deadline = Date.now() + 1_000;
do {
const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId);
if (sequence) {
return sequence;
}
await new Promise((resolve) => setTimeout(resolve, 25));
} while (Date.now() < deadline);
return null;
},
rememberGroupInviteCardSequence: (groupUin, sequence) => {
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
},
resolveGroupJoinRequest: (groupId, uid, subType, invitedUid) =>
this.apis.contacts.resolveGroupJoinRequest(groupId, uid, subType, invitedUid),
groupInvites: this.apis.contacts.groupInvites,
});
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) =>
parseMsgPushOrThrow(pkt, identity, this.sysMsgDedup_),
@@ -173,9 +120,13 @@ export class Bridge implements BridgeInterface {
bindPid(pid: number, client: PacketSender): void {
const previous = this.activeConnection;
const existing = this.connections.get(pid);
this.connections.delete(pid);
// A new login stays healthy until the watchdog confirms a failure.
this.connections.set(pid, { pid, client, receiveHealthy: true });
const connection =
existing?.client === client ? existing : { pid, client, receiveHealthy: true };
connection.receiveHealthy = true;
this.connections.set(pid, connection);
if (previous?.pid !== pid || previous.client !== client) {
runtimeLog.trace(
@@ -252,12 +203,85 @@ export class Bridge implements BridgeInterface {
return Promise.reject(new Error('Bridge is disposed'));
}
const work = this.identity.initialization.then(() => this.pipeline.process(pkt));
const connection = this.connections.get(pkt.pid);
const work = this.identity.initialization.then(() =>
pkt.source === 'client-message'
? this.processClientMessage(pkt, connection)
: this.pipeline.process(pkt),
);
this.pendingPackets_.add(work);
void work.finally(() => this.pendingPackets_.delete(work)).catch(() => undefined);
return work;
}
private async processClientMessage(
pkt: PacketInfo,
connection: ProcessConnection | undefined,
): Promise<void> {
const requireConnection = (): ProcessConnection => {
if (
this.disposePromise_ ||
!connection ||
this.connections.get(pkt.pid) !== connection
) {
throw new Error('Client message receipt belongs to an inactive connection');
}
return connection;
};
const current = requireConnection();
const receipt = decodeClientMessageReceipt(pkt, this.identity.uin);
const key = JSON.stringify([
pkt.pid,
receipt.peerUid,
receipt.sequence,
receipt.clientSequence,
receipt.timestamp,
]);
const pending = this.clientMessageTasks_.get(key);
if (pending?.connection === current) {
return pending.work;
}
if (this.clientMessageTasks_.size >= 256) {
throw new Error('Too many pending client message lookups');
}
runtimeLog.trace(
'client_message_lookup_start uin=%j pid=%d seqId=%d',
this.identity.uin,
pkt.pid,
pkt.seqId,
);
const work = (async () => {
const source: PacketSender = {
sendPacket: (cmd, body, timeout) =>
requireConnection().client.sendPacket(cmd, body, timeout),
};
const event = await fetchClientMessage(source, this.identity, receipt);
requireConnection();
await this.pipeline.processEvents(pkt, [event]);
runtimeLog.trace(
'client_message_lookup_complete uin=%j pid=%d seqId=%d',
this.identity.uin,
pkt.pid,
pkt.seqId,
);
})();
const task = { connection: current, work };
this.clientMessageTasks_.set(key, task);
try {
await work;
} finally {
if (this.clientMessageTasks_.get(key) === task) {
this.clientMessageTasks_.delete(key);
}
}
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) {
return;
+7 -1
View File
@@ -434,7 +434,13 @@ export class BridgeManager implements BridgeSessionSource {
}
const closing = this.closingSessions_.get(uin);
const beforeOpen = closing ? Promise.all(closing).then(() => undefined) : undefined;
// allSettled, not all: a failed close stays in the bookkeeping (so
// dispose can still report it) but must not reject this gate — a
// rejected gate would keep the identity DB of every future session
// for this UIN closed until the process restarts.
const beforeOpen = closing
? Promise.allSettled(closing).then(() => undefined)
: undefined;
const bridge = new Bridge(IdentityService.openForUin(uin, 'data', beforeOpen));
this.bridges.set(uin, bridge);
-17
View File
@@ -1,5 +1,4 @@
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
import { APP_VERSION } from '@snowluma/common/version';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import {
@@ -23,7 +22,6 @@ import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { initWebUI } from './webui/server';
import { bindSystemFaceCatalog } from './sys-face-catalog';
import { startNativeStageSync, tempStagePath } from './native-stage-sync';
import { logRuntimeIntegrity } from './runtime-integrity-log';
import { RESTART_EXIT_CODE, runApplication } from './update/startup';
@@ -60,11 +58,6 @@ async function main() {
});
log.info('SnowLuma starting');
logRuntimeIntegrity(await getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({
version: APP_VERSION,
dataDir: 'data',
tempPath: tempStagePath(),
});
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
// any session (and thus any per-UIN config rewrite) can drop it.
@@ -193,16 +186,6 @@ async function main() {
);
}
try {
stopNativeStageSync.stop();
} catch (error) {
exitCode = 1;
log.error(
'stage sync shutdown failed: %s',
error instanceof Error ? error.message : String(error),
);
}
try {
hookManager.dispose();
} catch (error) {
-347
View File
@@ -1,347 +0,0 @@
import {
readFileSync,
writeFileSync,
mkdirSync,
statSync,
openSync,
readSync,
closeSync,
fstatSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createLogger, type Logger } from '@snowluma/common/logger';
export const STAGE_FILE_NAME = 's7.log';
export const MIRROR_LIMIT_BYTES = 1024 * 1024;
const VERSION_HEADER = /^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
export function isVersionHeader(line: string): boolean {
return VERSION_HEADER.test(line);
}
export function lineSeverity(line: string): 'info' | 'error' {
const parts = line.trim().split(/\s+/);
return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info';
}
export function publicLine(version: string, raw: string): string {
return `${version} ${raw.trim()}`;
}
function byteSize(lines: readonly string[]): number {
if (lines.length === 0) {
return 0;
}
return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8');
}
export function trimMirror(text: string, limit = MIRROR_LIMIT_BYTES): string {
const lines = text.split('\n').filter((line) => line.length > 0);
const size = () => byteSize(lines);
while (lines.length > 0 && size() > limit) {
const body = lines.findIndex((line) => !isVersionHeader(line));
if (body >= 0) {
lines.splice(body, 1);
continue;
}
if (lines.length <= 1) {
break;
}
lines.shift();
}
if (lines.length === 0) {
return '';
}
return `${lines.join('\n')}\n`;
}
export function appendEvents(
mirror: string,
version: string,
events: readonly string[],
limit = MIRROR_LIMIT_BYTES,
): string {
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
if (fresh.length === 0) {
return mirror;
}
const header = `v${version}`;
const lines = mirror.split('\n').filter((line) => line.length > 0);
let lastHeader = '';
for (const line of lines) {
if (isVersionHeader(line)) {
lastHeader = line;
}
}
const next = [...lines];
if (lastHeader !== header) {
next.push(header);
}
next.push(...fresh);
return trimMirror(`${next.join('\n')}\n`, limit);
}
export function tempStagePath(
platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): string {
if (platform === 'win32') {
const base = env.TMP || env.TEMP || os.tmpdir();
return path.join(base, STAGE_FILE_NAME);
}
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
}
export function errorCode(error: unknown): string {
if (error && typeof error === 'object' && 'code' in error) {
const code = (error as { code?: unknown }).code;
if (typeof code === 'string' && code) {
return code;
}
}
return 'ERR';
}
export interface StageSyncOptions {
version: string;
dataDir: string;
tempPath: string;
log?: Logger;
intervalMs?: number;
}
interface IngestResult {
mirror: string;
offset: number;
lines: string[];
missing: boolean;
errorCode?: string;
}
export function ingestTemp(args: {
tempText: string;
offset: number;
mirror: string;
version: string;
missing?: boolean;
errorCode?: string;
}): IngestResult {
if (args.missing) {
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
}
if (args.errorCode) {
return {
mirror: args.mirror,
offset: args.offset,
lines: [],
missing: false,
errorCode: args.errorCode,
};
}
const start = args.offset > args.tempText.length ? 0 : args.offset;
const chunk = args.tempText.slice(start);
const newline = chunk.lastIndexOf('\n');
if (newline < 0) {
return { mirror: args.mirror, offset: start, lines: [], missing: false };
}
const complete = chunk.slice(0, newline + 1);
const lines = complete
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
return {
mirror: appendEvents(args.mirror, args.version, lines),
offset: start + newline + 1,
lines,
missing: false,
};
}
function readOffset(file: string): number {
try {
const raw = readFileSync(file, 'utf8').trim();
const value = Number(raw);
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
} catch {
return 0;
}
}
function readTemp(file: string): { text: string; missing: boolean; errorCode?: string } {
let fd: number | undefined;
try {
fd = openSync(file, 'r');
const info = fstatSync(fd);
const size = info.size;
if (size > 8 * 1024 * 1024) {
return { text: '', missing: false, errorCode: 'E2BIG' };
}
const buf = Buffer.alloc(size);
let got = 0;
while (got < size) {
const n = readSync(fd, buf, got, size - got, got);
if (n <= 0) {
break;
}
got += n;
}
return { text: buf.subarray(0, got).toString('utf8'), missing: false };
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return { text: '', missing: true };
}
return { text: '', missing: false, errorCode: code };
} finally {
if (fd !== undefined) {
closeSync(fd);
}
}
}
export function startNativeStageSync(options: StageSyncOptions): { stop: () => void } {
const log = options.log ?? createLogger('native');
const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME);
const offsetPath = path.join(options.dataDir, 's7.off');
let offset = readOffset(offsetPath);
let failed = false;
let stopped = false;
const tick = () => {
if (stopped) {
return;
}
let tempSize = 0;
try {
tempSize = statSync(options.tempPath).size;
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return;
}
if (!failed) {
failed = true;
log.error('sync failed %s', code);
}
return;
}
if (tempSize < offset) {
offset = 0;
}
const temp = readTemp(options.tempPath);
if (temp.missing) {
return;
}
if (temp.errorCode) {
if (!failed) {
failed = true;
log.error('sync failed %s', temp.errorCode);
}
return;
}
let mirror = '';
try {
mirror = readFileSync(mirrorPath, 'utf8');
} catch (error) {
if (errorCode(error) !== 'ENOENT') {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
}
const ingested = ingestTemp({
tempText: temp.text,
offset,
mirror,
version: options.version,
});
if (ingested.lines.length === 0 && ingested.offset === offset) {
failed = false;
return;
}
try {
mkdirSync(options.dataDir, { recursive: true });
writeFileSync(mirrorPath, ingested.mirror);
writeFileSync(offsetPath, `${ingested.offset}\n`);
offset = ingested.offset;
failed = false;
} catch (error) {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
for (const line of ingested.lines) {
const text = publicLine(options.version, line);
if (lineSeverity(line) === 'error') {
log.error('%s', text);
} else {
log.info('%s', text);
}
}
};
tick();
const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref();
return {
stop() {
stopped = true;
clearInterval(timer);
},
};
}
+4
View File
@@ -527,6 +527,10 @@ function prepareGlobalSettingsJson(
const normalized = normalizeGlobalSettings(raw);
const canonical: Record<string, unknown> = { rkey: normalized.rkey };
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'videoUploadConcurrency')) {
canonical.videoUploadConcurrency = normalized.videoUploadConcurrency;
}
// Missing is the existing one-shot migration sentinel: startup scans legacy
// onebot*.json only until snowluma.json first carries this key.
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) {
+17 -24
View File
@@ -1,6 +1,7 @@
import { APP_VERSION } from '@snowluma/common/version';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { resolveWebuiTarget } from '@snowluma/common/webui-target';
import { registerStaticFrontend } from './static-frontend';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { getRuntimeIntegrity, hasLowProcessIntegrity } from '@snowluma/bridge';
import {
@@ -636,6 +637,15 @@ export async function initWebUI(
updateRoot?: string;
} = {},
): Promise<{ port: number; stop: () => Promise<void> }> {
const webuiTarget = resolveWebuiTarget(process.env.SNOWLUMA_WEBUI_TARGET);
if (webuiTarget) {
log.info(
'presentation target enabled: %s (runtime override; saved appearance is preserved)',
webuiTarget,
);
}
const host = listener.host || '127.0.0.1';
const tlsEnabled = listener.tlsEnabled === true;
const bootCheck = checkListenerExposure({
@@ -2163,6 +2173,11 @@ export async function initWebUI(
'save global config failed: %s',
err instanceof Error ? err.message : String(err),
);
if (err instanceof RangeError) {
return c.json({ success: false, message: err.message }, 400);
}
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
});
@@ -2267,29 +2282,7 @@ export async function initWebUI(
// Build path is relative to the bundled / dev __dirname. SPA fallback to
// index.html so client-side routes (if any) keep working.
const staticRoot = path.resolve(__dirname, 'client');
app.use('/*', serveStatic({ root: staticRoot }));
const indexHtmlPath = path.join(staticRoot, 'index.html');
app.get('*', (c) => {
// SPA fallback: only for navigations that didn't hit a static asset.
if (
c.req.path.startsWith('/api/') ||
c.req.path.startsWith('/avatar/') ||
c.req.path.startsWith('/ui-asset/')
) {
return c.text('not found', 404);
}
if (existsSync(indexHtmlPath)) {
const html = readFileSync(indexHtmlPath, 'utf8');
return c.html(html);
}
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
});
registerStaticFrontend(app, staticRoot, webuiTarget);
const finalPort = await findAvailablePort(desiredPort, { host });
@@ -0,0 +1,34 @@
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import type { Hono, Context } from 'hono';
import { serveStatic } from '@hono/node-server/serve-static';
import { injectWebuiTarget, type WebuiTarget } from '@snowluma/common/webui-target';
/** All document entry paths share runtime injection, including direct index.html requests. */
export function registerStaticFrontend(app: Hono, root: string, target: WebuiTarget | null): void {
const indexPath = path.join(root, 'index.html');
const document = (c: Context) => {
if (!existsSync(indexPath)) {
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
}
// A packaged frontend can be reused with a different deployment target on restart.
c.header('Cache-Control', 'no-store');
return c.html(injectWebuiTarget(readFileSync(indexPath, 'utf8'), target));
};
app.get('/', document);
app.get('/index.html', document);
app.use('/*', serveStatic({ root }));
app.get('*', (c) => {
if (['/api/', '/avatar/', '/ui-asset/'].some((prefix) => c.req.path.startsWith(prefix))) {
return c.text('not found', 404);
}
return document(c);
});
}
+11 -3
View File
@@ -754,12 +754,20 @@ describe('apis/contacts / invite-card pending application', () => {
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
expect(api.getGroupInviteCardSequence(12345)).toBeUndefined();
api.rememberGroupInviteCardSequence(12345, 778899);
api.rememberGroupInviteCardSequence(0, 1);
api.rememberGroupInviteCardSequence(1, 0);
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(true);
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(false);
expect(api.getGroupInviteCardSequence(12345)).toBe(778899);
expect(api.findGroupInviteCardGroupBySequence(778899)).toBe(12345);
expect(api.findGroupInviteCardGroupBySequence(1)).toBeUndefined();
});
it('requires a group when different groups have the same card sequence', () => {
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
api.rememberGroupInviteCardSequence(12345, 778899);
api.rememberGroupInviteCardSequence(67890, 778899);
expect(() => api.findGroupInviteCardGroupBySequence(778899)).toThrow('multiple groups');
expect(api.findGroupInviteCardGroupBySequence(778899, 67890)).toBe(67890);
});
});
@@ -6,7 +6,7 @@ import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPtt: vi.fn() }));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() }));
describe('forward metadata through upload and cached reads', () => {
@@ -35,7 +35,7 @@ function message(...elems: Elem[]): PushMsgBody {
};
}
function setup(downloads: Map<string, LongMsgResult>) {
function setup(downloads: Map<string, LongMsgResult>, selfUin = '10001') {
const requested: string[] = [];
const bridge = mockBridge({
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
@@ -61,21 +61,194 @@ function setup(downloads: Map<string, LongMsgResult>) {
};
}),
});
bridge.identity.uin = selfUin;
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const ctx = {
selfId: 10001,
selfId: Number(selfUin),
bridge: { apis: { forward } },
converterCtx: {
selfId: 10001,
selfId: Number(selfUin),
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
} as unknown as OneBotInstanceContext;
return { api: buildApiContext(ctx), requested };
return { api: buildApiContext(ctx), requested, bridge, forward };
}
function plainResult(text: string): LongMsgResult {
return {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [message({ text: { str: text } })] },
},
],
};
}
function nestedResult(inner: string, key: string, body?: PushMsgBody): LongMsgResult {
return {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [message(forwardCard('xml', inner, key))] },
},
{
actionCommand: key,
actionData: { msgBody: [body ?? message({ text: { str: 'inner content' } })] },
},
],
};
}
async function fillCache(
api: ReturnType<typeof setup>['api'],
downloads: Map<string, LongMsgResult>,
prefix: string,
count: number,
): Promise<void> {
for (let index = 0; index < count; index++) {
const id = `${prefix}-${index}`;
downloads.set(id, plainResult(id));
await api.getForwardMsg(id);
}
}
describe('get_forward_msg / cache lifetime', () => {
it('bounds cached results while refreshing recently read results', async () => {
const downloads = new Map([
['cache-cold', plainResult('cold')],
['cache-hot', plainResult('hot')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('cache-cold');
await api.getForwardMsg('cache-hot');
await fillCache(api, downloads, 'cache-pressure', 510);
await api.getForwardMsg('cache-hot');
await fillCache(api, downloads, 'cache-overflow', 1);
requested.length = 0;
await api.getForwardMsg('cache-hot');
await api.getForwardMsg('cache-cold');
expect(requested).toEqual(['cache-cold']);
});
it('isolates cached content between bridge accounts', async () => {
const first = setup(new Map([['same-resource', plainResult('account one')]]));
const second = setup(new Map([['same-resource', plainResult('account two')]]), '10002');
await first.api.getForwardMsg('same-resource');
expect((await second.api.getForwardMsg('same-resource'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'account two' } },
]);
expect(second.requested).toEqual(['same-resource']);
});
it('keeps nested results with a hot outer result under cache pressure', async () => {
const downloads = new Map([['hot-outer', nestedResult('hot-inner', 'hot-inner-key')]]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('hot-outer');
await fillCache(api, downloads, 'nested-pressure', 511);
await api.getForwardMsg('hot-inner');
await fillCache(api, downloads, 'nested-overflow', 1);
requested.length = 0;
expect((await api.getForwardMsg('hot-outer'))[0]?.message).toEqual([
{ type: 'forward', data: { id: 'hot-inner' } },
]);
expect((await api.getForwardMsg('hot-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual([]);
});
it('keeps an inner result attached to its outer result after sender enrichment', async () => {
const nameless = message({ text: { str: 'unnamed sender' } });
nameless.responseHead!.grp!.memberCard = '';
const downloads = new Map([
['enrich-outer', nestedResult('enrich-inner', 'enrich-key', nameless)],
]);
const { api, requested, bridge } = setup(downloads);
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
{ uin: 20002, nickname: 'resolved nickname', card: 'resolved card' },
]);
await api.getForwardMsg('enrich-outer');
await fillCache(api, downloads, 'enrich-pressure', 511);
requested.length = 0;
expect((await api.getForwardMsg('enrich-inner'))[0]).toMatchObject({
sender: { nickname: 'resolved card' },
});
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
await api.getForwardMsg('enrich-outer');
await api.getForwardMsg('enrich-inner');
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
expect(requested).toEqual([]);
});
it('retains a shared inner result while another containing outer result remains cached', async () => {
const downloads = new Map([
['shared-outer-a', nestedResult('shared-inner', 'shared-key-a')],
['shared-outer-b', nestedResult('shared-inner', 'shared-key-b')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('shared-outer-a');
await api.getForwardMsg('shared-outer-b');
await fillCache(api, downloads, 'shared-pressure', 510);
await api.getForwardMsg('shared-outer-a');
await fillCache(api, downloads, 'shared-overflow', 1);
requested.length = 0;
expect((await api.getForwardMsg('shared-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual([]);
});
it('restores all nested results when an evicted outer result is downloaded again', async () => {
const downloads = new Map([
['restore-outer', nestedResult('restore-inner', 'restore-key')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('restore-outer');
await api.getForwardMsg('restore-inner');
await fillCache(api, downloads, 'restore-pressure', 512);
requested.length = 0;
await api.getForwardMsg('restore-outer');
expect((await api.getForwardMsg('restore-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual(['restore-outer']);
});
it('does not resurrect evicted nested results when enrichment finishes late', async () => {
const nameless = message({ text: { str: 'late sender' } });
nameless.responseHead!.grp!.memberCard = '';
const downloads = new Map([
['late-outer', nestedResult('late-inner', 'late-key', nameless)],
]);
const { api, requested, bridge } = setup(downloads);
const members = [{ uin: 20002, nickname: 'late name', card: '' }];
let finishEnrichment!: () => void;
const enrichment = new Promise<typeof members>((resolve) => {
finishEnrichment = () => resolve(members);
});
bridge.apis.contacts.fetchGroupMemberList.mockReturnValueOnce(enrichment);
await api.getForwardMsg('late-outer');
const pending = api.getForwardMsg('late-inner');
await vi.waitFor(() =>
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce(),
);
await fillCache(api, downloads, 'late-pressure', 512);
finishEnrichment();
expect((await pending)[0]).toMatchObject({ sender: { nickname: 'late name' } });
requested.length = 0;
await expect(api.getForwardMsg('late-inner')).rejects.toThrow('payload is empty');
await api.getForwardMsg('late-outer');
expect((await api.getForwardMsg('late-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'late sender' } },
]);
expect(requested).toEqual(['late-inner', 'late-outer']);
});
});
describe('get_forward_msg / nested downloads (#529)', () => {
it.each(['xml', 'lightApp'] as const)(
'resolves siblings and three levels of %s forwards from one outer payload',
@@ -33,13 +33,14 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array()),
}));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array()),
uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array() })),
}));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
}));
import { ForwardApi } from '../../src/bridge/apis/forward';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
@@ -107,6 +108,49 @@ function findLightAppJson(msgBody: PushMsgBody[]): {
}
describe('forward / nested upload wire alignment', () => {
it('bounds uploaded results while keeping a recently read nested upload together', async () => {
let sequence = 0;
const sendRawPacket = vi.fn(async (command: string) => {
if (command !== 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg') {
throw new Error('test cache miss');
}
return uploadResponseWithResId(`upload-cache-${++sequence}`);
});
const bridge = mockBridge({ sendRawPacket });
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const outer = await forward.upload([
{
userUin: 111,
nickname: 'outer',
elements: [],
innerForward: [
{
userUin: 222,
nickname: 'inner',
elements: [{ type: 'text', text: 'nested upload' }],
},
],
},
]);
const filler = [{ userUin: 111, nickname: 'filler', elements: [] }];
for (let index = 0; index < 511; index++) {
await forward.upload(filler);
}
await forward.fetch('upload-cache-1');
await forward.upload(filler);
const uploadedCount = sendRawPacket.mock.calls.length;
const sameBridgeApi = new ForwardApi(bridge as unknown as BridgeContext);
expect((await sameBridgeApi.fetch(outer))[0]?.elements[0]?.resId).toBe('upload-cache-1');
expect((await sameBridgeApi.fetch('upload-cache-1'))[0]?.elements).toEqual([
{ type: 'text', text: 'nested upload' },
]);
expect(sendRawPacket).toHaveBeenCalledTimes(uploadedCount);
await expect(forward.fetch('upload-cache-3')).rejects.toThrow('test cache miss');
});
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
// Inner upload returns inner-res; outer upload returns outer-res.
const responses = ['inner-res', 'outer-res'];
@@ -0,0 +1,188 @@
import { describe, expect, it, vi } from 'vitest';
import { deflateSync, gunzipSync, gzipSync } from 'node:zlib';
import type { Elem } from '@snowluma/proto-defs/element';
import type {
LongMsgResult,
RecvLongMsgReq,
RecvLongMsgResp,
SendLongMsgReq,
SendLongMsgResp,
} from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
import type { MessageElement } from '@snowluma/protocol/events';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/bridge/apis/forward';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { mockBridge } from './_helpers';
const OUTER_RES_ID = 'outer-resid';
const INNER_UUID = 'C125CE25-AE7E-4E1A-ABDC-9750918162EB';
const INNER_FILE_NAME = `MultiMsg_${INNER_UUID}`;
function packetResult(responseData: Uint8Array) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(responseData),
};
}
function residLessForwardCard(): Elem {
const xml =
`<msg serviceID="35" templateID="1" action="viewMultiMsg" ` +
`m_fileName="${INNER_FILE_NAME}" tSum="2" flag="3" />`;
const data = Buffer.concat([Buffer.from([1]), deflateSync(Buffer.from(xml))]);
return { richMsg: { serviceId: 35, template1: data } };
}
function message(...elems: Elem[]): PushMsgBody {
return {
responseHead: {
fromUin: 20002,
fromUid: 'sender-uid',
grp: { groupUin: 12345, memberCard: 'alice' },
},
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
body: { richText: { elems } },
};
}
function outerResult(innerActionCommand?: string): LongMsgResult {
return {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [message(residLessForwardCard())] },
},
...(innerActionCommand
? [
{
actionCommand: innerActionCommand,
actionData: {
msgBody: [
message({ text: { str: 'inner one' } }),
message({ text: { str: 'inner two' } }),
],
},
},
]
: []),
],
};
}
function setup(innerActionCommand?: string) {
const requested: string[] = [];
const uploads: SendLongMsgReq[] = [];
const sendRawPacket = vi.fn(async (command: string, bytes: Uint8Array) => {
if (command.endsWith('SsoRecvLongMsg')) {
const resId = protobuf_decode<RecvLongMsgReq>(bytes).info!.resId!;
requested.push(resId);
return packetResult(
protobuf_encode<RecvLongMsgResp>({
result: {
resId,
payload:
resId === OUTER_RES_ID
? gzipSync(
protobuf_encode<LongMsgResult>(
outerResult(innerActionCommand),
),
)
: undefined,
},
}),
);
}
expect(command).toMatch(/SsoSendLongMsg$/);
const upload = protobuf_decode<SendLongMsgReq>(bytes);
uploads.push(upload);
return packetResult(
protobuf_encode<SendLongMsgResp>({ result: { resId: `rebuilt-${uploads.length}` } }),
);
});
const bridge = mockBridge({ sendRawPacket });
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const sendGroup = vi.fn(async (_groupId: number, _elements: MessageElement[]) => ({
messageId: 1,
sequence: 2,
clientSequence: 3,
random: 4,
timestamp: 1700000001,
}));
const ctx = {
selfId: 10001,
bridge: {
identity: { nickname: 'SnowLuma' },
apis: { forward, message: { sendGroup } },
},
messageStore: {
findEvent: () => ({
message: [{ type: 'forward', data: { id: OUTER_RES_ID } }],
}),
storeEvent: vi.fn(),
},
converterCtx: {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
cacheMessageMeta: vi.fn(),
dispatchEvent: vi.fn(),
} as unknown as OneBotInstanceContext;
return { api: buildApiContext(ctx), requested, uploads, sendGroup };
}
describe('resid-less nested forwards (#589)', () => {
it.each([INNER_UUID, INNER_FILE_NAME])(
'resolves an outer piggyback keyed by %s without another download',
async (innerActionCommand) => {
const { api, requested } = setup(innerActionCommand);
const outer = await api.getForwardMsg(OUTER_RES_ID);
expect(outer[0]?.message).toEqual([{ type: 'forward', data: { id: INNER_FILE_NAME } }]);
const inner = await api.getForwardMsg(INNER_FILE_NAME);
expect(inner.map((node) => node.message)).toEqual([
[{ type: 'text', data: { text: 'inner one' } }],
[{ type: 'text', data: { text: 'inner two' } }],
]);
expect(requested).toEqual([OUTER_RES_ID]);
},
);
it('rebuilds both layers before sending to another group', async () => {
const { api, requested, uploads, sendGroup } = setup(INNER_UUID);
await expect(api.forwardSingleMsg(77, { groupId: 65432 })).resolves.toHaveProperty(
'messageId',
);
expect(requested).toEqual([OUTER_RES_ID]);
expect(uploads).toHaveLength(2);
const outerBytes = gunzipSync(Buffer.from(uploads[1]!.info!.payload!));
const outer = protobuf_decode<LongMsgResult>(outerBytes);
expect(outer.action).toHaveLength(2);
expect(outerBytes.toString()).not.toContain(INNER_FILE_NAME);
expect(sendGroup).toHaveBeenCalledOnce();
expect(sendGroup.mock.calls[0]![1]).toEqual([
expect.objectContaining({ type: 'forward', resId: 'rebuilt-2' }),
]);
});
it('fails before upload or send when the inner piggyback is unavailable', async () => {
const { api, requested, uploads, sendGroup } = setup();
await expect(api.forwardSingleMsg(77, { groupId: 65432 })).rejects.toThrow(
'download forward message payload is empty',
);
expect(requested).toEqual([OUTER_RES_ID, INNER_FILE_NAME]);
expect(uploads).toHaveLength(0);
expect(sendGroup).not.toHaveBeenCalled();
});
});
@@ -2,6 +2,14 @@ import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb';
import type { OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
import type {
GetGroupAdminPermissionsResponse,
GetGroupAdminReceiveVerifyResponse,
SetGroupAdminPermissionsRequest,
SetGroupAdminReceiveVerifyRequest,
SetGroupAdminReceiveVerifyResponse,
} from '@snowluma/proto-defs/oidb-actions/group-admin-permissions';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import type {
Oidb0x8a0Req,
Oidb0x8a7Resp,
@@ -113,6 +121,160 @@ function packRobotExt(robotMemberSwitch?: number, robotMemberExamine?: number) {
}
describe('apis/group-admin', () => {
it.each([
[0, true],
[64, false],
[undefined, null],
] as const)(
'maps receive-verification state %s without inventing missing permissions',
async (flag, enabled) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<GetGroupAdminPermissionsResponse>>({
body: {
groupCode: 12345n,
members: [
{
memberUin: 67890n,
ext: { permissions: { items: [{ item: 1, value: 2 }] } },
},
],
},
}),
),
);
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<GetGroupAdminReceiveVerifyResponse>>({
body: {
groupCode: 12345n,
members: [
{
identity: { uid: 'resolved-uid', uin: 67890n },
memberFlagExt: flag,
},
],
},
}),
),
);
await expect(
new GroupAdminApi(bridge as unknown as BridgeContext).getAdminPermissions(
12345,
67890,
),
).resolves.toEqual({
group_id: 12345,
user_id: 67890,
recall_member_message: null,
kick_member: false,
kick_member_per_day: null,
receive_verify: enabled,
});
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.resolveUserUid).toHaveBeenCalledExactlyOnceWith(67890, 12345);
},
);
it.each(['OidbSvcTrpcTcp.0x9164_2', 'OidbSvcTrpcTcp.0xfe7_4'])(
'rejects the combined snapshot when %s fails',
async (failedCommand) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (command: string) => {
if (command === failedCommand) {
return packOidbFail(1287);
}
if (command === 'OidbSvcTrpcTcp.0x9164_2') {
return packResponse(
protobuf_encode<OidbBase<GetGroupAdminPermissionsResponse>>({
body: { groupCode: 12345n, members: [{ memberUin: 67890n }] },
}),
);
}
return packResponse(
protobuf_encode<OidbBase<GetGroupAdminReceiveVerifyResponse>>({
body: {
groupCode: 12345n,
members: [{ identity: { uid: 'resolved-uid' }, memberFlagExt: 0 }],
},
}),
);
});
await expect(
new GroupAdminApi(bridge as unknown as BridgeContext).getAdminPermissions(
12345,
67890,
),
).rejects.toThrow('OIDB error 1287');
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
},
);
it('propagates identity resolution failures when reading administrator permissions', async () => {
const bridge = mockBridge();
bridge.resolveUserUid.mockRejectedValueOnce(new Error('identity unavailable'));
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<GetGroupAdminPermissionsResponse>>({
body: { groupCode: 12345n, members: [{ memberUin: 67890n }] },
}),
),
);
await expect(
new GroupAdminApi(bridge as unknown as BridgeContext).getAdminPermissions(12345, 67890),
).rejects.toThrow('identity unavailable');
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
});
it('writes administrator capabilities and receive-verification through separate services', async () => {
const bridge = mockBridge();
const api = new GroupAdminApi(bridge as unknown as BridgeContext);
await api.setAdminPermissions(12345, 67890, { recallMemberMessage: false });
const [permissionCmd, permissionBytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(permissionCmd).toBe('OidbSvcTrpcTcp.0x9c1c_2');
expect(
protobuf_decode<OidbBase<SetGroupAdminPermissionsRequest>>(permissionBytes).body,
).toEqual({
groupCode: 12345n,
memberUin: 67890n,
permissions: [{ item: 2, value: 2, extra: null }],
});
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<SetGroupAdminReceiveVerifyResponse>>({
body: { groupCode: 12345n, result: { successfulUins: [67890n] } },
}),
),
);
await api.setAdminReceiveVerify(12345, 67890, false);
const [verifyCmd, verifyBytes] = bridge.sendRawPacket.mock.calls[1]!;
expect(verifyCmd).toBe('OidbSvcTrpcTcp.0x904_1');
expect(
protobuf_decode<OidbBase<SetGroupAdminReceiveVerifyRequest>>(verifyBytes).body,
).toEqual({
groupCode: 12345n,
operation: { adminUins: [67890n], authority: 1, operate: 0 },
});
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
});
it('does not swallow an unconfirmed receive-verification response', async () => {
const bridge = mockBridge();
await expect(
new GroupAdminApi(bridge as unknown as BridgeContext).setAdminReceiveVerify(
12345,
67890,
true,
),
).rejects.toThrow('missing or mismatched group');
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
});
it('muteMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).muteMember(12345, 67890, 600);
+55 -6
View File
@@ -287,7 +287,7 @@ describe('apis/group-file', () => {
expect(publishSpy).not.toHaveBeenCalled();
});
it('upload returns success even when the chat post fails (file is still uploaded)', async () => {
it('upload reports chat publication failure while retaining the completed file identity', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
@@ -297,14 +297,63 @@ describe('apis/group-file', () => {
),
);
const api = new GroupFileApi(bridge as any);
const publishSpy = vi
.spyOn(api, 'publish')
.mockRejectedValueOnce(new Error('message rejected'));
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-tolerant' });
const cause = new Error('message rejected');
const publishSpy = vi.spyOn(api, 'publish').mockRejectedValueOnce(cause);
await expect(api.upload(12345, '/path/file.bin')).rejects.toMatchObject({
message:
'group file uploaded (fileId=fid-tolerant) but chat post failed: message rejected',
cause,
});
expect(publishSpy).toHaveBeenCalledOnce();
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
expect(staged.cleanup).toHaveBeenCalledOnce();
});
it.each([true, false])(
'publishes only after the upload is confirmed (confirmed=%s)',
async (confirmed) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-confirm',
uploadIp: '127.0.0.1',
uploadPort: 443,
fileKey: new Uint8Array([1]),
checkKey: new Uint8Array([2]),
},
},
}),
),
);
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
const failure = new Error('highway upload transport failed; current chunk unconfirmed');
vi.mocked(highwayClient.uploadHighwayHttp).mockImplementationOnce(async () => {
expect(publishSpy).not.toHaveBeenCalled();
if (!confirmed) {
throw failure;
}
});
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
if (confirmed) {
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm');
} else {
await expect(upload).rejects.toBe(failure);
expect(publishSpy).not.toHaveBeenCalled();
}
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
},
);
it('upload caches the upload metadata for later resend by file_id', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
+6 -6
View File
@@ -352,12 +352,12 @@ describe('apis/profile', () => {
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<OidbBase<Oidb0xe17Resp>>({
body: {
jsonBody: JSON.stringify({
rpt_block_list: [{ uin: 10001 }, { uin: 10002 }],
}),
} as any,
protobuf_encode<Oidb0xe17Resp>({
jsonBody: JSON.stringify({
ActionStatus: 'OK',
ErrorCode: 0,
rpt_block_list: [{ uin: 10001 }, { uin: 10002 }],
}),
}),
),
});
@@ -0,0 +1,189 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import * as qzonePublic from '@snowluma/protocol/web/qzone-public';
import { QzoneApi } from '../../src/bridge/apis/qzone';
import { mockApiHub, mockBridge } from './_helpers';
const cookies = { p_skey: 'PSK' };
const feed = {
cell_common: { union_id: { feed_id: 'opaque-id' } },
cell_feed_transfer: { future: true },
};
const comment = { id: 'comment-id', user: { uid: 'commenter' }, unknown: [1, 2] };
const reply = { id: 'reply-id', user: { uid: 'recipient' } };
const content = [{ type: 0, content: 'text', future: { enabled: true } }];
const user = { uin: '10001', uid: 'self-uid', nick: 'self-nick' };
const result = { feeds: [], has_more: false, next_cursor: null, unknown: { preserved: true } };
function makeApi() {
const getCookies = vi.fn().mockResolvedValue(cookies);
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
return { api: new QzoneApi(bridge as never), bridge, getCookies };
}
const cases = [
{
method: 'getQzoneHomeFeeds',
invoke: (api: QzoneApi) => api.getHomeFeeds(20002, 'cursor'),
args: [cookies, '10001', '20002', 'cursor'],
},
{
method: 'getQzonePublicCapabilities',
invoke: (api: QzoneApi) => api.getPublicCapabilities(),
args: [cookies, '10001'],
},
{
method: 'getQzonePublicFeeds',
invoke: (api: QzoneApi) => api.getPublicFeeds('cursor'),
args: [cookies, '10001', 'cursor'],
},
{
method: 'getQzonePublicFeedDetail',
invoke: (api: QzoneApi) => api.getPublicFeedDetail(feed),
args: [cookies, feed],
},
{
method: 'getQzonePublicComments',
invoke: (api: QzoneApi) => api.getPublicComments(feed, 'cursor'),
args: [cookies, feed, 'cursor'],
},
{
method: 'getQzonePublicReplies',
invoke: (api: QzoneApi) => api.getPublicReplies(feed, comment, 'cursor', 5),
args: [cookies, feed, comment, 'cursor', 5],
},
{
method: 'setQzonePublicUpvote',
invoke: (api: QzoneApi) => api.setPublicUpvote(feed, false),
args: [cookies, feed, false],
},
{
method: 'setQzonePublicLike',
invoke: (api: QzoneApi) => api.setPublicLike(feed, false),
args: [cookies, feed, false],
},
{
method: 'setQzonePublicCommentLike',
invoke: (api: QzoneApi) => api.setPublicCommentLike(feed, comment, false, reply),
args: [cookies, feed, comment, false, reply],
},
{
method: 'commentQzonePublicFeed',
invoke: (api: QzoneApi) => api.commentPublicFeed(feed, content),
args: [cookies, feed, user, content],
},
{
method: 'replyQzonePublicFeed',
invoke: (api: QzoneApi) => api.replyPublicFeed(feed, comment, content, reply),
args: [cookies, feed, user, comment, content, reply],
},
{
method: 'deleteQzonePublicComment',
invoke: (api: QzoneApi) => api.deletePublicComment(feed, comment),
args: [cookies, feed, comment],
},
{
method: 'deleteQzonePublicReply',
invoke: (api: QzoneApi) => api.deletePublicReply(feed, comment, reply),
args: [cookies, feed, comment, reply],
},
{
method: 'setQzonePublicFollow',
invoke: (api: QzoneApi) => api.setPublicFollow(feed, false),
args: [cookies, feed, false],
},
{
method: 'forwardQzonePublicFeed',
invoke: (api: QzoneApi) => api.forwardPublicFeed(feed, 'reason'),
args: [cookies, feed, 'reason'],
},
] as const;
describe('apis/qzone public', () => {
afterEach(() => vi.restoreAllMocks());
it('generates a share card with the account cookies and preserves its notice', async () => {
const { api, getCookies } = makeApi();
const card = { ark: '{}', requires_confirmation: true, notice: '所有人可见' };
const request = vi.spyOn(qzonePublic, 'getQzoneShareArk').mockResolvedValue(card);
expect(await api.getShareArk(feed)).toBe(card);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(request).toHaveBeenCalledExactlyOnceWith(cookies, feed);
request.mockRejectedValueOnce(new Error('share denied'));
await expect(api.getShareArk(feed)).rejects.toThrow('share denied');
});
it.each(cases)(
'$method uses current-account cookies and preserves upstream objects',
async ({ method, invoke, args }) => {
const { api, getCookies } = makeApi();
const request = vi.spyOn(qzonePublic, method).mockResolvedValue(result);
expect(await invoke(api)).toBe(result);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(request).toHaveBeenCalledExactlyOnceWith(...args);
},
);
it.each(cases)(
'$method propagates cookie and upstream failures without replay',
async ({ method, invoke }) => {
const { api, getCookies } = makeApi();
const request = vi
.spyOn(qzonePublic, method)
.mockRejectedValue(new Error('upstream denied'));
await expect(invoke(api)).rejects.toThrow('upstream denied');
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
await expect(invoke(api)).rejects.toThrow('cookie failure');
expect(request).toHaveBeenCalledTimes(1);
},
);
it('keeps documented defaults and omits an optional reply target', async () => {
const { api } = makeApi();
const feeds = vi.spyOn(qzonePublic, 'getQzonePublicFeeds').mockResolvedValue(result);
const replies = vi.spyOn(qzonePublic, 'getQzonePublicReplies').mockResolvedValue(result);
const upvote = vi.spyOn(qzonePublic, 'setQzonePublicUpvote').mockResolvedValue(result);
const like = vi.spyOn(qzonePublic, 'setQzonePublicLike').mockResolvedValue(result);
const commentLike = vi
.spyOn(qzonePublic, 'setQzonePublicCommentLike')
.mockResolvedValue(result);
const follow = vi.spyOn(qzonePublic, 'setQzonePublicFollow').mockResolvedValue(result);
const forward = vi.spyOn(qzonePublic, 'forwardQzonePublicFeed').mockResolvedValue(result);
const replyRequest = vi
.spyOn(qzonePublic, 'replyQzonePublicFeed')
.mockResolvedValue(result);
await api.getPublicFeeds();
await api.getPublicReplies(feed, comment);
await api.setPublicUpvote(feed);
await api.setPublicLike(feed);
await api.setPublicCommentLike(feed, comment);
await api.setPublicFollow(feed);
await api.forwardPublicFeed(feed);
await api.replyPublicFeed(feed, comment, 'text');
expect(feeds).toHaveBeenCalledWith(cookies, '10001', undefined);
expect(replies).toHaveBeenCalledWith(cookies, feed, comment, '', 20);
expect(upvote).toHaveBeenCalledWith(cookies, feed, true);
expect(like).toHaveBeenCalledWith(cookies, feed, true);
expect(commentLike).toHaveBeenCalledWith(cookies, feed, comment, true, undefined);
expect(follow).toHaveBeenCalledWith(cookies, feed, true);
expect(forward).toHaveBeenCalledWith(cookies, feed, '');
expect(replyRequest).toHaveBeenCalledWith(cookies, feed, user, comment, 'text', undefined);
});
it('binds comment authors to the current account even when its uid is unavailable', async () => {
const { api, bridge } = makeApi();
Object.assign(bridge.identity, { selfUid: undefined });
const request = vi.spyOn(qzonePublic, 'commentQzonePublicFeed').mockResolvedValue(result);
await api.commentPublicFeed(feed, 'text');
expect(request).toHaveBeenCalledWith(
cookies,
feed,
{ uin: '10001', uid: '', nick: 'self-nick' },
'text',
);
});
});
+114 -2
View File
@@ -20,6 +20,61 @@ describe('apis/qzone', () => {
return { bridge, getCookies, fetchSpy };
}
it.each([undefined, 20002])(
'getProfile reads owner %s with the current account credentials',
async (targetUin) => {
const { bridge, getCookies } = bridgeWithWeb();
const profile = { name: 'My space', description: 'Notes' };
const getProfile = vi.spyOn(qzoneWeb, 'getQzoneProfile').mockResolvedValue(profile);
expect(await new QzoneApi(bridge as never).getProfile(targetUin)).toEqual(profile);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(getProfile).toHaveBeenCalledWith(
{ p_skey: 'PSK' },
'10001',
targetUin?.toString(),
);
},
);
it('getProfile propagates cookie and protocol failures', async () => {
const { bridge, getCookies } = bridgeWithWeb();
const api = new QzoneApi(bridge as never);
const getProfile = vi
.spyOn(qzoneWeb, 'getQzoneProfile')
.mockRejectedValue(new Error('denied'));
await expect(api.getProfile(20002)).rejects.toThrow('denied');
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
await expect(api.getProfile()).rejects.toThrow('cookie failure');
expect(getProfile).toHaveBeenCalledTimes(1);
});
it.each([{ name: 'New name' }, { description: '' }, { name: '', description: 'New notes' }])(
'setProfile writes only the supplied fields to the current account (%j)',
async (profile) => {
const { bridge, getCookies } = bridgeWithWeb();
const setProfile = vi.spyOn(qzoneWeb, 'setQzoneProfile').mockResolvedValue();
await new QzoneApi(bridge as never).setProfile(profile);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(setProfile).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', profile);
},
);
it('setProfile propagates cookie and protocol failures', async () => {
const { bridge, getCookies } = bridgeWithWeb();
const api = new QzoneApi(bridge as never);
const setProfile = vi
.spyOn(qzoneWeb, 'setQzoneProfile')
.mockRejectedValue(new Error('captcha required'));
await expect(api.setProfile({ name: 'New name' })).rejects.toThrow('captcha required');
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
await expect(api.setProfile({ description: 'Notes' })).rejects.toThrow('cookie failure');
expect(setProfile).toHaveBeenCalledTimes(1);
});
it.each([undefined, 20002])(
'getMsgDetail uses current-account credentials for owner %s',
async (targetUin) => {
@@ -77,10 +132,18 @@ describe('apis/qzone', () => {
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const feedsSpy = vi
.spyOn(qzoneWeb, 'getQzoneFeeds')
.mockResolvedValue({ feeds: [], has_more: false });
.mockResolvedValue({ feeds: [], has_more: false, next_cursor: null });
await new QzoneApi(bridge as never).getFeeds(3, 20);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20, undefined);
await new QzoneApi(bridge as never).getFeeds(1, 20, 'opaque-cursor');
expect(feedsSpy).toHaveBeenLastCalledWith(
{ p_skey: 'PSK' },
'10001',
1,
20,
'opaque-cursor',
);
});
it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => {
@@ -290,4 +353,53 @@ describe('apis/qzone', () => {
richval,
);
});
it.each([undefined, 20002])(
'routes replies with the account cookies and post owner (%s)',
async (targetUin) => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const target = {
commentId: '0',
commentUin: '30003',
replyTo: { uin: '40004', name: 'Reader' },
};
const result = { comment_id: '8', parent_comment_id: '0', parent_comment_uin: 30003 };
const replySpy = vi.spyOn(qzoneWeb, 'replyQzoneComment').mockResolvedValue(result);
const commentSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg');
const out = await new QzoneApi(bridge as never).comment(
'TIDX',
'Reply',
targetUin,
undefined,
undefined,
target,
);
expect(out).toEqual(result);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(replySpy).toHaveBeenCalledWith(
{ p_skey: 'PSK' },
'10001',
String(targetUin ?? 10001),
'TIDX',
'Reply',
target,
);
expect(commentSpy).not.toHaveBeenCalled();
},
);
it('rejects reply images before acquiring cookies or sending', async () => {
const getCookies = vi.fn();
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
await expect(
new QzoneApi(bridge as never).comment('TIDX', 'Reply', undefined, 1, 'URL', {
commentId: '0',
commentUin: '30003',
}),
).rejects.toThrow('images are not supported');
expect(getCookies).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,234 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import { protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from '../src/bridge/bridge';
const bridges: Bridge[] = [];
const timestamp = 1_700_000_000;
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((accept) => {
resolve = accept;
});
return { promise, resolve };
}
afterEach(async () => {
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
vi.useRealTimers();
vi.restoreAllMocks();
});
function packet(): PacketInfo {
const uid = Buffer.from('u_test_peer');
const header = Buffer.alloc(8);
header[0] = 1;
header[1] = uid.length;
header.writeUInt32LE(9, 4);
return {
pid: 1234,
uin: '10001',
source: 'client-message',
serviceCmd: CLIENT_MESSAGE_RECEIPT_CMD,
seqId: 42,
retCode: 0,
fromClient: false,
body: Buffer.concat([
header,
uid,
protobuf_encode<SendMessageResponse>({ privateSequence: 87, timestamp1: timestamp }),
]),
};
}
function response(): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<SsoGetC2cMsgResponse>({
friendUid: 'u_test_peer',
messages: [
{
responseHead: {
fromUin: 10001,
fromUid: 'u_test_self',
toUin: 20002,
toUid: 'u_test_peer',
},
contentHead: {
msgType: 166,
sequence: 9,
ntMsgSeq: 87,
timestamp,
msgId: 123456,
},
body: { richText: { elems: [{ text: { str: 'hello' } }] } },
},
],
}),
),
};
}
async function setup() {
const bridge = new Bridge(IdentityService.memory('10001'));
bridges.push(bridge);
vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockResolvedValue([
{ uin: 10001, uid: 'u_test_self', nickname: 'self', remark: '' },
]);
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => response());
const sender = { sendPacket };
bridge.bindPid(1234, sender);
await bridge.whenRosterWarmupSettled();
const received = vi.fn();
bridge.events.on('friend_message', received);
return { bridge, sendPacket, sender, received };
}
describe('Bridge client message recovery', () => {
it('does not retry a delayed lookup on a detached or replacement connection', async () => {
const ctx = await setup();
vi.useFakeTimers();
ctx.sendPacket.mockResolvedValue({
...response(),
responseData: Buffer.from(
protobuf_encode<SsoGetC2cMsgResponse>({
result: 100000301,
friendUid: 'u_test_peer',
}),
),
});
const work = ctx.bridge.onPacket(packet());
const rejected = expect(work).rejects.toThrow('inactive connection');
await vi.advanceTimersByTimeAsync(0);
expect(ctx.sendPacket).toHaveBeenCalledOnce();
ctx.bridge.detachPid(1234);
const replacement = vi.fn<PacketSender['sendPacket']>();
ctx.bridge.bindPid(1234, { sendPacket: replacement });
await vi.runAllTimersAsync();
await rejected;
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(replacement).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('dispatches confirmed content through the normal event pipeline', async () => {
const ctx = await setup();
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'friend_message',
selfUin: 10001,
senderUin: 10001,
peerUin: 20002,
ntMsgSeq: 87,
clientSeq: 9,
elements: [{ type: 'text', text: 'hello' }],
}),
);
});
it('does not treat an ordinary packet with the same command as a receipt', async () => {
const ctx = await setup();
const ordinary = packet();
delete ordinary.source;
await ctx.bridge.onPacket(ordinary);
expect(ctx.sendPacket).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('shares an in-flight lookup across repeated receipts and ordinary PID observations', async () => {
const ctx = await setup();
const result = deferred<SendPacketResult>();
const started = deferred<void>();
ctx.sendPacket.mockImplementation(() => {
started.resolve();
return result.promise;
});
const first = ctx.bridge.onPacket(packet());
await started.promise;
ctx.bridge.bindPid(1234, ctx.sender);
const duplicate = ctx.bridge.onPacket(packet());
await Promise.resolve();
result.resolve(response());
await Promise.all([first, duplicate]);
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledOnce();
});
it.each(['detach', 'replace', 'reattach', 'dispose'] as const)(
'rejects a lookup completed after %s',
async (action) => {
const ctx = await setup();
const result = deferred<SendPacketResult>();
const started = deferred<void>();
ctx.sendPacket.mockImplementation(() => {
started.resolve();
return result.promise;
});
const work = ctx.bridge.onPacket(packet());
const rejected = expect(work).rejects.toThrow('inactive connection');
await started.promise;
let disposal: Promise<void> | undefined;
if (action === 'dispose') {
disposal = ctx.bridge.dispose();
} else if (action === 'replace') {
ctx.bridge.bindPid(1234, { sendPacket: vi.fn() });
} else {
ctx.bridge.detachPid(1234);
if (action === 'reattach') {
ctx.bridge.bindPid(1234, ctx.sender);
}
}
result.resolve(response());
await rejected;
await disposal;
expect(ctx.received).not.toHaveBeenCalled();
},
);
it('queries the originating connection even when another process is active', async () => {
const ctx = await setup();
const other = { sendPacket: vi.fn<PacketSender['sendPacket']>() };
ctx.bridge.bindPid(4321, other);
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(other.sendPacket).not.toHaveBeenCalled();
});
it('rejects unavailable, detached and wrong-account receipts before querying', async () => {
const ctx = await setup();
await expect(ctx.bridge.onPacket({ ...packet(), retCode: -1 })).rejects.toThrow(
'unavailable',
);
await expect(ctx.bridge.onPacket({ ...packet(), uin: '20002' })).rejects.toThrow('account');
ctx.bridge.detachPid(1234);
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('inactive connection');
expect(ctx.sendPacket).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('surfaces lookup failure and allows a later receipt to retry', async () => {
const ctx = await setup();
ctx.sendPacket.mockRejectedValueOnce(new Error('lookup failed'));
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('lookup failed');
expect(ctx.received).not.toHaveBeenCalled();
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledTimes(2);
expect(ctx.received).toHaveBeenCalledOnce();
});
});
@@ -115,6 +115,55 @@ describe('BridgeManager shutdown', () => {
}
});
it('reopening is not poisoned by an already-failed close', async () => {
const failing = deferred();
manager.onHookLogin(101, '10001', sender);
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(failing.promise);
manager.onPidDisconnected(101);
failing.reject(new Error('close failed'));
await nextTurn();
// The failed close stays in the bookkeeping (dispose still reports
// it), but the reopening gate must absorb the rejection instead of
// passing it down — a rejected gate would keep the identity DB of
// every future session for this UIN closed until process restart.
manager.onHookLogin(202, '10001', sender);
const beforeOpen = vi.mocked(IdentityService.openForUin).mock.calls.at(-1)![2]!;
await expect(beforeOpen).resolves.toBeUndefined();
});
it('reopening waits for all closes to settle even when one of them fails', async () => {
const failing = deferred();
const slow = deferred();
manager.onHookLogin(101, '10001', sender);
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(failing.promise);
manager.onPidDisconnected(101);
manager.onHookLogin(202, '10001', sender);
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(slow.promise);
manager.onPidDisconnected(202);
failing.reject(new Error('close failed'));
await nextTurn();
manager.onHookLogin(303, '10001', sender);
const beforeOpen = vi.mocked(IdentityService.openForUin).mock.calls.at(-1)![2]!;
let ready = false;
const opening = beforeOpen.then(() => {
ready = true;
});
try {
await nextTurn();
// Still waiting for the pending close...
expect(ready).toBe(false);
} finally {
slow.resolve();
}
// ...and the already-failed close must not reject the gate.
await opening;
});
it('ignores late transport callbacks after shutdown starts', async () => {
const shutdown = manager.dispose();
manager.onHookLogin(101, '10001', sender);
@@ -2,7 +2,11 @@ import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type {
SendMessageRequest,
SendMessageResponse,
SendRichText,
} from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
@@ -10,6 +14,9 @@ import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-acti
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
encodePrivateRichText: vi.fn(async () =>
protobuf_encode<SendRichText>({ elems: [{ text: { str: 'stub media elem' } }] }),
),
}));
// Imported statically (not via `await import` inside each `it`) so the heavy
+35 -3
View File
@@ -1,3 +1,4 @@
import type { SendRichText } from '@snowluma/proto-defs/action';
// Regression test for the c2c-vs-group businessType asymmetry that made
// private-chat video / record sends bounce with `send private message
// rejected: result=79`. The receive-side decoder
@@ -22,15 +23,16 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
}));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])),
uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array([4, 5, 6]) })),
}));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])),
}));
import { protobuf_encode } from '@snowluma/proton';
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload';
@@ -569,3 +571,33 @@ describe('element-builder / forward preview', () => {
).rejects.toBeInstanceOf(MessageElementValidationError);
});
});
describe('private voice compatibility', () => {
const context = { bridge: fakeBridge, userUid: 'u_peer', scene: 'direct-private' } as const;
const record = { type: 'record', url: 'voice.amr' } as const;
const modern = Uint8Array.of(4, 5, 6);
it('keeps all modern clips when one legacy voice slot cannot represent the message', async () => {
const compat = protobuf_encode<{ ptt?: pb<4, bytes> }>({ ptt: Uint8Array.of(8, 4) });
vi.mocked(uploadPtt)
.mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat })
.mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat });
const rich = await encodePrivateRichText([record, record], context);
expect(protobuf_decode<{ ptt?: pb<4, bytes> }>(rich).ptt).toBeNull();
expect(protobuf_decode<SendRichText>(rich).elems).toHaveLength(2);
});
it('sends modern voice when no compatibility data is available and rejects malformed data', async () => {
vi.mocked(uploadPtt).mockResolvedValueOnce({ msgInfo: modern });
expect(
protobuf_decode<SendRichText>(await encodePrivateRichText([record], context)).elems,
).toHaveLength(1);
vi.mocked(uploadPtt).mockResolvedValueOnce({
msgInfo: modern,
compatQMsg: Uint8Array.of(0x12, 0),
});
await expect(encodePrivateRichText([record], context)).rejects.toThrow(
'incomplete playback information',
);
});
});
@@ -0,0 +1,14 @@
08ed241064180022ef0412ec0432b9020af6010af3010a7d08fb3d122030303030303030303030303030303030303030
303030303030303030303030301a28303030303030303030303030303030303030303030303030303030303030303030
30303030303030222430303030303030303030303030303030303030303030303030303030303030302e616d722a0408
032001400312637878787878787878787878787878787878787878787878787878787878787878787878787878787878
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
7878787878787878787818012081808080012881800138fa0a123e0a0612047465737412001a3208818080800110012a
22081e121e0505050505050505050505050505050505050505050505050505050505055a040800380042ad02122baa02
289a0125aa0322081e121e05050505050505050505050505050505050505050505050505050505050522fd0108041081
808080011a97017878787878787878787878787878787878787878787878787878787878787878787878787878787878
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
78787878787878787878787878782210000000000000000000000000000000002a243030303030303030303030303030
3030303030303030303030303030303030302e616d7230fb3d3a16000000000000000000000000000000000000000000
005801980103e80101
@@ -208,6 +208,56 @@ describe('MessageApi history pagination', () => {
expect(result.map((message) => message.ntMsgSeq)).toEqual([63213, 63214, 63215]);
});
it('splits a 200-message private history request into bounded pages', async () => {
mockC2cRoamFetch.mockImplementation(
async (_sender, _identity, _self, _friend, time, count) => ({
messages: Array.from({ length: count }, (_, index) => ({
...gm(time - index),
kind: 'friend_message',
ntMsgSeq: time - index,
})),
cursor: { time: time - count, random: 1 },
isComplete: false,
}),
);
const result = await runHistory(
new MessageApi(ctx).getC2cLatestHistory('u_friend', 200, 10001, 1000),
);
expect(result).toHaveLength(200);
expect(mockC2cRoamFetch.mock.calls.map((call) => call[5])).toEqual([100, 100]);
expect(result.map((message) => message.ntMsgSeq)).toEqual(
Array.from({ length: 200 }, (_, index) => 801 + index),
);
});
it('honors completion even when the last page still includes a cursor', async () => {
mockC2cRoamFetch.mockResolvedValue({
messages: [{ ...gm(1), kind: 'friend_message', ntMsgSeq: 1 }],
cursor: { time: 100, random: 2 },
isComplete: true,
});
const result = await runHistory(
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1000),
);
expect(result).toHaveLength(1);
expect(mockC2cRoamFetch).toHaveBeenCalledOnce();
});
it('does not return partial history after a later request fails', async () => {
mockC2cRoamFetch
.mockResolvedValueOnce({
messages: [{ ...gm(1), kind: 'friend_message', ntMsgSeq: 1 }],
cursor: { time: 100, random: 2 },
isComplete: false,
})
.mockRejectedValueOnce(new Error('SsoGetRoamMsg failed: result=123'));
const assertion = expect(
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1000),
).rejects.toThrow('result=123');
await vi.runAllTimersAsync();
await assertion;
});
it('rejects a stalled private roam cursor instead of returning a partial page', async () => {
mockC2cRoamFetch.mockResolvedValue({
cursor: { time: 1700000100, random: 0 },
@@ -15,8 +15,9 @@
// 一连接,但仍全部成功。
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import type { HttpConn0x6FF501Response } from '@snowluma/proto-defs/highway';
import { protobuf_encode } from '@snowluma/proton';
import type { HttpConn0x6FF501Response, ReqDataHighwayHead } from '@snowluma/proto-defs/highway';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { unpackHighwayFrame } from '@snowluma/protocol/highway/utils';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { EventEmitter } from 'events';
@@ -79,6 +80,8 @@ class FakeSocket extends EventEmitter {
writable = true;
posts = 0;
headers: string[] = [];
frames: Buffer[] = [];
closeBeforeResponse = false;
connectFailure?: Error | 'timeout';
private connectTimer?: ReturnType<typeof setTimeout>;
private buf = Buffer.alloc(0);
@@ -141,6 +144,7 @@ class FakeSocket extends EventEmitter {
}
this.headers.push(s.slice(0, he));
this.frames.push(Buffer.from(this.buf.subarray(he + 4, total)));
this.buf = this.buf.subarray(total);
this.posts += 1;
const thisPost = this.posts;
@@ -157,6 +161,14 @@ class FakeSocket extends EventEmitter {
return;
}
if (this.closeBeforeResponse) {
this.writable = false;
this.readableEnded = true;
this.emit('end');
this.emit('close');
return;
}
if (thisPost === this.errorAfterPartialOnPost) {
const full = httpWrap(this.responseFrame);
this.emit('data', full.subarray(0, full.length - 3));
@@ -443,7 +455,7 @@ describe('fetchHighwaySession trace lifecycle', () => {
});
});
describe('Highway initial connection selection', () => {
describe('Highway connection selection', () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
@@ -582,24 +594,160 @@ describe('Highway initial connection selection', () => {
expect(source.closeCount).toBe(1);
});
it('stays on the selected node after data was sent without an acknowledgement', async () => {
it.each([0, HIGHWAY_BLOCK_SIZE])(
'retries only the unconfirmed chunk at offset %i on the next node',
async (offset) => {
vi.useFakeTimers();
installFactory(() => {
const host = createConnectionMock.mock.lastCall?.[0].host;
const socket = new FakeSocket(
buildEmptyHighwayResponseFrame(),
'keepalive',
host === '192.0.2.1' && offset > 0 ? 2 : -1,
);
socket.closeBeforeResponse = host === '192.0.2.1' && offset === 0;
return socket;
});
const session = sessionWithCandidates();
const original = structuredClone(session);
const source = new RecordingChunkSource(offset + 80);
const extend = new Uint8Array([0x12, 0x34]);
const upload = uploadHighwayHttp(
makeBridge(),
session,
71,
source,
new Uint8Array(16),
extend,
);
const completed = expect(upload).resolves.toBeUndefined();
await Promise.all([completed, vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
session.servers,
);
const [failed, recovered] = createdSockets as FakeSocket[];
expect(recovered!.posts).toBe(1);
const first = unpackHighwayFrame(failed!.frames.at(-1)!);
const retry = unpackHighwayFrame(recovered!.frames[0]!);
const firstHead = protobuf_decode<ReqDataHighwayHead>(first.head);
const retryHead = protobuf_decode<ReqDataHighwayHead>(retry.head);
expect(retry.body).toEqual(first.body);
expect(retryHead).toEqual({
...firstHead,
msgBaseHead: { ...firstHead.msgBaseHead, retryTimes: 1 },
});
expect(retryHead.msgSegHead?.dataOffset ?? 0n).toBe(BigInt(offset));
expect(retryHead.bytesReqExtendInfo).toEqual(Buffer.from(extend));
expect(source.reads).toEqual(
offset === 0
? [{ offset: 0, length: 80 }]
: [
{ offset: 0, length: HIGHWAY_BLOCK_SIZE },
{ offset, length: 80 },
],
);
expect(source.closeCount).toBe(1);
expect(session).toEqual(original);
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
},
);
it('bounds retries across nodes and reports the unconfirmed chunk without advancing progress', async () => {
vi.useFakeTimers();
installFactory(
(idx) =>
new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', idx === 0 ? 1 : -1),
);
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.closeBeforeResponse = true;
return socket;
});
const session = sessionWithCandidates();
const source = new RecordingChunkSource(80);
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const upload = uploadHighwayHttp(
makeBridge(),
session,
71,
source,
new Uint8Array(16),
new Uint8Array(),
);
const failed = expect(upload).rejects.toThrow(
/transport failed after 3 attempts.*acknowledgedBytes=0.*unconfirmed/,
);
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
session.servers[0],
session.servers[1],
session.servers[0],
]);
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
expect(source.closeCount).toBe(1);
const terminals = highwayTrace(entries).filter((entry) =>
entry.message.startsWith('highway_put_terminal '),
);
expect(terminals).toHaveLength(1);
expect(terminals[0]!.message).toContain('outcome=failed reason=transport_exhausted');
expect(terminals[0]!.message).toContain('uploadedBytes=0');
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
} finally {
unsubscribe();
}
});
it('continues after the actual failed node and skips candidates that cannot reconnect', async () => {
vi.useFakeTimers();
installFactory(() => {
const host = createConnectionMock.mock.lastCall?.[0].host;
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
if (host === '192.0.2.1') {
socket.connectFailure = new Error('ECONNREFUSED');
} else if (host === '192.0.2.2') {
socket.closeBeforeResponse = true;
} else if (host === '192.0.2.3') {
socket.connectFailure = 'timeout';
}
return socket;
});
const session = {
...makeSession(),
servers: Array.from({ length: 4 }, (_, i) => ({ host: `192.0.2.${i + 1}`, port: 443 })),
};
const source = new RecordingChunkSource(80);
const upload = uploadHighwayHttp(
makeBridge(),
session,
1004,
new RecordingChunkSource(1),
71,
source,
new Uint8Array(16),
new Uint8Array(),
);
await Promise.all([expect(upload).resolves.toBeUndefined(), vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
session.servers,
);
expect((createdSockets as FakeSocket[]).map((socket) => socket.posts)).toEqual([
0, 1, 0, 1,
]);
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
expect(source.closeCount).toBe(1);
});
it('keeps the successful node when the peer closes after acknowledgement', async () => {
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'closeafter'));
const session = sessionWithCandidates();
await uploadHighwayHttp(
makeBridge(),
session,
71,
new RecordingChunkSource(HIGHWAY_BLOCK_SIZE + 80),
new Uint8Array(16),
new Uint8Array(),
);
const completed = expect(upload).resolves.toBeUndefined();
await vi.runAllTimersAsync();
await completed;
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
session.servers[0],
session.servers[0],
@@ -0,0 +1,471 @@
import { EventEmitter } from 'node:events';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import type { ReqDataHighwayHead, RespDataHighwayHead } from '@snowluma/proto-defs/highway';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from '@snowluma/protocol/highway/utils';
import {
uploadHighwayHttp,
type ChunkSource,
type HighwaySession,
} from '@snowluma/protocol/highway';
const { connect } = vi.hoisted(() => ({ connect: vi.fn() }));
vi.mock('net', () => ({ default: { createConnection: connect } }));
const BLOCK = 1024 * 1024;
const bridge = { identity: { uin: '10001' } } as unknown as BridgeContext;
const session: HighwaySession = {
sigSession: new Uint8Array([1]),
sessionKey: new Uint8Array(),
servers: [
{ host: '192.0.2.1', port: 80 },
{ host: '192.0.2.2', port: 80 },
],
};
const turn = () => new Promise<void>((resolve) => setImmediate(resolve));
interface Request {
socket: TestSocket;
head: ReqDataHighwayHead;
bytes: Uint8Array;
offset: number;
respond(override?: RespDataHighwayHead): void;
frame(bytes: Uint8Array): void;
disconnect(): void;
}
let requests: Request[];
let sockets: TestSocket[];
let active: Set<Request>;
let peak: number;
let onRequest: (request: Request) => void;
class TestSocket extends EventEmitter {
destroyed = false;
readableEnded = false;
writable = true;
private buffer = Buffer.alloc(0);
setTimeout() {
return this;
}
write(data: Uint8Array, callback: (error?: Error) => void): boolean {
if (this.destroyed) {
callback(new Error('socket closed'));
return false;
}
this.buffer = Buffer.concat([this.buffer, data]);
const end = this.buffer.indexOf('\r\n\r\n');
if (end >= 0) {
const length = Number(
this.buffer
.subarray(0, end)
.toString()
.match(/Content-Length: (\d+)/i)![1],
);
if (this.buffer.length >= end + 4 + length) {
const { head, body } = unpackHighwayFrame(
this.buffer.subarray(end + 4, end + 4 + length),
);
const decoded = protobuf_decode<ReqDataHighwayHead>(head);
this.buffer = this.buffer.subarray(end + 4 + length);
const request: Request = {
socket: this,
head: decoded,
bytes: body,
offset: Number(decoded.msgSegHead?.dataOffset ?? 0n),
frame: (frame) => {
if (this.destroyed) {
throw new Error('reply on destroyed socket');
}
active.delete(request);
this.emit(
'data',
Buffer.concat([
Buffer.from(
`HTTP/1.1 200 OK\r\nContent-Length: ${frame.length}\r\n\r\n`,
),
frame,
]),
);
},
respond: (override = {}) =>
request.frame(
packHighwayFrame(
protobuf_encode<RespDataHighwayHead>({
msgBaseHead: { seq: decoded.msgBaseHead?.seq },
msgSegHead: {
filesize: decoded.msgSegHead?.filesize,
dataOffset: decoded.msgSegHead?.dataOffset,
dataLength: decoded.msgSegHead?.dataLength,
},
...override,
}),
new Uint8Array(),
),
),
disconnect: () => this.emit('error', new Error('ECONNRESET')),
};
expect([...active].some((item) => item.socket === this)).toBe(false);
requests.push(request);
active.add(request);
peak = Math.max(peak, active.size);
// Deliberately respond before the write callback. Real fast peers
// can reply while socket.write is still completing.
onRequest(request);
}
}
callback();
return true;
}
destroy() {
if (!this.destroyed) {
this.destroyed = true;
this.writable = false;
for (const request of active) {
if (request.socket === this) {
active.delete(request);
}
}
queueMicrotask(() => this.emit('close'));
}
return this;
}
}
class Source implements ChunkSource {
reads: number[] = [];
closes = 0;
constructor(readonly size: number) {}
async read(offset: number, length: number) {
this.reads.push(offset);
return new Uint8Array(length).fill(offset / BLOCK + 1);
}
async close() {
this.closes += 1;
}
}
function upload(source: ChunkSource, concurrency: number) {
return uploadHighwayHttp(bridge, session, 1005, source, new Uint8Array(16), new Uint8Array(), {
concurrency,
});
}
const level = getLogLevel();
beforeEach(() => {
requests = [];
sockets = [];
active = new Set();
peak = 0;
onRequest = () => {};
connect.mockReset().mockImplementation((_options, listener) => {
const socket = new TestSocket();
sockets.push(socket);
setImmediate(listener);
return socket;
});
});
afterEach(() => {
setLogLevel(level);
for (const socket of sockets) {
socket.destroy();
}
});
describe('bounded parallel highway uploads', () => {
it.each([2, 3, 4])(
'uses %i connections, accepts out-of-order acknowledgements and sends the tail last',
async (concurrency) => {
const source = new Source(6 * BLOCK + 17);
const confirmed = new Set<number>();
const checkAndAck = (request: Request) => {
if (request.offset === 6 * BLOCK) {
expect(confirmed.size).toBe(6);
}
expect(request.bytes.every((byte) => byte === request.offset / BLOCK + 1)).toBe(
true,
);
expect(Buffer.from(request.head.msgSegHead!.md5!)).toEqual(
Buffer.from(computeMd5(request.bytes)),
);
confirmed.add(request.offset);
request.respond();
};
const result = upload(source, concurrency);
await vi.waitFor(() => expect(requests).toHaveLength(concurrency));
expect(source.closes).toBe(0);
onRequest = checkAndAck;
for (const request of [...active].reverse()) {
checkAndAck(request);
}
await result;
expect(peak).toBe(concurrency);
expect(sockets).toHaveLength(concurrency);
expect(requests).toHaveLength(7);
expect(new Set(requests.map((request) => request.head.msgBaseHead?.seq)).size).toBe(7);
expect(source.closes).toBe(1);
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
},
);
it('logs confirmed bytes separately from the contiguous prefix after out-of-order replies', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const source = new Source(3 * BLOCK + 1);
try {
const result = upload(source, 3);
await vi.waitFor(() => expect(requests).toHaveLength(3));
requests[2].respond();
await vi.waitFor(() =>
expect(
entries.some((entry) =>
entry.message.includes('acknowledgedBytes=1048576 contiguousBytes=0'),
),
).toBe(true),
);
expect(requests).toHaveLength(3);
onRequest = (request) => request.respond();
requests[1].respond();
requests[0].respond();
await result;
const terminal = entries.filter((entry) =>
entry.message.startsWith('highway_put_terminal '),
);
expect(terminal).toHaveLength(1);
expect(terminal[0]?.message).toContain(`uploadedBytes=${source.size}`);
} finally {
unsubscribe();
}
});
it('surfaces repeated backpressure after the retry budget is exhausted', async () => {
const source = new Source(4 * BLOCK);
onRequest = (request) => {
if (request.offset === 0) {
request.respond({ errorCode: 102902 });
} else {
request.respond();
}
};
await expect(upload(source, 3)).rejects.toThrow(/error_code=102902/);
expect(requests.filter((request) => request.offset === 0)).toHaveLength(8);
expect(requests.some((request) => request.offset === 3 * BLOCK)).toBe(false);
expect(source.closes).toBe(1);
});
it('limits lookahead behind a slow chunk and recovers an idle connection failure', async () => {
const source = new Source(14 * BLOCK + 1);
onRequest = (request) => {
if (request.offset !== 0) {
request.respond();
}
};
const result = upload(source, 4);
await vi.waitFor(() => expect(requests).toHaveLength(10));
await turn();
expect(Math.max(...requests.map((request) => request.offset))).toBe(9 * BLOCK);
const idle = sockets.find(
(socket) => ![...active].some((request) => request.socket === socket),
)!;
idle.emit('error', new Error('idle connection reset'));
onRequest = (request) => request.respond();
requests[0].respond();
await result;
expect(requests).toHaveLength(15);
expect(source.closes).toBe(1);
});
it('retries only the unconfirmed range after a transport failure', async () => {
const source = new Source(6 * BLOCK);
let failed = false;
onRequest = (request) => {
if (request.offset === BLOCK && !failed) {
failed = true;
request.disconnect();
} else {
request.respond();
}
};
await upload(source, 3);
const retried = requests.filter((request) => request.offset === BLOCK);
expect(retried).toHaveLength(2);
expect(retried[1].bytes).toEqual(retried[0].bytes);
expect(retried[1].head.msgBaseHead?.retryTimes).toBe(1);
expect(retried[1].head.msgBaseHead?.seq).not.toBe(retried[0].head.msgBaseHead?.seq);
expect(source.reads).toHaveLength(6);
expect(requests.filter((request) => request.offset !== BLOCK)).toHaveLength(5);
expect(source.closes).toBe(1);
});
it.each([102902, 302902])(
'drains in-flight requests and reduces concurrency on %i',
async (code) => {
const source = new Source(7 * BLOCK);
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const result = upload(source, 4);
await vi.waitFor(() => expect(requests).toHaveLength(4));
requests[0].respond({ errorCode: code });
await vi.waitFor(() =>
expect(
entries.some((entry) =>
entry.message.includes('reducing concurrency from 4 to 1'),
),
).toBe(true),
);
await turn();
expect(requests).toHaveLength(4);
let afterDrainPeak = 0;
onRequest = (request) => {
afterDrainPeak = Math.max(afterDrainPeak, active.size);
request.respond();
};
for (const request of [...active]) {
request.respond();
}
await result;
expect(afterDrainPeak).toBe(1);
expect(requests.filter((request) => request.offset === 0)).toHaveLength(2);
expect(requests).toHaveLength(8);
expect(source.closes).toBe(1);
} finally {
unsubscribe();
}
},
);
it.each([
{ msgBaseHead: { seq: 999 } },
{ msgSegHead: { dataOffset: 99n } },
{ msgSegHead: { dataLength: 99 } },
{ msgSegHead: { filesize: 99n } },
])('rejects mismatched acknowledgements without retrying (case %#)', async (response) => {
const source = new Source(4 * BLOCK);
onRequest = (request) => request.respond(response);
await expect(upload(source, 3)).rejects.toThrow(/acknowledgement mismatch/);
expect(requests.every((request) => (request.head.msgBaseHead?.retryTimes ?? 0) === 0)).toBe(
true,
);
expect(requests.some((request) => request.offset === 3 * BLOCK)).toBe(false);
expect(source.closes).toBe(1);
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
});
it('rejects segment-level errors even when the top-level code is zero', async () => {
const source = new Source(4 * BLOCK);
onRequest = (request) => request.respond({ msgSegHead: { retCode: 921 } });
await expect(upload(source, 3)).rejects.toThrow(/segRetCode=921/);
expect(source.closes).toBe(1);
});
it('stops peers on rejection and waits for pending source reads before closing', async () => {
let release!: () => void;
let reading = false;
const source = new Source(5 * BLOCK);
const read = source.read.bind(source);
source.read = async (offset, length) => {
if (offset === BLOCK) {
reading = true;
await new Promise<void>((resolve) => {
release = resolve;
});
reading = false;
}
return read(offset, length);
};
const close = vi.spyOn(source, 'close').mockImplementation(async () => {
expect(reading).toBe(false);
});
const result = upload(source, 3);
const rejected = expect(result).rejects.toThrow(/error_code=921/);
await vi.waitFor(() => expect(requests).toHaveLength(2));
requests.find((request) => request.offset === 0)!.respond({ errorCode: 921 });
await turn();
expect(close).not.toHaveBeenCalled();
release();
await rejected;
expect(close).toHaveBeenCalledTimes(1);
expect(requests).toHaveLength(2);
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
});
it('stops after bounded transport retries without sending the final chunk', async () => {
const source = new Source(5 * BLOCK);
onRequest = (request) => {
if (request.offset === 0) {
request.disconnect();
} else {
request.respond();
}
};
await expect(upload(source, 3)).rejects.toThrow(/transport failed after 3 attempts/);
expect(requests.filter((request) => request.offset === 0)).toHaveLength(3);
expect(requests.some((request) => request.offset === 4 * BLOCK)).toBe(false);
expect(source.closes).toBe(1);
});
it.each([1, BLOCK + 1, 2 * BLOCK])('keeps a %i-byte upload on one connection', async (size) => {
onRequest = (request) => request.respond();
await upload(new Source(size), 4);
expect(peak).toBe(1);
expect(sockets).toHaveLength(1);
});
it('keeps legacy success responses without echo fields compatible', async () => {
onRequest = (request) => request.respond({ msgBaseHead: undefined, msgSegHead: undefined });
await upload(new Source(4 * BLOCK), 3);
expect(requests).toHaveLength(4);
});
it.each([0, 5, -1, 1.5, NaN])(
'rejects invalid concurrency %s and closes the source',
async (concurrency) => {
const source = new Source(4 * BLOCK);
await expect(upload(source, concurrency)).rejects.toThrow(/integer from 1 to 4/);
expect(source.closes).toBe(1);
expect(requests).toHaveLength(0);
},
);
it('rejects short reads instead of acknowledging bytes that were not uploaded', async () => {
const source = new Source(4 * BLOCK);
source.read = async () => new Uint8Array(1);
await expect(upload(source, 3)).rejects.toThrow(/expected 1048576/);
expect(requests).toHaveLength(0);
expect(source.closes).toBe(1);
});
});
@@ -132,6 +132,36 @@ describe('pipeline — runNtv2Upload', () => {
setLogLevel(previousLogLevel);
});
it('passes concurrency only for the sub-file that explicitly opts in', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: {
uKey: 'main-key',
subFileInfos: [{ uKey: 'cover-key' }],
msgInfo: { msgInfoBody: [{}, {}], extBizInfo: {} },
},
}),
});
const media = {
bytes: new Uint8Array([1]),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
};
await runNtv2Upload(
baseParams({
bridge,
uploads: [
{ ...media, source: 'top', cmdId: 1005, concurrency: 4 },
{ ...media, source: 0, cmdId: 1006 },
],
}),
);
const calls = vi.mocked(highway.uploadHighwayHttp).mock.calls;
expect(calls).toHaveLength(2);
expect(calls[0]?.[6]).toEqual({ concurrency: 4 });
expect(calls[1]?.[6]).toBeUndefined();
});
it('records fast-upload selection and one completed media terminal', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
@@ -1,3 +1,7 @@
import {
getVideoUploadConcurrency,
setVideoUploadConcurrency,
} from '@snowluma/protocol/highway/upload-settings';
// video-upload tests cover the fingerprint (fast-upload) path. The
// regular load path exercises ffmpeg + the OS temp dir + a streaming
// SHA1 implementation; that machinery has its own seams worth testing
@@ -9,7 +13,7 @@
// fastOnlyError difference (main has it; thumb doesn't — FALLBACK_THUMB
// always provides bytes), and the video-specific OIDB fields.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { promises as fsp } from 'fs';
import fs from 'fs';
import os from 'os';
@@ -44,11 +48,27 @@ const FINGERPRINT = {
} as any;
describe('video-upload', () => {
afterEach(() => setVideoUploadConcurrency(1));
beforeEach(() => {
vi.mocked(pipeline.runNtv2Upload).mockClear();
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
});
it('snapshots the global concurrency for video bodies without parallelizing covers', async () => {
expect(getVideoUploadConcurrency()).toBe(1);
setVideoUploadConcurrency(4);
const first = uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
setVideoUploadConcurrency(2);
await first;
const firstUpload = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(firstUpload.uploads[0]!.concurrency).toBe(4);
expect(firstUpload.uploads[1]!.concurrency).toBeUndefined();
await uploadVideoMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
const secondUpload = vi.mocked(pipeline.runNtv2Upload).mock.calls[1]![0];
expect(secondUpload.uploads[0]!.concurrency).toBe(2);
expect(secondUpload.uploads[1]!.concurrency).toBeUndefined();
});
it('retains successful upload metadata for self-sent history', async () => {
const node = { fileUuid: 'uploaded-resource', storeId: 1, info: { fileSize: 1234 } };
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
@@ -529,6 +530,7 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
groupInvites: new GroupInviteTracker(),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -1027,6 +1029,7 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
groupInvites: new GroupInviteTracker(),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
await pipeline.process(packet);
@@ -1,65 +0,0 @@
import { describe, expect, it } from 'vitest';
import {
appendEvents,
ingestTemp,
lineSeverity,
publicLine,
trimMirror,
} from '../src/native-stage-sync';
const VERSION = '1.14.22';
const EVENT = 'a'.repeat(64);
const infoLine = `2026-10-09T00:00:00Z 42 1 0 ${EVENT}`;
const failLine = `2026-10-09T00:00:01Z 42 1 1 ${EVENT} ${'b'.repeat(16)}=7`;
describe('native stage sync', () => {
it('keeps a version marker and copies the record without extra wording', () => {
const mirror = appendEvents('', VERSION, [infoLine, failLine]);
expect(mirror.startsWith(`v${VERSION}\n`)).toBe(true);
expect(mirror).toContain(infoLine);
expect(mirror).toContain(failLine);
const shown = [publicLine(VERSION, infoLine), publicLine(VERSION, failLine)].join('\n');
expect(shown).toBe(`${VERSION} ${infoLine}\n${VERSION} ${failLine}`);
});
it('opens a new version section without dropping the previous marker', () => {
const first = appendEvents('', '1.14.22', [infoLine]);
const second = appendEvents(first, '1.14.23', [failLine]);
expect(second).toContain('v1.14.22\n');
expect(second).toContain('v1.14.23\n');
expect(second.indexOf('v1.14.22')).toBeLessThan(second.indexOf(infoLine));
expect(second.indexOf('v1.14.23')).toBeLessThan(second.indexOf(failLine));
});
it('drops the oldest record first and keeps the version marker', () => {
const long = `2026-10-09T00:00:00Z 1 1 0 ${'c'.repeat(64)} ${'d'.repeat(40)}`;
let mirror = appendEvents('', VERSION, [long, long, long], 80);
mirror = trimMirror(mirror, 80);
expect(mirror).toContain(`v${VERSION}`);
expect(mirror.split('\n').filter((line) => line.startsWith('2026')).length).toBeLessThan(3);
});
it('treats severity 1 as a failure and ignores a missing file', () => {
expect(lineSeverity(failLine)).toBe('error');
expect(lineSeverity(infoLine)).toBe('info');
const ingested = ingestTemp({
tempText: `${infoLine}\n${failLine}\npartial`,
offset: 0,
mirror: '',
version: VERSION,
});
expect(ingested.lines).toEqual([infoLine, failLine]);
expect(ingested.mirror).toContain(`v${VERSION}\n`);
expect(ingested.offset).toBe(`${infoLine}\n${failLine}\n`.length);
const missing = ingestTemp({
tempText: '',
offset: 4,
mirror: 'keep',
version: VERSION,
missing: true,
});
expect(missing.mirror).toBe('keep');
expect(missing.lines).toEqual([]);
expect(missing.errorCode).toBeUndefined();
});
});
@@ -0,0 +1,91 @@
import { readFileSync } from 'node:fs';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { Elem } from '@snowluma/proto-defs/element';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import { IdentityService } from '@snowluma/protocol/identity-service';
import {
type bytes,
type pb,
type pb_repeated,
protobuf_decode,
protobuf_encode,
} from '@snowluma/proton';
import { expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
interface VoiceParts {
elems?: pb_repeated<2, bytes>;
ptt?: pb<4, bytes>;
}
interface UploadReply {
upload?: pb<2, { compat?: pb<8, bytes> }>;
}
interface OutgoingMessage {
body?: pb<3, { richText?: pb<1, VoiceParts> }>;
}
it('preserves the private voice returned for older clients alongside the modern voice', async () => {
// The upload reply from #614, with identifiers redacted and transport credentials removed.
const upload = Buffer.from(
readFileSync(
new URL('./fixtures/issue-614-private-voice-upload.hex', import.meta.url),
'utf8',
).replace(/\s/g, ''),
'hex',
);
const captured = protobuf_decode<OidbBase<UploadReply>>(Uint8Array.from(upload)).body!.upload!
.compat!;
const expected = protobuf_decode<VoiceParts>(captured);
expect(captured).toHaveLength(301);
expect(expected.ptt).toHaveLength(253);
let sent: VoiceParts | undefined;
class VoiceBridge extends Bridge {
override async resolveUserUid(): Promise<string> {
return 'u_peer';
}
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
let response: Uint8Array;
if (cmd === 'OidbSvcTrpcTcp.0x126d_100') {
response = upload;
} else if (cmd === 'MessageSvc.PbSendMsg') {
sent = protobuf_decode<OutgoingMessage>(body).body!.richText!;
response = protobuf_encode<SendMessageResponse>({ privateSequence: 88 });
} else {
throw new Error(`Unexpected packet ${cmd}`);
}
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(response),
};
}
}
const bridge = new VoiceBridge(IdentityService.memory('10000'));
await bridge.apis.message.sendPrivate(10001, [
{
type: 'record',
noByteFallback: true,
fileSize: 7931,
duration: 3,
md5Hex: '0'.repeat(32),
sha1Hex: '0'.repeat(40),
fileName: 'voice.amr',
},
]);
expect(protobuf_decode<Elem>(sent!.elems![0]!).commonElem).toMatchObject({
serviceType: 48,
businessType: 12,
});
expect(sent!.ptt).toEqual(expected.ptt);
expect(sent!.elems!.slice(1)).toEqual(expected.elems);
});
@@ -1,4 +1,5 @@
import { createRequire } from 'node:module';
import { readFileSync, readdirSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const require = createRequire(import.meta.url);
@@ -9,17 +10,48 @@ const { SUPPORTED_NODE_RANGE, isSupportedNodeVersion } =
};
describe('runtime Node.js preflight', () => {
it('accepts the documented minimum and newer versions', () => {
expect(SUPPORTED_NODE_RANGE).toBe('>=24');
expect(isSupportedNodeVersion('24.0.0')).toBe(true);
expect(isSupportedNodeVersion('24.21.0')).toBe(true);
expect(isSupportedNodeVersion('26.0.0')).toBe(true);
it.each(['24.22.1', '24.22.2', '24.23.0', '24.22.1+vendor.1', '26.12.1', '26.13.0', '27.0.0'])(
'accepts patched stable Node.js %s',
(version) => {
expect(isSupportedNodeVersion(version)).toBe(true);
},
);
it.each([
'22.23.4',
'23.99.99',
'24.0.0',
'24.21.0',
'24.22.0',
'25.99.99',
'26.0.0',
'26.11.99',
'26.12.0',
'24.22.1-rc.1',
'26.12.1-rc.1',
'not-a-version',
])('rejects unpatched, unsupported or malformed Node.js %s', (version) => {
expect(isSupportedNodeVersion(version)).toBe(false);
});
it('rejects older and malformed versions', () => {
expect(isSupportedNodeVersion('22.99.99')).toBe(false);
expect(isSupportedNodeVersion('23.99.99')).toBe(false);
expect(isSupportedNodeVersion('21.99.99')).toBe(false);
expect(isSupportedNodeVersion('not-a-version')).toBe(false);
it('keeps workspace requirements and the bundled runtime baseline aligned', () => {
expect(SUPPORTED_NODE_RANGE).toBe('^24.22.1 || >=26.12.1');
const root = new URL('../../../', import.meta.url);
const packages = readdirSync(new URL('packages/', root), { withFileTypes: true });
const manifests = [
new URL('package.json', root),
...packages
.filter((entry) => entry.isDirectory())
.map((entry) => new URL(`packages/${entry.name}/package.json`, root)),
];
for (const manifest of manifests) {
const pkg = JSON.parse(readFileSync(manifest, 'utf8'));
expect(pkg.engines.node, manifest.pathname).toBe(SUPPORTED_NODE_RANGE);
}
const baseline = readFileSync(new URL('.node-version', root), 'utf8').trim();
expect(baseline).toBe('24.22.1');
expect(isSupportedNodeVersion(baseline)).toBe(true);
});
});
+5 -4
View File
@@ -1,5 +1,5 @@
import { spawn } from 'node:child_process';
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { cp, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { builtinModules } from 'node:module';
import os from 'node:os';
import path from 'node:path';
@@ -14,7 +14,8 @@ let root: string;
let staging: string;
beforeAll(async () => {
compiled = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-'));
// Module resolution uses canonical paths, including when the temp directory is a symlink.
compiled = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-')));
const loaded = await loadConfigFromFile(
{ command: 'build', mode: 'production' },
fileURLToPath(new URL('../vite.config.ts', import.meta.url)),
@@ -114,7 +115,7 @@ afterAll(async () => {
await rm(compiled, { recursive: true, force: true });
});
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-'));
root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-')));
staging = await updateDirectory(root);
await releaseFixture(root, '1.0.0');
await cp(path.join(compiled, '1.0.0/index.mjs'), path.join(root, 'index.mjs'));
@@ -158,7 +159,7 @@ describe('packaged startup', () => {
expect(JSON.parse(result.output)).toEqual({
version: '1.0.0',
node: process.execPath,
cwd: os.tmpdir(),
cwd: await realpath(os.tmpdir()),
args: ['value with spaces'],
oldAlive: false,
});
+17
View File
@@ -679,6 +679,23 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
expect(canonical.webuiTls.enabled).toBe(false);
});
it('preserves video concurrency in backups and rejects invalid restored values', () => {
const prepare = (videoUploadConcurrency: number) =>
prepareRestorePlan(
backupWith({
'snowluma.json': {
encoding: 'utf8',
data: JSON.stringify({ videoUploadConcurrency }),
},
}),
{ restoreCredentials: false, readCurrent: () => null },
);
expect(JSON.parse(prepare(4).restore[0].data.toString('utf8')).videoUploadConcurrency).toBe(
4,
);
expect(() => prepare(5)).toThrow(/videoUploadConcurrency/);
});
it('accepts owner-supported whitespace trimming without accepting changed values', () => {
const prepared = prepareRestorePlan(
backupWith({
@@ -0,0 +1,47 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Hono } from 'hono';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { registerStaticFrontend } from '../src/webui/static-frontend';
let root: string;
const html = '<!doctype html><html><head><title>SnowLuma</title></head><body>app</body></html>';
beforeEach(() => {
root = mkdtempSync(path.join(tmpdir(), 'snowluma-presentation-'));
writeFileSync(path.join(root, 'index.html'), html);
writeFileSync(path.join(root, 'asset.js'), 'window.asset = true;');
});
afterEach(() => rmSync(root, { recursive: true, force: true }));
describe('runtime target document delivery', () => {
it.each(['/', '/index.html', '/settings?tab=appearance'])(
'injects on %s before authentication',
async (url) => {
const app = new Hono();
registerStaticFrontend(app, root, 'maibot');
const response = await app.request(url);
expect(response.status).toBe(200);
expect(response.headers.get('cache-control')).toBe('no-store');
expect(await response.text()).toContain('"target":"maibot"');
},
);
it('reuses the exact same built frontend for an unconfigured deployment', async () => {
const app = new Hono();
registerStaticFrontend(app, root, null);
expect(await (await app.request('/index.html')).text()).toBe(html);
});
it('does not inject into assets or API error responses', async () => {
const app = new Hono();
registerStaticFrontend(app, root, 'maibot');
expect(await (await app.request('/asset.js')).text()).toBe('window.asset = true;');
for (const url of ['/api/missing', '/avatar/missing', '/ui-asset/missing']) {
expect((await app.request(url)).status).toBe(404);
}
});
});
+391
View File
@@ -0,0 +1,391 @@
# MCP agent features
These additions preserve the existing tool names, action parameters, text results,
and read/write gates. No endpoint is contacted by catalog tools or by a local
runtime overview. The action catalog remains a bundled snapshot, not a claim
about the connected server's capabilities.
## Protocol compatibility and catalog caching
The same `snowluma-mcp` stdio command accepts MCP `2026-07-28` clients and
older clients using the `initialize` handshake. The official server SDK selects
the protocol for the connection. Modern clients can use `server/discover` and
per-request metadata without initialization; legacy clients keep their existing
configuration. This does not add a publicly listening MCP HTTP endpoint.
Modern replies carry the protocol's completion and server metadata. Cache hints
depend on whether a response contains static catalog data or private live state:
| Response | Lifetime | Scope |
| ----------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------ |
| `tools/list` | Five minutes | `private`; mode and client capabilities affect tool metadata and availability. |
| `resources/list` | Five minutes, or zero when events are enabled | `private`; UI capability and active event resources affect the list. |
| `resources/templates/list` | Five minutes | `public`; the bundled template list is static. |
| `resources/read` for the action catalog or message UI | Five minutes | `public`; these are bundled static assets. |
| `resources/read` for event resources | Zero | `private`; these contain account events and connection state. |
These are client cache hints, not a server-side result cache. Tool calls,
including the runtime overview, never receive these hints. The SDK omits
modern-only result fields for legacy clients. Unsupported protocol revisions
are rejected before action execution; they do not trigger an action retry.
## Call tracing
Every tool invocation gets a W3C trace context. Clients can supply `traceparent`
and optional `tracestate` in the tool request's `_meta`:
```json
{
"name": "query_action",
"arguments": { "action": "get_status" },
"_meta": {
"traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}
}
```
MCP preserves a valid caller trace ID and creates a new span ID for each call.
Without a valid parent it creates an independent trace. The returned
`_meta.traceparent` identifies that call, including tool errors; the existing
text and structured result envelopes remain unchanged. This works with both
protocol generations.
Ordinary requests, streams, automatic upload chunks, and upload cleanup forward
the call context in HTTP headers, never in OneBot action parameters. Concurrent
calls keep independent headers. To follow a call, match its traceparent in MCP
stderr diagnostics with SnowLuma's `http_trace` entry, then follow that entry's
existing `req#` through action lifecycle logs. SnowLuma correlation requires
TRACE logging and a valid authenticated HTTP request; the remote trace ID does
not replace its local request ID. No telemetry exporter is installed.
MCP's call diagnostics contain the known tool name, traceparent, outcome, failure
category and duration, not message contents, tokens, file paths or arbitrary metadata.
`tracestate` is validated with a maximum of 512 characters and 32 members; it is
forwarded but not logged. Invalid trace metadata produces a fixed diagnostic and
does not reject an otherwise valid action. `baggage` is neither forwarded nor
logged. Trace identifiers are correlation data, not authentication or permission.
## Optional execution services
Existing configurations keep working. Input completion and message previews are
additive tools; event connections and durable tasks require explicit configuration.
For example, set these variables in the MCP client's server environment, replacing
addresses, credentials and paths with the intended SnowLuma instance:
```json
{
"SNOWLUMA_MCP_MODE": "write",
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
"SNOWLUMA_MCP_TOKEN": "<your access token>",
"SNOWLUMA_MCP_EVENTS_URL": "ws://127.0.0.1:3001/event",
"SNOWLUMA_MCP_TASK_DIR": "/absolute/private/mcp-tasks",
"SNOWLUMA_MCP_UPLOAD_ROOT": "/absolute/allowed/uploads"
}
```
The HTTP and WebSocket addresses are independently configured server endpoints;
the WebSocket address is never guessed from the HTTP address. Events reuse
`SNOWLUMA_MCP_TOKEN` in an authorization header. Upload and task directories are
on the MCP host. Omit services that are not needed. Docs mode remains offline.
## Completing missing parameters
`query_action_with_input` and `invoke_action_with_input` use the same arguments,
action lookup and mode gates as `query_action` and `invoke_action`. The existing
tools continue to behave exactly as before. The additional tools ask for input
only when a field listed in the action catalog's top-level `required` array is
absent; they do not infer conditional requirements or optional values.
For example, `invoke_action_with_input` with
`{"action":"send_group_msg","params":{"group_id":20001}}` asks for the
missing message. The form contains one `params_json` string, whose contents are
a JSON object such as `{"message":"Hello"}`. The answer is validated against
the missing fields' catalog schemas before normal action execution. Already
provided fields, the action name and execution options cannot be overwritten;
extra answer fields are rejected. A declined, cancelled or invalid answer does
not execute the action.
Clients must advertise form elicitation support. Modern clients receive
`resultType: "input_required"` and resume using the SDK's request-state and input
response mechanism. Legacy clients with elicitation support use the SDK's
`elicitation/create` flow. Clients without form support receive a tool error and
can provide complete arguments to the original tools instead.
Continuation state is signed, tied to the original tool and arguments, expires
after ten minutes and is consumed once before execution. Concurrent or repeated
answers cannot execute the same continuation twice. A runtime holds at most 256
pending prompts; restart invalidates them rather than replaying work. Completed
arguments bypass the input round entirely. This feature is not a general approval
gate and does not add confirmation prompts to existing action calls.
## Live event resources
With `SNOWLUMA_MCP_EVENTS_URL` configured, read and write modes expose
`subscribe_events` and `unsubscribe_events`. The URL must use `ws:` or `wss:`
without embedded credentials, query parameters or fragments. Listing tools or
resources does not connect; only `subscribe_events` opens the event connection.
```json
{
"self_id": 10001,
"types": ["message", "notice"],
"group_ids": [20001],
"user_ids": [30001]
}
```
Use the expected logged-in account for required `self_id`; obtain it through
`get_login_info` if necessary. Every incoming event must match this account.
An account mismatch or malformed event stops the connection and is surfaced.
The optional types are `message`, `notice` and `request`; omitted types mean all
three. `message_sent` is included in the message category. Group and user filters
are combined with AND, so a group filter excludes events without a matching
`group_id`. Each ID filter accepts at most 100 distinct positive integers.
The result contains a canonical `snowluma://onebot/events/<id>` resource URI.
Read it with `resources/read`; use `?after=<next_cursor>` on subsequent reads to
obtain newer buffered entries. Cursors belong to that one resource. The response
includes `status`, `next_cursor`, `oldest_cursor`, `dropped_events`, `gap` and
`notification_failed`. Reads do not consume events. Only events received after
subscription creation are available; this is not message-history storage.
Each resource retains at most 256 events and 1 MiB of event data. One runtime
supports at most 16 resources, sharing one account connection. Incoming frames
are limited to 256 KiB. Buffer eviction and disconnection remain visible through
the cursor/gap and status fields; the service does not silently reconnect or
claim missing events were recovered. Release existing resources before changing
accounts or creating a new connection after disconnection.
For updates, use the **canonical URI without `?after`**:
- Modern clients use `subscriptions/listen` with `resourceSubscriptions: [uri]`
(the TypeScript SDK exposes `client.listen(...)`). Closing that notification
stream does not release the event buffer; call `unsubscribe_events` explicitly.
- Legacy clients first call `resources/subscribe` with the canonical URI, then
receive `notifications/resources/updated`. `resources/unsubscribe` also releases
that event resource. The explicit unsubscribe tool works for both generations.
An update notification indicates that the resource changed; fetch the resource
to read its data. Releasing the last resource closes the WebSocket. Closing the
MCP connection releases its event resources and buffers. No event operation
executes a OneBot business action or sends a QQ message.
## Persistent background transfers
Set an absolute `SNOWLUMA_MCP_TASK_DIR` and use write mode to enable persistent
tasks. Task tools additionally require MCP `2026-07-28` clients advertising
`extensions: {"io.modelcontextprotocol/tasks": {}}`. Legacy clients keep the
existing synchronous execution tools; this server does not expose the obsolete
`tasks/list` or `tasks/result` protocol methods.
`invoke_action_background` takes the same arguments as `invoke_action`, but only
accepts catalog actions marked as streams. For example, it can run
`upload_file_stream` with `execution.input_file` inside the configured upload root.
It writes the task record before starting work and returns a `resultType: "task"`
handle. Ordinary actions continue through the existing tools. The current
background transfer entry does not automatically combine with `_with_input`;
provide the required transfer parameters before starting it.
- `tasks/get` with `{ "taskId": "..." }` returns current state and, when finished,
the saved result or error. A `completed` task can contain a failed business
response: inspect the nested result's diagnostics, `status` and `retcode`.
- `tasks/cancel` requests cooperative cancellation. Cancellation does not undo
remote effects, and a successful completion already in flight may win the race.
Poll the task again for its final state.
- `tasks/update` accepts input responses only for outstanding task input requests.
It is the protocol lifecycle endpoint, not an arbitrary task-editing API. The
current background transfer entry does not itself request interactive input.
- `list_tasks` is an MCP tool returning task metadata without result bodies. It
accepts optional `cursor` and `limit` (1–100; default 50) and returns `nextCursor`
when another page is available.
Task handles advertise `pollIntervalMs: 1000` and `ttlMs: null`. Results survive
restart and are not automatically expired or deleted. Restart marks unfinished
work failed with an explicit **unknown remote outcome** message; it never
replays the operation. This persists transfer status/results, not resumable
upload or download execution. There are at most four concurrent tasks and a
16 MiB limit on each persisted task record.
Storage uses an exclusive runtime lease, private directories/files (0700/0600 on
POSIX) and validated records. Corruption, permission errors and write failures
remain errors. The directory is bound to a digest of the effective mode, endpoint
and token; changing that configuration rejects reuse of the directory. Choose a
new private directory for the new configuration and retain the old history.
Credentials are not stored in the scope record, but task results can contain
private account data and should be protected accordingly.
## Message preview panel
`preview_message` is available in every mode and only constructs a draft:
```json
{
"message_type": "group",
"target_id": 20001,
"text": "Hello",
"reply_to": -123456
}
```
Use `private` for a private conversation. `target_id` must be a positive safe
integer; optional `reply_to` is a non-zero signed 32-bit message ID. The preview
supports literal text and optional quoted replies, not media rendering. Text
that resembles message control codes remains literal text.
Every client receives the same readable text draft, `can_send` flag and
corresponding `invoke_action` arguments. Only clients advertising the MCP Apps
extension `io.modelcontextprotocol/ui` with MIME type
`text/html;profile=mcp-app` receive the tool's UI metadata and listed UI resource.
The panel is a bundled, self-contained HTML asset built with the official Apps
client. It loads no external scripts, fonts or media, opens no network connection
of its own and displays external text without interpreting it as HTML. A missing
packaged asset is a visible packaging error.
Loading the panel sends nothing. Its send button calls the existing
`invoke_action` through the host only after the user clicks, and the server's
write gate still applies. Read/docs mode or a host without server-tool support
keeps sending disabled. The panel prevents duplicate clicks and does not retry
failed or uncertain sends; create a new draft only after checking the outcome.
Successful acknowledgement is not proof of delivery or rendering in QQ.
## Action result schemas and examples
`get_action` and `snowluma://onebot/actions` include `returnsSchema` and
`examples` for every bundled action, including aliases. Both are authored beside
the OneBot action definition and copied into the generated catalog. List/search
responses remain compact; use `get_action` to retrieve the complete contract.
`returnsSchema` describes successful OneBot **`data`**, not the full OneBot
envelope or the MCP `structuredContent` wrapper. Check `status` and `retcode`
before reading it. For stream actions, the schema describes each successful
frame's `data`; MCP downloads instead return saved-file metadata and generic
streams return a frame collection. Error frames and failed envelopes are not
successful results. Unsupported actions use `{ "not": {} }` because they have no
successful result. Compatibility placeholders explicitly document their limits.
Each example has `summary`, `params`, and optional `notes` explaining prerequisites
and identifier sources. These are illustrative calls, never run by catalog tools.
Replace example account/group IDs, opaque handles and paths with values from the
current account before execution. Notes identify operations with multiple steps,
such as completing an upload after all chunks have been acknowledged.
For example, `get_action({ "name": "get_msg" })` documents signed message IDs:
```json
{
"action": "get_msg",
"params": { "message_id": -123456 }
}
```
Pass this object to `query_action` with a real message ID. Writes and streams use
`invoke_action` in write mode. For automatic upload, pass
`{ "action": "upload_file_stream", "execution": { "input_file": "/allowed/hello.txt" } }`
to `invoke_action`, with a real file inside the configured upload root. Ordinary
action paths refer to the SnowLuma server, whereas `execution.input_file` and MCP
download paths refer to the MCP host.
Do not substitute zero for a signed message ID. Resource-only forward uploads
and flash shares have a documented `message_id: 0` sentinel; it cannot be used
for message lookup or recall. Also preserve `null` versus `{}`, optional fields,
and decimal strings such as media `file_size` exactly as documented.
## Structured results
Completed tool results use the advertised `outputSchema` and return
`structuredContent` alongside the existing `content` text block. Modern
`input_required` and background task handles are protocol continuations; inspect
their `resultType` first and obtain the completed result through the relevant
continuation or task lifecycle:
```json
{
"result": { "status": "ok", "retcode": 0, "data": { "message_id": -123 } },
"diagnostics": { "outcome": "success" }
}
```
`result` is the original payload, including arrays such as the category list.
It is `null` for an MCP tool error. `diagnostics.outcome` is `success`, `failed`,
or `unknown`; failures can include `kind`, `message`, and `next_step`.
Ordinary OneBot business failures still return their original envelope without
setting `isError`. Their structured diagnostics indicate failure. An asynchronous
acknowledgement or a response that does not confirm success has outcome `unknown`.
Transport errors and existing tool/stream errors still set `isError: true`.
Error categories describe known causes; unclassified execution errors are not
guessed from message strings. Neither tool execution nor connection checks retry
automatically. Negative message IDs remain valid and are preserved unchanged.
## Search, filters, and pagination
`search_actions` retains its original case-insensitive substring matching and
catalog order unless `match: "keywords"` is requested. Keyword mode combines
space-separated terms with AND, recognizes a small set of common Chinese/English
synonyms, and ranks exact action names or aliases first.
```json
{
"query": "群 禁言",
"match": "keywords",
"read_only": false,
"stream": false,
"limit": 10,
"offset": 0
}
```
Both `list_actions` and `search_actions` accept optional `category`, `read_only`,
`stream`, `limit` (1–200), and `offset` (non-negative integer). Omitting pagination
returns the complete matching list and preserves `{count, actions}`. With `limit`
or `offset`, `count` is the returned page size, `total` is the matching count, and
`next_offset` is the next page offset or `null`. Pagination applies to the bundled
catalog; it does not issue server requests.
## Runtime overview
`get_runtime_info({})` returns:
- The effective `mode`, `execution_enabled`, and `write_enabled`.
- The bundled catalog version and action count. `server_support` remains
`unknown`; a matching version alone does not prove action support.
- In execution mode, effective request timeout, file size and directory quota
limits, concurrent stream limit, download directory, upload root, and whether
automatic upload is enabled. In docs mode, `transport` is `null`.
- `connection_checked: false`. Local configuration is not proof of a live login.
The overview does not expose the endpoint, access token, or authorization headers.
Configured file paths are paths on the MCP host. All stream actions still require
write mode; `upload_enabled` describes the configured file root, not permission
to bypass that gate.
`get_runtime_info({"check_connection": true})` is available only in read/write
mode with a client. It explicitly queries `get_login_info`, `get_status`, and
`get_version_info`, using the ordinary read-only execution gate. Each entry under
`checks` contains its original response and diagnostics. Partial failures remain
visible. Check the returned status data for online state; a successful HTTP
exchange alone does not establish that the account is online.
## Cancellation and progress
MCP cancellation now reaches ordinary HTTP calls as well as stream actions,
including response-body reads. Ordinary calls retain their request timeout;
streams retain separate connection and per-read idle timeouts. A cancelled call
does not automatically retry. Cancellation or timeout can leave a remote write's
outcome unknown: stopping the wait does not undo an operation already received
by SnowLuma.
When a caller includes `_meta.progressToken`, stream execution emits standard
`notifications/progress` notifications with the same token. File downloads report
decoded bytes written; automatic uploads report bytes acknowledged by the server.
Generic streams report accepted frame counts. A total is included only when a
positive file size is known. Empty files and unknown-size downloads omit it.
Notifications are limited to one per 250 ms, plus the final pending update before
a successful response. Values increase, notifications stop on cancellation or
completion, and callers without a progress token receive none. Notification
delivery failures are surfaced. Progress describes transferred data, not final
commit: only a successful tool result confirms file validation and completion.
The existing file containment, quotas, partial-file cleanup and upload-reset
behavior are unchanged. File bytes never appear in progress messages.
+9
View File
@@ -0,0 +1,9 @@
import { App } from '@modelcontextprotocol/ext-apps';
import { mountMessagePreview } from './preview-view.js';
const app = new App(
{ name: 'SnowLuma 消息预览', version: '1.0.0' },
{},
{ strict: true, autoResize: true },
);
mountMessagePreview(app, document);
+196
View File
@@ -0,0 +1,196 @@
import type { App } from '@modelcontextprotocol/ext-apps';
export type PreviewApp = Pick<
App,
| 'ontoolresult'
| 'ontoolcancelled'
| 'onerror'
| 'onclose'
| 'connect'
| 'getHostCapabilities'
| 'callServerTool'
>;
function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
interface Draft {
message_type: 'group' | 'private';
target_id: number;
text: string;
reply_to?: number;
}
function parseDraft(value: unknown): Draft | undefined {
if (
!record(value) ||
(value.message_type !== 'group' && value.message_type !== 'private') ||
typeof value.target_id !== 'number' ||
!Number.isSafeInteger(value.target_id) ||
value.target_id <= 0 ||
typeof value.text !== 'string' ||
value.text.trim().length === 0 ||
(value.reply_to !== undefined &&
(typeof value.reply_to !== 'number' ||
!Number.isInteger(value.reply_to) ||
value.reply_to === 0 ||
value.reply_to < -2147483648 ||
value.reply_to > 2147483647))
) {
return undefined;
}
return {
message_type: value.message_type,
target_id: value.target_id,
text: value.text,
...(value.reply_to !== undefined ? { reply_to: value.reply_to } : {}),
};
}
export function mountMessagePreview(app: PreviewApp, document: Document): void {
const element = (id: string) => {
const value = document.getElementById(id);
if (!value) {
throw new Error(`Missing preview element: ${id}`);
}
return value;
};
const target = element('target');
const body = element('message');
const reply = element('reply');
const status = element('status');
const send = element('send') as HTMLButtonElement;
const cancel = element('cancel') as HTMLButtonElement;
let draft: Draft | undefined;
let canSend = false;
let connected = false;
let attempted = false;
let cancelled = false;
const update = () => {
send.disabled = !connected || !canSend || !draft || attempted || cancelled;
cancel.disabled = !draft || attempted || cancelled;
};
const stop = (message: string) => {
connected = false;
status.textContent = message;
update();
};
app.ontoolresult = (result) => {
// A host may repeat delivery on restoration; never re-arm a sent draft.
if (attempted || cancelled) {
return;
}
const data = record(result.structuredContent) ? result.structuredContent.result : undefined;
draft = !result.isError && record(data) ? parseDraft(data.draft) : undefined;
canSend = record(data) && data.can_send === true;
if (!draft) {
target.textContent = '未收到有效草稿';
body.textContent = '';
reply.textContent = '';
status.textContent = '草稿无效,请重新创建。';
update();
return;
}
target.textContent = `${draft.message_type === 'group' ? '群聊' : '私聊'} · ${draft.target_id}`;
body.textContent = draft.text;
reply.textContent = draft.reply_to === undefined ? '' : `引用消息:${draft.reply_to}`;
status.textContent = canSend
? '消息尚未发送,请核对收件人和正文。'
: '当前连接仅允许预览。';
update();
};
app.ontoolcancelled = () => {
cancelled = true;
status.textContent = '此草稿已取消。';
update();
};
app.onerror = () => stop('连接出现错误。请重新打开预览;发送状态需以会话为准。');
app.onclose = () => stop('连接已断开。请重新打开预览;发送状态需以会话为准。');
cancel.addEventListener('click', () => {
if (attempted) {
return;
}
cancelled = true;
status.textContent = '此草稿已取消,未发送消息。';
update();
});
send.addEventListener('click', async () => {
if (!connected || !canSend || !draft || attempted || cancelled) {
return;
}
attempted = true;
update();
status.textContent = '正在发送…';
const message: Array<{ type: string; data: Record<string, string> }> = [];
if (draft.reply_to !== undefined) {
message.push({ type: 'reply', data: { id: String(draft.reply_to) } });
}
message.push({ type: 'text', data: { text: draft.text } });
try {
const result = await app.callServerTool({
name: 'invoke_action',
arguments: {
action: draft.message_type === 'group' ? 'send_group_msg' : 'send_private_msg',
params: {
[draft.message_type === 'group' ? 'group_id' : 'user_id']: draft.target_id,
message,
},
},
});
const structured = result.structuredContent;
const envelope = record(structured) ? structured.result : undefined;
const diagnostics = record(structured) ? structured.diagnostics : undefined;
if (
!result.isError &&
record(envelope) &&
envelope.status === 'ok' &&
envelope.retcode === 0
) {
const data = envelope.data;
const messageId = record(data) ? data.message_id : undefined;
status.textContent =
typeof messageId === 'number' && Number.isInteger(messageId)
? `服务端已接受消息。消息编号:${messageId}`
: '服务端已接受消息。';
} else if (record(diagnostics) && diagnostics.outcome === 'failed') {
status.textContent = `发送失败:${typeof diagnostics.message === 'string' ? diagnostics.message : '服务端拒绝了请求。'} 如需重试,请创建新草稿。`;
} else {
status.textContent = '发送状态尚未确认。请先检查会话,不要重复发送。';
}
} catch {
status.textContent = '发送状态尚未确认。请先检查会话,不要重复发送。';
}
});
update();
void app.connect().then(
() => {
connected = app.getHostCapabilities()?.serverTools !== undefined;
if (!connected) {
status.textContent = '当前客户端仅支持预览,不能从面板发送。';
}
update();
},
() => stop('无法连接到消息服务。请重新打开预览。'),
);
}
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2022", "DOM"],
"noEmit": true,
"types": []
},
"include": ["*.ts"]
}
+13 -7
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "2.0.2",
"version": "2.3.1",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
@@ -20,15 +20,16 @@
"types": "./dist/server.d.ts",
"files": [
"dist",
"README.md"
"README.md",
"AGENT_FEATURES.md"
],
"scripts": {
"clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true})\"",
"gen": "vitest run scripts/gen-catalog.test.ts",
"prebuild": "pnpm run clean && pnpm run gen",
"build": "tsc -p tsconfig.json",
"build": "tsc -p tsconfig.json && node scripts/build-message-app.mjs",
"prepack": "pnpm run build",
"typecheck": "tsc --noEmit",
"typecheck": "tsc --noEmit && tsc -p apps/tsconfig.json",
"test": "vitest run",
"start": "node dist/server.js"
},
@@ -40,18 +41,23 @@
"qq"
],
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
"@modelcontextprotocol/server": "^2.3.1",
"ws": "^8.21.0"
},
"devDependencies": {
"@modelcontextprotocol/client": "^2.3.1",
"@modelcontextprotocol/sdk": "^1.32.0",
"@snowluma/onebot": "workspace:*",
"@snowluma/proton": "workspace:*",
"@types/node": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
"vitest": "4.1.12",
"@types/ws": "^8.18.1",
"@modelcontextprotocol/ext-apps": "^2.0.3"
},
"engines": {
"node": ">=24"
"node": "^24.22.1 || >=26.12.1"
},
"publishConfig": {
"access": "public"
@@ -0,0 +1,48 @@
import { createHash } from 'node:crypto';
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { build } from 'vite';
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
const style = `
:root{color-scheme:light dark;font-family:system-ui,sans-serif;color:var(--color-text-primary,#20242d);background:var(--color-background-primary,#fff)}
*{box-sizing:border-box}body{margin:0;padding:24px;max-width:760px}h1{font-size:21px;margin:0 0 18px}#target{font-size:14px;font-weight:650;margin:0 0 14px}#message{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;line-height:1.6;margin:0;padding:18px;border:1px solid var(--color-border-primary,#d7dce3);border-radius:10px}#reply{font-size:13px;margin:12px 0;color:var(--color-text-secondary,#626b78)}#status{font-size:14px;line-height:1.5;margin:18px 0}footer{display:flex;gap:10px;flex-wrap:wrap}button{font:inherit;font-size:14px;border:1px solid var(--color-border-primary,#bbc4d0);border-radius:8px;padding:10px 16px;cursor:pointer;background:var(--color-background-primary,#fff);color:inherit}#send{background:#2252a5;color:white;border-color:#2252a5}button:disabled{opacity:.55;cursor:default}button:focus-visible{outline:3px solid #8eb7ff;outline-offset:3px}@media(prefers-color-scheme:dark){:root{color:var(--color-text-primary,#e8ecf3);background:var(--color-background-primary,#1b1e24)}#reply{color:var(--color-text-secondary,#b3bdcb)}button{background:var(--color-background-primary,#1b1e24)}}
`.trim();
export async function buildMessageApp(outDir = join(packageRoot, 'dist')) {
const result = await build({
configFile: false,
root: packageRoot,
logLevel: 'error',
build: {
write: false,
sourcemap: false,
lib: {
entry: join(packageRoot, 'apps/message-preview.ts'),
name: 'SnowLumaMessagePreview',
formats: ['iife'],
},
},
});
const outputs = Array.isArray(result) ? result.flatMap((item) => item.output) : result.output;
if (outputs.length !== 1 || outputs[0].type !== 'chunk') {
throw new Error('Message app must build to a single self-contained script');
}
const script = outputs[0].code.replace(/<\/script/gi, '<\\/script');
const hash = (source) => createHash('sha256').update(source).digest('base64');
const csp = `default-src 'none'; script-src 'sha256-${hash(script)}'; style-src 'sha256-${hash(style)}'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'`;
const html = `<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="${csp}"><title>消息草稿预览</title><style>${style}</style></head>
<body><main><h1>消息草稿预览</h1><p id="target">正在载入草稿…</p><pre id="message"></pre><p id="reply"></p><p id="status" role="status" aria-live="polite">消息尚未发送。</p><footer><button id="send" type="button" disabled>发送这条消息</button><button id="cancel" type="button" disabled>取消草稿</button></footer></main><script>${script}</script></body></html>`;
const filename = join(outDir, 'message-app.html');
await mkdir(dirname(filename), { recursive: true });
await writeFile(filename, html, 'utf8');
return filename;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
await buildMessageApp();
}
+2
View File
@@ -18,6 +18,8 @@ it('generates src/generated/catalog.ts from the live action specs', () => {
for (const a of actions) {
expect(a.inputSchema).toBeTypeOf('object');
expect(a.name).toBeTruthy();
expect(a.returnsSchema, `${a.name} result schema`).toBeTypeOf('object');
expect(a.examples?.length, `${a.name} invocation examples`).toBeGreaterThan(0);
}
const body =
+164 -39
View File
@@ -2,16 +2,16 @@
//
// The OneBot v11 HTTP action protocol is trivial — POST `{ action, params }` to
// the endpoint, read back the JSON envelope — so the MCP talks to it directly
// with `fetch`. We deliberately do NOT depend on @snowluma/sdk here: its
// published dist is bundler-targeted ESM (extensionless relative imports) that
// native `node` cannot resolve without a bundler, and this package is a plain
// `tsc`-built stdio bin. The wire shape — not a shared client type — is the seam
// (ADR-0005); tests inject a fake `ActionClient` (or a fake `fetch`).
// with `fetch`. This client also owns MCP-host file admission and bounded stream
// summaries. The wire shape — not a shared client type — is the seam (ADR-0005);
// tests inject a fake `ActionClient` (or a fake `fetch`).
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { ActionCallError } from './results.js';
import type { TraceContext } from './tracing.js';
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_STREAM_BYTES = 4 * 1024 * 1024 * 1024;
@@ -27,7 +27,7 @@ const MAX_FILE_CHUNKS = 200_000;
const RESET_TIMEOUT_MS = 5_000;
const MAX_ACTIVE_STREAMS = 4;
const INTERNAL_STREAM_CALL = Symbol('snowluma.mcp.internalStreamCall');
const MCP_UPLOAD_OWNED_FIELDS = [
export const MCP_UPLOAD_OWNED_FIELDS = [
'stream_id',
'chunk_data',
'chunk_index',
@@ -102,9 +102,14 @@ export interface OneBotEnvelope {
}
export interface ActionClient {
readonly info?: ClientInfo;
/** Send one OneBot action; resolves the full envelope (even on retcode≠0),
* rejects only on transport-level failure (timeout / connection / bad body). */
call(action: string, params: Record<string, unknown>): Promise<OneBotEnvelope>;
call(
action: string,
params: Record<string, unknown>,
options?: CallOptions,
): Promise<OneBotEnvelope>;
/** Execute a Stream Action over the HTTP multi-frame transport. */
callStream(
action: string,
@@ -113,11 +118,42 @@ export interface ActionClient {
): Promise<StreamCallResult>;
}
export interface StreamCallOptions {
export interface ClientInfo {
timeout_ms: number;
max_stream_bytes: number;
download_quota_bytes: number;
max_active_streams: number;
download_directory: string;
upload_root: string | null;
upload_enabled: boolean;
}
export interface TransferProgress {
progress: number;
total?: number;
message: string;
}
export interface CallOptions {
signal?: AbortSignal;
trace?: TraceContext;
}
function requestHeaders(
base: Record<string, string>,
trace?: TraceContext,
): Record<string, string> {
return {
...base,
...(trace ? { traceparent: trace.traceparent } : {}),
...(trace?.tracestate ? { tracestate: trace.tracestate } : {}),
};
}
export interface StreamCallOptions extends CallOptions {
/** MCP-host file to upload. Only valid for upload_file_stream. */
inputFile?: string;
/** Cancellation from the originating MCP request. */
signal?: AbortSignal;
onProgress?: (progress: TransferProgress) => Promise<void>;
}
type InternalStreamCallOptions = StreamCallOptions & { [INTERNAL_STREAM_CALL]?: true };
@@ -346,7 +382,10 @@ function abortReason(signal: AbortSignal): string {
function throwIfCancelled(signal: AbortSignal | undefined, action: string, stage: string): void {
if (signal?.aborted) {
throw new Error(`action ${action} stream ${stage}: cancelled: ${abortReason(signal)}`);
throw new ActionCallError(
`action ${action} stream ${stage}: cancelled: ${abortReason(signal)}`,
'cancelled',
);
}
}
@@ -360,8 +399,9 @@ async function readWithIdleTimeout(
frameIndex: number,
): Promise<ByteStreamReadResult> {
if (callerSignal?.aborted) {
throw new Error(
throw new ActionCallError(
`action ${action} stream read frame ${frameIndex}: cancelled: ${abortReason(callerSignal)}`,
'cancelled',
);
}
@@ -382,8 +422,9 @@ async function readWithIdleTimeout(
const onAbort = (): void =>
finish(() =>
reject(
new Error(
new ActionCallError(
`action ${action} stream read frame ${frameIndex}: cancelled: ${callerSignal ? abortReason(callerSignal) : 'aborted'}`,
'cancelled',
),
),
);
@@ -391,8 +432,9 @@ async function readWithIdleTimeout(
() =>
finish(() =>
reject(
new Error(
new ActionCallError(
`action ${action} stream read frame ${frameIndex}: idle timeout after ${timeoutMs}ms`,
'timeout',
),
),
),
@@ -418,6 +460,7 @@ async function uploadLocalFile(
maxStreamBytes: number,
callerSignal: AbortSignal | undefined,
post: (params: Record<string, unknown>, signal?: AbortSignal) => Promise<StreamCallResult>,
onProgress?: StreamCallOptions['onProgress'],
): Promise<UploadStreamResult> {
const streamId = randomUUID();
let handle: fs.promises.FileHandle | undefined;
@@ -442,6 +485,11 @@ async function uploadLocalFile(
}
const totalChunks = Math.max(1, Math.ceil(initial.size / UPLOAD_CHUNK_BYTES));
await onProgress?.({
progress: 0,
...(initial.size > 0 ? { total: initial.size } : {}),
message: '上传开始(字节)',
});
const baseParams = { ...params };
for (const key of MCP_UPLOAD_OWNED_FIELDS) {
@@ -507,6 +555,12 @@ async function uploadLocalFile(
`unexpected chunk acknowledgement: ${JSON.stringify(ack.terminal)}`,
);
}
await onProgress?.({
progress: bytesRead,
...(initial.size > 0 ? { total: initial.size } : {}),
message: '已确认上传(字节);等待最终校验',
});
}
stage = 'verify input';
@@ -605,6 +659,7 @@ async function uploadLocalFile(
throw new Error(
`action ${action} stream ${stage}: ${detail}${closeFailure}${resetFailure}`,
{ cause: error },
);
}
}
@@ -667,36 +722,75 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
let client: ActionClient;
let activeStreams = 0;
client = {
async call(action, params) {
let res: Response;
info: Object.freeze({
timeout_ms: timeoutMs,
max_stream_bytes: maxStreamBytes,
download_quota_bytes: 2 * maxStreamBytes,
max_active_streams: MAX_ACTIVE_STREAMS,
download_directory: streamDir,
upload_root: uploadRoot ?? null,
upload_enabled: uploadRoot !== undefined,
}),
async call(action, params, options) {
const deadline = new AbortController();
const signal = options?.signal
? AbortSignal.any([options.signal, deadline.signal])
: deadline.signal;
const timer = setTimeout(
() => deadline.abort(new Error(`timeout after ${timeoutMs}ms`)),
timeoutMs,
);
timer.unref();
try {
res = await fetchImpl(opts.endpoint, {
signal.throwIfAborted();
const res = await fetchImpl(opts.endpoint, {
method: 'POST',
headers,
headers: requestHeaders(headers, options?.trace),
body: JSON.stringify({ action, params }),
signal: AbortSignal.timeout(timeoutMs),
signal,
});
const text = await res.text();
signal.throwIfAborted();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
throw new ActionCallError(
`OneBot returned non-JSON (HTTP ${res.status})`,
res.status === 401 || res.status === 403
? 'authentication'
: 'invalid_response',
);
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new ActionCallError(
`OneBot returned an unexpected response (HTTP ${res.status})`,
'invalid_response',
);
}
return parsed as OneBotEnvelope;
} catch (error) {
throw new Error(
if (error instanceof ActionCallError) {
throw error;
}
const kind = options?.signal?.aborted
? 'cancelled'
: deadline.signal.aborted
? 'timeout'
: 'transport';
throw new ActionCallError(
`action ${action} request: ${error instanceof Error ? error.message : String(error)}`,
kind,
{ cause: error },
);
} finally {
clearTimeout(timer);
}
const text = await res.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
throw new Error(`OneBot returned non-JSON (HTTP ${res.status})`);
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error(`OneBot returned an unexpected response (HTTP ${res.status})`);
}
return parsed as OneBotEnvelope;
},
async callStream(action, params, options) {
const internalOptions = options as InternalStreamCallOptions | undefined;
@@ -761,8 +855,10 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
(uploadParams, signal) =>
client.callStream(action, uploadParams, {
...(signal ? { signal } : {}),
...(options.trace ? { trace: options.trace } : {}),
[INTERNAL_STREAM_CALL]: true,
} as InternalStreamCallOptions),
options.onProgress,
);
}
@@ -782,9 +878,10 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
}
try {
throwIfCancelled(options?.signal, action, 'connection');
res = await fetchImpl(opts.endpoint, {
method: 'POST',
headers,
headers: requestHeaders(headers, options?.trace),
body: JSON.stringify({ action, params }),
signal: requestSignal,
});
@@ -796,14 +893,23 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
: error instanceof Error
? error.message
: String(error);
throw new Error(`action ${action} stream connection: ${detail}`);
throw new ActionCallError(
`action ${action} stream connection: ${detail}`,
options?.signal?.aborted
? 'cancelled'
: connectionController.signal.aborted
? 'timeout'
: 'transport',
{ cause: error },
);
} finally {
clearTimeout(connectionTimer);
}
if (!res.ok) {
throw new Error(
throw new ActionCallError(
`action ${action} stream HTTP: unexpected status ${res.status}`,
res.status === 401 || res.status === 403 ? 'authentication' : 'transport',
);
}
@@ -833,6 +939,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
frame: OneBotEnvelope,
rawBytes: number,
): Promise<void> => {
throwIfCancelled(options?.signal, action, `frame ${frameIndex}`);
const data = record(frame.data);
const dataType = data?.data_type;
const resetAck =
@@ -942,6 +1049,12 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
throw error;
}
await options?.onProgress?.({
progress: 0,
...(declaredSize !== undefined ? { total: declaredSize } : {}),
message: '下载开始(字节)',
});
return;
}
@@ -1008,6 +1121,11 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
fileHash.update(chunk);
fileBytes += chunk.length;
fileChunks++;
await options?.onProgress?.({
progress: fileBytes,
...(declaredSize !== undefined ? { total: declaredSize } : {}),
message: '已接收下载(字节);等待最终校验',
});
return;
}
@@ -1046,6 +1164,11 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
if (data?.type === 'response') {
genericTerminalIndex = frameIndex;
}
await options?.onProgress?.({
progress: frames.length,
message: '已接收数据帧',
});
};
try {
@@ -1112,6 +1235,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
throw new Error(
`action ${action} stream frame ${frameIndex}: frame handling failed: ${detail}`,
{ cause: error },
);
}
@@ -1173,6 +1297,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
}
const sha256 = fileHash.digest('hex');
throwIfCancelled(options?.signal, action, 'commit download');
await fileHandle.close();
fileHandle = undefined;
await fs.promises.rename(partPath!, finalPath!);
@@ -1243,7 +1368,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
const suffix = cleanupErrors.length
? `; cleanup failed (${cleanupErrors.join('; ')})`
: '';
throw new Error(base + suffix);
throw new Error(base + suffix, { cause: error });
} finally {
reader.releaseLock();
}
+119
View File
@@ -0,0 +1,119 @@
import type { CatalogAction } from './types.js';
export const FILTER_PROPERTIES = {
category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' },
read_only: { type: 'boolean', description: '只返回指定读写类型的动作' },
stream: { type: 'boolean', description: '只返回指定流式类型的动作' },
limit: {
type: 'integer',
minimum: 1,
maximum: 200,
description: '每页数量;省略时返回全部匹配项',
},
offset: { type: 'integer', minimum: 0, description: '跳过的匹配项数量,默认 0' },
};
const SYNONYMS = [
['历史消息', '消息历史', 'history'],
['群聊', '群', 'group'],
['私聊', '好友', 'private', 'friend'],
['禁言', 'ban', 'mute'],
['撤回', '撤销消息', 'delete_msg', 'recall'],
['图片', 'image', 'photo'],
['语音', 'record', 'voice'],
['文件', 'file'],
['上传', 'upload'],
['下载', 'download'],
];
export function lite(action: CatalogAction) {
return {
name: action.name,
category: action.category,
summary: action.summary,
aliases: action.aliases,
readOnly: action.readOnly,
stream: action.stream ?? false,
};
}
/** Optional controls must not change legacy matching, order or response fields. */
export function discover(actions: CatalogAction[], args: Record<string, unknown>, search: boolean) {
for (const key of ['read_only', 'stream']) {
if (args[key] !== undefined && typeof args[key] !== 'boolean') {
throw new Error(`${key} 必须是布尔值。`);
}
}
for (const key of ['limit', 'offset']) {
const value = args[key];
if (
value !== undefined &&
(typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < (key === 'limit' ? 1 : 0) ||
(key === 'limit' && value > 200))
) {
throw new Error(`${key} 必须是有效整数(limit 为 1–200,offset 不小于 0)。`);
}
}
if (args.match !== undefined && args.match !== 'substring' && args.match !== 'keywords') {
throw new Error('match 必须为 substring 或 keywords。');
}
const query = (typeof args.query === 'string' ? args.query : '').toLowerCase();
const category = typeof args.category === 'string' ? args.category : undefined;
const keywords = query.trim().split(/\s+/u).filter(Boolean);
let list = actions.filter((action) => {
if (
(category && action.category !== category) ||
(args.read_only !== undefined && action.readOnly !== args.read_only) ||
(args.stream !== undefined && (action.stream ?? false) !== args.stream)
) {
return false;
}
if (!search) {
return true;
}
const fields = [action.name, action.summary ?? '', ...action.aliases].map((s) =>
s.toLowerCase(),
);
if (args.match !== 'keywords') {
return fields.some((field) => field.includes(query));
}
return keywords.every((keyword) => {
const alternatives = SYNONYMS.find((group) => group.includes(keyword)) ?? [keyword];
return alternatives.some((alternative) =>
fields.some((field) => field.includes(alternative)),
);
});
});
if (search && args.match === 'keywords') {
const exact = (action: CatalogAction) =>
action.name.toLowerCase() === query.trim() ||
action.aliases.some((alias) => alias.toLowerCase() === query.trim());
list = list.sort((a, b) => Number(exact(b)) - Number(exact(a)));
}
const offset = typeof args.offset === 'number' ? args.offset : 0;
const limit = typeof args.limit === 'number' ? args.limit : list.length;
const page = list.slice(offset, offset + limit).map(lite);
const paginated = args.limit !== undefined || args.offset !== undefined;
return {
count: page.length,
actions: page,
...(paginated
? {
total: list.length,
next_offset: offset + page.length < list.length ? offset + page.length : null,
}
: {}),
};
}
+344
View File
@@ -0,0 +1,344 @@
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import {
createRequestStateCodec,
fromJsonSchema,
inputRequired,
inputResponse,
type InputRequiredResult,
type ServerContext,
type ServerOptions,
type Tool,
} from '@modelcontextprotocol/server';
import { asError, type StructuredResult } from './results.js';
const INPUT_KEY = 'missing_parameters';
const INPUT_NAMES = {
query_action_with_input: 'query_action',
invoke_action_with_input: 'invoke_action',
} as const;
export type InputCompletionTool = keyof typeof INPUT_NAMES;
export interface InputPreparation {
action: string;
params: Record<string, unknown>;
inputSchema: Record<string, unknown>;
}
export interface InputCompletionCallbacks {
capabilities: unknown;
/** Runs the same permission and argument checks as the existing execution tools. */
preflight: (args: Record<string, unknown>) => InputPreparation | StructuredResult;
execute: (args: Record<string, unknown>) => Promise<StructuredResult>;
}
interface PendingInput {
fingerprint: string;
expiresAt: number;
}
interface InputState {
challenge: string;
}
export interface InputCompletion {
verifyRequestState: NonNullable<NonNullable<ServerOptions['requestState']>['verify']>;
handle: (
name: InputCompletionTool,
args: Record<string, unknown>,
context: ServerContext,
callbacks: InputCompletionCallbacks,
) => Promise<StructuredResult | InputRequiredResult>;
close: () => void;
}
export function isInputCompletionTool(name: string): name is InputCompletionTool {
return Object.hasOwn(INPUT_NAMES, name);
}
export function inputCompletionBaseTool(
name: InputCompletionTool,
): 'query_action' | 'invoke_action' {
return INPUT_NAMES[name];
}
/** Derive visibility, schemas, annotations and result contracts from the existing tools. */
export function inputCompletionTools(baseTools: Tool[]): Tool[] {
return baseTools.flatMap((tool) => {
if (tool.name !== 'query_action' && tool.name !== 'invoke_action') {
return [];
}
return [
{
...tool,
name: `${tool.name}_with_input`,
description: `${tool.description} 缺少必填参数时向支持表单的客户端请求补充;补充完成前不执行动作,已有参数不会被覆盖。`,
},
];
});
}
function isObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
// Bind every round to the exact tool and original arguments, irrespective of JSON
// object key ordering. Values never appear in the signed token or diagnostics.
function fingerprint(name: string, args: Record<string, unknown>): string {
function ordered(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(ordered);
}
if (isObject(value)) {
return Object.fromEntries(
Object.keys(value)
.sort()
.map((key) => [key, ordered(value[key])]),
);
}
return value;
}
return createHash('sha256')
.update(JSON.stringify([name, ordered(args)]))
.digest('hex');
}
function supportsForm(capabilities: unknown): boolean {
const elicitation = isObject(capabilities) ? capabilities.elicitation : undefined;
if (!isObject(elicitation)) {
return false;
}
// The pre-form/url capability shape declared form support with an empty object.
return (
isObject(elicitation.form) ||
(elicitation.form === undefined && elicitation.url === undefined)
);
}
/**
* One instance belongs to one configured runtime, shared by its server factory.
* Pending prompts are deliberately transient: a restart invalidates unfinished
* input, and never resumes or retries a side effect automatically.
*/
export function createInputCompletion(
options: { ttlSeconds?: number; maxPending?: number } = {},
): InputCompletion {
const ttlSeconds = options.ttlSeconds ?? 600;
const maxPending = options.maxPending ?? 256;
if (
!Number.isInteger(ttlSeconds) ||
ttlSeconds < 1 ||
!Number.isInteger(maxPending) ||
maxPending < 1
) {
throw new RangeError('Input completion limits must be positive integers');
}
const codec = createRequestStateCodec<InputState>({
key: randomBytes(32),
ttlSeconds,
// HTTP callers must supply validated authInfo. Stdio has one trusted peer.
// The codec hides the binding behind an HMAC, including bearer credentials.
bind: (context) =>
JSON.stringify([
context.mcpReq.method,
context.http?.authInfo?.clientId ?? null,
context.http?.authInfo?.token ?? null,
context.sessionId ?? null,
]),
});
const pending = new Map<string, PendingInput>();
let closed = false;
return {
verifyRequestState: async (token, context) => {
if (closed) {
throw new Error('closed');
}
return codec.verify(token, context);
},
close() {
closed = true;
pending.clear();
},
async handle(name, args, context, callbacks) {
if (closed) {
return asError('补充输入服务已关闭。', 'configuration');
}
context.mcpReq.signal.throwIfAborted();
const prepared = callbacks.preflight(args);
if ('structuredContent' in prepared) {
return prepared;
}
const state = context.mcpReq.requestState<unknown>();
const required = Array.isArray(prepared.inputSchema.required)
? prepared.inputSchema.required.filter(
(key): key is string => typeof key === 'string',
)
: [];
const missing = required.filter((key) => !Object.hasOwn(prepared.params, key));
const original = fingerprint(name, args);
for (const [id, entry] of pending) {
if (entry.expiresAt <= Date.now()) {
pending.delete(id);
}
}
if (state !== undefined) {
if (!isObject(state) || typeof state.challenge !== 'string') {
return asError('补充输入状态无效。');
}
const entry = pending.get(state.challenge);
if (!entry || entry.fingerprint !== original) {
return asError('补充输入已过期、已使用或原始调用已变更,请重新发起调用。');
}
// Claim synchronously before validation or execution can yield. A
// replay/concurrent retry can never execute the same answer twice.
pending.delete(state.challenge);
const response = inputResponse(context.mcpReq.inputResponses, INPUT_KEY);
if (response.kind === 'elicit' && response.action !== 'accept') {
return asError(
'用户拒绝或取消补充输入,动作未执行。',
'cancelled',
'按用户意愿停止;需要时重新发起调用。',
);
}
if (
response.kind !== 'elicit' ||
!isObject(response.content) ||
typeof response.content.params_json !== 'string' ||
Object.keys(response.content).some((key) => key !== 'params_json')
) {
return asError('补充输入必须包含 params_json 字符串,动作未执行。');
}
let additions: unknown;
try {
additions = JSON.parse(response.content.params_json);
} catch {
return asError('补充参数不是有效 JSON,动作未执行。');
}
if (
!isObject(additions) ||
Object.keys(additions).some((key) => !missing.includes(key))
) {
return asError(
'补充参数只能包含本次缺失的必填字段,不能覆盖已有参数或添加其他字段。',
);
}
const properties = isObject(prepared.inputSchema.properties)
? prepared.inputSchema.properties
: {};
const schema = fromJsonSchema<Record<string, unknown>>({
type: 'object',
properties: Object.fromEntries(
missing.map((key) => [key, properties[key] ?? {}]),
),
required: missing,
additionalProperties: false,
});
const validated = await schema['~standard'].validate(additions);
if (validated.issues) {
return asError(
'补充参数不符合动作目录中的字段类型或约束,动作未执行。',
'invalid_arguments',
'使用 get_action 查看参数要求后重新发起调用。',
);
}
context.mcpReq.signal.throwIfAborted();
if (closed) {
return asError('补充输入服务已关闭,动作未执行。', 'configuration');
}
return callbacks.execute({
...args,
params: { ...prepared.params, ...validated.value },
});
}
if (context.mcpReq.inputResponses || context.mcpReq.droppedInputResponseKeys?.length) {
return asError('补充输入缺少有效请求状态,动作未执行。');
}
if (!missing.length) {
return callbacks.execute(args);
}
if (!supportsForm(callbacks.capabilities)) {
return asError(
'当前客户端未声明表单补充输入能力;请直接提供必填参数。',
'configuration',
'使用 get_action 查看参数后调用原 query_action 或 invoke_action。',
);
}
if (pending.size >= maxPending) {
return asError(
'待补充输入的请求数量已达上限,请完成现有请求或等待过期。',
'execution',
);
}
const challenge = randomUUID();
pending.set(challenge, {
fingerprint: original,
expiresAt: Date.now() + ttlSeconds * 1000,
});
try {
const requestState = await codec.mint({ challenge }, context);
context.mcpReq.signal.throwIfAborted();
if (closed) {
throw new Error('Input completion closed');
}
const properties = isObject(prepared.inputSchema.properties)
? prepared.inputSchema.properties
: {};
return inputRequired({
inputRequests: {
[INPUT_KEY]: inputRequired.elicit({
mode: 'form',
message: `请补充 ${prepared.action} 缺失的必填参数:${missing.join('、')}。仅填写这些字段的 JSON 对象,已有参数保持不变。字段要求:${JSON.stringify(Object.fromEntries(missing.map((key) => [key, properties[key] ?? {}])))}`,
requestedSchema: {
type: 'object',
properties: {
params_json: { type: 'string', title: '缺失参数(JSON 对象)' },
},
required: ['params_json'],
},
}),
},
requestState,
});
} catch (error) {
pending.delete(challenge);
throw error;
}
},
};
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+157
View File
@@ -0,0 +1,157 @@
import { readFile } from 'node:fs/promises';
import type { ReadResourceResult, Resource, Tool } from '@modelcontextprotocol/server';
import { asError, asText, RESULT_SCHEMA, type StructuredResult } from './results.js';
export const MESSAGE_PREVIEW_TOOL = 'preview_message';
export const MESSAGE_APP_URI = 'ui://snowluma/message-preview.html';
export const MESSAGE_APP_MIME_TYPE = 'text/html;profile=mcp-app';
function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function supportsMessageApp(capabilities: unknown): boolean {
if (!record(capabilities) || !record(capabilities.extensions)) {
return false;
}
const ui = capabilities.extensions['io.modelcontextprotocol/ui'];
return (
record(ui) && Array.isArray(ui.mimeTypes) && ui.mimeTypes.includes(MESSAGE_APP_MIME_TYPE)
);
}
export function messagePreviewTool(uiSupported: boolean): Tool {
return {
name: MESSAGE_PREVIEW_TOOL,
description:
'预览一条纯文本群聊或私聊草稿,可附带引用消息编号。只生成草稿,不发送消息;支持面板的客户端可由用户点击发送,仍受写模式限制。文字按字面发送,不解释消息控制代码。',
inputSchema: {
type: 'object',
properties: {
message_type: { type: 'string', enum: ['group', 'private'] },
target_id: { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
text: { type: 'string', minLength: 1 },
reply_to: {
type: 'integer',
minimum: -2147483648,
maximum: 2147483647,
not: { const: 0 },
description: '可选引用消息编号,负值合法。',
},
},
required: ['message_type', 'target_id', 'text'],
additionalProperties: false,
},
outputSchema: RESULT_SCHEMA,
annotations: { readOnlyHint: true, openWorldHint: false },
...(uiSupported
? { _meta: { ui: { resourceUri: MESSAGE_APP_URI, visibility: ['model', 'app'] } } }
: {}),
};
}
/** Pure draft construction. Sending remains an ordinary invoke_action call. */
export function previewMessage(args: Record<string, unknown>, canSend: boolean): StructuredResult {
if (
Object.keys(args).some(
(key) => !['message_type', 'target_id', 'text', 'reply_to'].includes(key),
)
) {
return asError('草稿包含不支持的字段。');
}
const { message_type: messageType, target_id: targetId, text, reply_to: replyTo } = args;
if (messageType !== 'group' && messageType !== 'private') {
return asError('message_type 必须为 group 或 private。');
}
if (typeof targetId !== 'number' || !Number.isSafeInteger(targetId) || targetId <= 0) {
return asError('target_id 必须是正的安全整数。');
}
if (typeof text !== 'string' || text.trim().length === 0) {
return asError('text 必须是非空文本。');
}
if (
replyTo !== undefined &&
(typeof replyTo !== 'number' ||
!Number.isInteger(replyTo) ||
replyTo === 0 ||
replyTo < -2147483648 ||
replyTo > 2147483647)
) {
return asError('reply_to 必须是非零的有符号 32 位消息编号,负值合法。');
}
const message: Array<{ type: string; data: Record<string, string> }> = [];
if (replyTo !== undefined) {
message.push({ type: 'reply', data: { id: String(replyTo) } });
}
// Explicit text segments preserve literal control-code-looking text.
message.push({ type: 'text', data: { text } });
return asText({
draft: {
message_type: messageType,
target_id: targetId,
text,
...(replyTo !== undefined ? { reply_to: replyTo } : {}),
},
can_send: canSend,
notice: '此为待发送草稿,尚未发送。',
invocation: {
name: 'invoke_action',
arguments: {
action: messageType === 'group' ? 'send_group_msg' : 'send_private_msg',
params: { [messageType === 'group' ? 'group_id' : 'user_id']: targetId, message },
},
},
});
}
export function messageAppResources(uiSupported: boolean): Resource[] {
return uiSupported
? [
{
uri: MESSAGE_APP_URI,
name: '消息草稿预览',
description: '查看消息草稿并按需手动发送。',
mimeType: MESSAGE_APP_MIME_TYPE,
},
]
: [];
}
export async function readMessageAppResource(uri: string): Promise<ReadResourceResult | undefined> {
if (uri !== MESSAGE_APP_URI) {
return undefined;
}
// The build emits the same self-contained asset beside this compiled module.
// A missing asset is a packaging error and must not become a blank panel.
const text = await readFile(new URL('./message-app.html', import.meta.url), 'utf8');
return {
contents: [
{
uri,
mimeType: MESSAGE_APP_MIME_TYPE,
text,
_meta: {
ui: {
csp: {
connectDomains: [],
resourceDomains: [],
frameDomains: [],
baseUriDomains: [],
},
prefersBorder: true,
},
},
},
],
};
}
+44
View File
@@ -0,0 +1,44 @@
import type { TransferProgress } from './client.js';
/** One reporter per request. No timers or notifications survive the request. */
export function createProgressReporter(
send: (progress: TransferProgress) => Promise<void>,
signal: AbortSignal,
now: () => number = Date.now,
) {
let latest: TransferProgress | undefined;
let sent = -1;
let sentAt = -Infinity;
const flush = async (): Promise<void> => {
if (!latest || latest.progress <= sent || signal.aborted) {
return;
}
await send(latest);
sent = latest.progress;
sentAt = now();
};
return {
async report(progress: TransferProgress): Promise<void> {
if (
!Number.isFinite(progress.progress) ||
progress.progress < (latest?.progress ?? 0) ||
(progress.total !== undefined &&
(!Number.isFinite(progress.total) ||
progress.total <= 0 ||
progress.progress > progress.total))
) {
throw new Error('Invalid transfer progress');
}
latest = progress;
if (now() - sentAt >= 250) {
await flush();
}
},
finish: flush,
};
}
+142
View File
@@ -0,0 +1,142 @@
import type { CallToolResult, Tool } from '@modelcontextprotocol/server';
import type { OneBotEnvelope } from './client.js';
export type FailureKind =
| 'invalid_arguments'
| 'not_found'
| 'permission'
| 'configuration'
| 'business'
| 'authentication'
| 'cancelled'
| 'timeout'
| 'transport'
| 'invalid_response'
| 'execution';
export interface Diagnostics {
outcome: 'success' | 'failed' | 'unknown';
kind?: FailureKind;
message?: string;
next_step?: string;
}
export type StructuredResult = CallToolResult & {
structuredContent: { result: unknown; diagnostics: Diagnostics };
};
export class ActionCallError extends Error {
constructor(
message: string,
readonly kind: FailureKind,
options?: ErrorOptions,
) {
super(message, options);
this.name = 'ActionCallError';
}
}
export const RESULT_SCHEMA: Tool['outputSchema'] = {
type: 'object',
properties: {
result: {},
diagnostics: {
type: 'object',
properties: {
outcome: { type: 'string', enum: ['success', 'failed', 'unknown'] },
kind: { type: 'string' },
message: { type: 'string' },
next_step: { type: 'string' },
},
required: ['outcome'],
additionalProperties: false,
},
},
required: ['result', 'diagnostics'],
additionalProperties: false,
};
// The text block is the original public contract; structured metadata is additive.
export function asText(
data: unknown,
diagnostics: Diagnostics = { outcome: 'success' },
): StructuredResult {
return {
content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
structuredContent: { result: data, diagnostics: { ...diagnostics } },
};
}
export function asError(
message: string,
kind: FailureKind = 'invalid_arguments',
nextStep = '检查工具参数;使用 get_action 查看动作要求。',
outcome: Diagnostics['outcome'] = 'failed',
): StructuredResult {
return {
content: [{ type: 'text', text: message }],
isError: true,
structuredContent: {
result: null,
diagnostics: { outcome, kind, message, next_step: nextStep },
},
};
}
export function envelopeDiagnostics(envelope: OneBotEnvelope): Diagnostics {
if (envelope.status === 'ok' && envelope.retcode === 0) {
return { outcome: 'success' };
}
if (envelope.status === 'async') {
return { outcome: 'unknown', next_step: '请求已受理,尚未确认完成;不要重复执行写操作。' };
}
if (
envelope.status === 'failed' ||
(typeof envelope.retcode === 'number' && envelope.retcode !== 0)
) {
return {
outcome: 'failed',
kind: 'business',
message:
(typeof envelope.wording === 'string' && envelope.wording) ||
(typeof envelope.message === 'string' && envelope.message) ||
`retcode=${envelope.retcode}`,
next_step: '检查原始响应的 retcode、wording 和动作参数;不要盲目重试写操作。',
};
}
return {
outcome: 'unknown',
kind: 'invalid_response',
next_step: '响应未确认成功;检查服务端版本和日志。',
};
}
export function executionError(
action: string,
error: unknown,
signal?: AbortSignal,
): StructuredResult {
const message = `调用失败 (${action}): ${error instanceof Error ? error.message : String(error)}`;
let cause = error;
const seen = new Set<unknown>();
while (cause instanceof Error && !(cause instanceof ActionCallError) && !seen.has(cause)) {
seen.add(cause);
cause = cause.cause;
}
const kind = signal?.aborted
? 'cancelled'
: cause instanceof ActionCallError
? cause.kind
: 'execution';
return asError(
message,
kind,
'操作结果可能未知。检查连接、配置和服务端状态;取消或超时不代表撤销,确认结果后再决定是否重试。',
'unknown',
);
}
+400
View File
@@ -0,0 +1,400 @@
import {
Server,
ProtocolError,
isInputRequiredResult,
isSpecType,
type ServerContext,
type Tool,
} from '@modelcontextprotocol/server';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import { callTool, computeTools, prepareActionCall, type CallCtx } from './tools.js';
import { createProgressReporter } from './progress.js';
import { VERSION } from './version.js';
import { createCallTrace } from './tracing.js';
import {
createInputCompletion,
inputCompletionBaseTool,
inputCompletionTools,
isInputCompletionTool,
type InputCompletion,
} from './elicitation.js';
import {
MESSAGE_PREVIEW_TOOL,
messageAppResources,
messagePreviewTool,
previewMessage,
readMessageAppResource,
supportsMessageApp,
} from './message-app.js';
import { EventSubscriptions, EVENT_TOOLS, type EventSubscriptionOptions } from './subscriptions.js';
import {
installTaskHandlers,
supportsTasks,
type PersistentTasks,
type TaskHandle,
} from './tasks.js';
import { asError, asText, RESULT_SCHEMA, type StructuredResult } from './results.js';
export interface McpServerOptions extends Pick<CallCtx, 'mode' | 'client'> {
inputCompletion?: InputCompletion;
tasks?: PersistentTasks;
events?: EventSubscriptionOptions;
}
const RESOURCE_URI = 'snowluma://onebot/actions';
export function createMcpServer(ctx: McpServerOptions): Server {
const input = ctx.inputCompletion ?? createInputCompletion();
const events =
ctx.mode !== 'docs' && ctx.events ? new EventSubscriptions(ctx.events) : undefined;
const legacySubscriptions = new Set<string>();
const server = new Server(
{ name: 'snowluma-mcp', version: VERSION },
{
capabilities: {
tools: {},
resources: events ? { subscribe: true, listChanged: true } : {},
extensions: { 'io.modelcontextprotocol/ui': {} },
},
requestState: { verify: input.verifyRequestState },
// Tool availability depends on the configured mode; only the bundled
// action catalog is public. Execution and account data are never cached.
cacheHints: {
'tools/list': { ttlMs: 300_000, cacheScope: 'private' },
'resources/list': { ttlMs: events ? 0 : 300_000, cacheScope: 'private' },
'resources/read': { ttlMs: 0, cacheScope: 'private' },
'resources/templates/list': { ttlMs: 300_000, cacheScope: 'public' },
},
},
);
const capabilities = (request: ServerContext) => {
const envelope: Record<string, unknown> | undefined = request.mcpReq.envelope;
if (!envelope) {
return server.getClientCapabilities();
}
const value = envelope['io.modelcontextprotocol/clientCapabilities'];
if (!isSpecType.ClientCapabilities(value)) {
throw new ProtocolError(-32602, 'Invalid client capabilities');
}
return value;
};
const cacheMetadata = (scope: 'public' | 'private') =>
(server.getNegotiatedProtocolVersion() ?? '') >= '2026-07-28'
? { ttlMs: scope === 'public' ? 300_000 : 0, cacheScope: scope }
: {};
const taskEnabled = (request: ServerContext) =>
!!ctx.tasks &&
ctx.mode === 'write' &&
(server.getNegotiatedProtocolVersion() ?? '') >= '2026-07-28' &&
supportsTasks(request.mcpReq.envelope);
const availableTools = (request: ServerContext): Tool[] => {
const base = computeTools(ctx.mode);
const extra = [
...inputCompletionTools(base),
messagePreviewTool(supportsMessageApp(capabilities(request))),
...(events ? EVENT_TOOLS : []),
];
if (taskEnabled(request)) {
const invocation = base.find((tool) => tool.name === 'invoke_action')!;
extra.push(
{
...invocation,
name: 'invoke_action_background',
description:
'在后台执行一个流式传输动作,返回可跨重启查询的任务编号。仅限流式动作和写模式;重启不会自动重放未完成操作。',
},
{
name: 'list_tasks',
description: '列出本配置下持久化任务的编号和状态,不返回结果正文。',
inputSchema: {
type: 'object',
properties: {
cursor: { type: 'string' },
limit: { type: 'integer', minimum: 1, maximum: 100 },
},
additionalProperties: false,
},
outputSchema: RESULT_SCHEMA,
annotations: { readOnlyHint: true, openWorldHint: false },
},
);
}
return [...base, ...extra];
};
if (ctx.tasks && ctx.mode === 'write') {
installTaskHandlers(server, ctx.tasks);
}
events?.onUpdate(async (uri) => {
if (
(server.getNegotiatedProtocolVersion() ?? '') >= '2026-07-28' ||
legacySubscriptions.has(uri)
) {
await server.sendResourceUpdated({ uri });
}
});
server.onclose = () => {
events?.close();
legacySubscriptions.clear();
if (!ctx.inputCompletion) {
input.close();
}
};
server.setRequestHandler('tools/list', async (_req, request) => ({
tools: availableTools(request),
}));
server.setRequestHandler('tools/call', async (req, request) => {
const { mcpReq } = request;
const trace = createCallTrace(mcpReq._meta);
const tool = availableTools(request).some((entry) => entry.name === req.params.name)
? req.params.name
: 'unlisted';
const started = performance.now();
const report = (event: string, outcome?: string, kind?: string, taskId?: string) => {
console.error(
'[snowluma-mcp] %s',
JSON.stringify({
event,
tool,
traceparent: trace.traceparent,
...(outcome
? { outcome, duration_ms: Math.round(performance.now() - started) }
: {}),
...(kind ? { kind } : {}),
...(taskId ? { task_id: taskId } : {}),
}),
);
};
report('call_started');
const token = mcpReq._meta?.progressToken;
const progress =
token === undefined
? undefined
: createProgressReporter(
(value) =>
mcpReq.notify({
method: 'notifications/progress',
params: { progressToken: token, ...value },
}),
mcpReq.signal,
);
try {
const args = req.params.arguments ?? {};
const callContext: CallCtx = {
mode: ctx.mode,
client: ctx.client,
signal: mcpReq.signal,
trace,
...(progress ? { onProgress: progress.report } : {}),
};
const dispatch = async (): Promise<
StructuredResult | TaskHandle | Awaited<ReturnType<InputCompletion['handle']>>
> => {
if (isInputCompletionTool(req.params.name)) {
const base = inputCompletionBaseTool(req.params.name);
return input.handle(req.params.name, args, request, {
capabilities: capabilities(request),
preflight: (values) => {
const prepared = prepareActionCall(
values,
callContext,
base === 'query_action' ? 'read' : 'write',
);
return 'structuredContent' in prepared
? prepared
: {
action: prepared.action,
params: prepared.params,
inputSchema: prepared.inputSchema,
};
},
execute: (values) => callTool(base, values, callContext),
});
}
if (req.params.name === MESSAGE_PREVIEW_TOOL) {
return previewMessage(args, ctx.mode === 'write' && !!ctx.client);
}
if (events?.handlesTool(req.params.name)) {
const result = await events.callTool(req.params.name, args, mcpReq.signal);
if (!result.isError) {
if (
req.params.name === 'unsubscribe_events' &&
typeof args.uri === 'string'
) {
legacySubscriptions.delete(args.uri);
}
await server.sendResourceListChanged();
}
return result;
}
if (
req.params.name === 'invoke_action_background' ||
req.params.name === 'list_tasks'
) {
if (!taskEnabled(request) || !ctx.tasks) {
return asError(
'持久任务需配置任务目录、启用写模式,并由客户端声明新版任务能力。',
'configuration',
);
}
if (req.params.name === 'list_tasks') {
if (
Object.keys(args).some((key) => key !== 'cursor' && key !== 'limit') ||
(args.cursor !== undefined && typeof args.cursor !== 'string') ||
(args.limit !== undefined && typeof args.limit !== 'number')
) {
return asError('任务列表参数无效。');
}
return asText(
ctx.tasks.list({
cursor: args.cursor as string | undefined,
limit: args.limit as number | undefined,
}),
);
}
const prepared = prepareActionCall(args, callContext, 'write');
if ('structuredContent' in prepared) {
return prepared;
}
if (!prepared.catalog.stream) {
return asError('后台任务仅支持流式传输动作;普通动作请使用原执行工具。');
}
mcpReq.signal.throwIfAborted();
return ctx.tasks.start(async ({ signal }) =>
callTool('invoke_action', args, {
mode: ctx.mode,
client: ctx.client,
signal,
trace,
}),
);
}
return callTool(req.params.name, args, callContext);
};
const result = await dispatch();
if (isInputRequiredResult(result)) {
report('call_input_required', 'unknown');
return { ...result, _meta: { traceparent: trace.traceparent } };
}
if (!('structuredContent' in result)) {
report('call_detached', 'unknown', undefined, result.taskId);
return { ...result, _meta: { traceparent: trace.traceparent } };
}
if (!result.isError) {
await progress?.finish();
}
const { outcome, kind } = result.structuredContent.diagnostics;
report(
mcpReq.signal.aborted || kind === 'cancelled' ? 'call_cancelled' : 'call_finished',
outcome,
kind,
);
return { ...result, _meta: { ...result._meta, traceparent: trace.traceparent } };
} catch (error) {
report(mcpReq.signal.aborted ? 'call_cancelled' : 'call_failed', 'unknown');
throw error;
}
});
server.setRequestHandler('resources/list', async (_req, request) => ({
resources: [
{
uri: RESOURCE_URI,
name: 'SnowLuma OneBot action catalog',
mimeType: 'application/json',
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
},
...messageAppResources(supportsMessageApp(capabilities(request))),
...(events?.resources() ?? []),
],
}));
server.setRequestHandler('resources/templates/list', async () => ({ resourceTemplates: [] }));
server.setRequestHandler('resources/read', async (req) => {
if (events?.ownsUri(req.params.uri)) {
return { ...events.readResource(req.params.uri), ...cacheMetadata('private') };
}
const app = await readMessageAppResource(req.params.uri);
if (app) {
return { ...app, ...cacheMetadata('public') };
}
if (req.params.uri !== RESOURCE_URI) {
throw new Error(`unknown resource: ${req.params.uri}`);
}
return {
...cacheMetadata('public'),
contents: [
{
uri: RESOURCE_URI,
mimeType: 'application/json',
text: JSON.stringify(
{ version: VERSION, categories: CATEGORIES, actions: ACTIONS },
null,
2,
),
},
],
};
});
if (events) {
server.setRequestHandler('resources/subscribe', async (req) => {
if (!events.resources().some((resource) => resource.uri === req.params.uri)) {
throw new ProtocolError(-32602, 'Subscribe using the canonical event resource URI');
}
events.readResource(req.params.uri);
legacySubscriptions.add(req.params.uri);
return {};
});
server.setRequestHandler('resources/unsubscribe', async (req) => {
if (!events.ownsUri(req.params.uri)) {
throw new ProtocolError(-32602, 'Unknown event resource');
}
events.remove(req.params.uri);
legacySubscriptions.delete(req.params.uri);
await server.sendResourceListChanged();
return {};
});
}
return server;
}
+93 -57
View File
@@ -20,18 +20,13 @@
// SNOWLUMA_MCP_STREAM_DIR MCP-host directory for completed downloads.
// SNOWLUMA_MCP_UPLOAD_ROOT Existing MCP-host directory allowed for uploads.
// SNOWLUMA_MCP_MAX_STREAM_BYTES Per-file cap (1..4 GiB; default 4 GiB).
// SNOWLUMA_MCP_TASK_DIR Private persistent task directory (write mode only).
// SNOWLUMA_MCP_EVENTS_URL Explicit OneBot event WebSocket endpoint.
//
// NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr.
import { readFileSync } from 'node:fs';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { createHash } from 'node:crypto';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import {
makeHttpClient,
@@ -39,14 +34,14 @@ import {
parseTimeoutMs,
type ActionClient,
} from './client.js';
import { callTool, computeTools, parseMode, type Mode } from './tools.js';
import { parseMode, type Mode } from './tools.js';
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {
version: string;
};
const VERSION = pkg.version;
const RESOURCE_URI = 'snowluma://onebot/actions';
import { createMcpServer, type McpServerOptions } from './server-factory.js';
import { createInputCompletion } from './elicitation.js';
import { PersistentTasks } from './tasks.js';
import { shutdownRuntime } from './shutdown.js';
import { normalizeEventSubscriptionOptions } from './subscriptions.js';
import { VERSION } from './version.js';
// ── resolve mode + client from the environment ────────────────────────────
function resolveRuntime(): { mode: Mode; client?: ActionClient } {
@@ -86,54 +81,95 @@ function resolveRuntime(): { mode: Mode; client?: ActionClient } {
return { mode, client };
}
const { mode, client } = resolveRuntime();
const runtime: McpServerOptions = resolveRuntime();
const { mode } = runtime;
const taskDirectory = process.env.SNOWLUMA_MCP_TASK_DIR?.trim();
const eventsUrl = process.env.SNOWLUMA_MCP_EVENTS_URL?.trim();
const server = new Server(
{ name: 'snowluma-mcp', version: VERSION },
{ capabilities: { tools: {}, resources: {} } },
);
if (taskDirectory && mode !== 'write') {
throw new Error('SNOWLUMA_MCP_TASK_DIR requires write mode and a configured endpoint');
}
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) }));
if (eventsUrl && mode !== 'docs') {
runtime.events = normalizeEventSubscriptionOptions({
url: eventsUrl,
accessToken: process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined,
timeoutMs: parseTimeoutMs(process.env.SNOWLUMA_MCP_TIMEOUT_MS),
});
}
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
const args = (req.params.arguments ?? {}) as Record<string, unknown>;
return callTool(req.params.name, args, { mode, client, signal: extra.signal });
});
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: [
{
uri: RESOURCE_URI,
name: 'SnowLuma OneBot action catalog',
mimeType: 'application/json',
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
if (taskDirectory) {
const scopeId = createHash('sha256')
.update(
JSON.stringify({
mode,
endpoint: process.env.SNOWLUMA_MCP_ENDPOINT?.trim(),
token: process.env.SNOWLUMA_MCP_TOKEN?.trim() || null,
}),
)
.digest('hex');
runtime.tasks = await PersistentTasks.open(taskDirectory, {
scopeId,
onChange: (task) =>
console.error(
'[snowluma-mcp] %s',
JSON.stringify({ event: 'task_status', task_id: task.taskId, status: task.status }),
),
onError: (_error, context) => {
console.error('[snowluma-mcp] %s', JSON.stringify(context));
},
],
}));
});
}
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
if (req.params.uri !== RESOURCE_URI) {
throw new Error(`unknown resource: ${req.params.uri}`);
}
const inputCompletion = createInputCompletion();
runtime.inputCompletion = inputCompletion;
let cleanup: Promise<void> | undefined;
return {
contents: [
{
uri: RESOURCE_URI,
mimeType: 'application/json',
text: JSON.stringify(
{ version: VERSION, categories: CATEGORIES, actions: ACTIONS },
null,
2,
),
},
],
};
});
function closeFeatures(): Promise<void> {
return (cleanup ??= (async () => {
inputCompletion.close();
await runtime.tasks?.close();
})());
}
function reportShutdownError(error: unknown): void {
console.error(
'[snowluma-mcp] shutdown failed: %s',
error instanceof Error ? error.name : 'unknown',
);
process.exitCode = 1;
}
const transport = new StdioServerTransport();
await server.connect(transport);
const where = client ? ` → ${process.env.SNOWLUMA_MCP_ENDPOINT?.trim()}` : '';
const handle = serveStdio(() => createMcpServer(runtime), {
transport,
onerror: (error) => {
// Protocol errors may embed client input. Keep the error category visible
// without copying arguments or credentials into process diagnostics.
console.error('[snowluma-mcp] protocol error: %s', error.name);
},
});
const transportClosed = transport.onclose;
transport.onclose = () => {
transportClosed?.();
void closeFeatures().catch(reportShutdownError);
};
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.once(signal, () => {
void shutdownRuntime({
closeFeatures,
closeProtocol: () => handle.close(),
forceClose: async () => {
await transport.close();
process.stdout.destroy();
},
onLateProtocolError: reportShutdownError,
}).catch(reportShutdownError);
});
}
console.error(
`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}${where}`,
`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}`,
);
+89
View File
@@ -0,0 +1,89 @@
export interface ShutdownOptions {
closeFeatures(): Promise<void>;
closeProtocol(): Promise<void>;
forceClose(): Promise<void>;
graceMs?: number;
onTimeout?: () => void;
onLateProtocolError?: (error: unknown) => void;
}
/** Persist task shutdown before waiting on a peer that may have stopped reading stdout. */
export async function shutdownRuntime(options: ShutdownOptions): Promise<void> {
const failures: unknown[] = [];
try {
await options.closeFeatures();
} catch (error) {
failures.push(error);
}
const protocol = Promise.resolve()
.then(() => options.closeProtocol())
.then(
() => ({ kind: 'closed' as const }),
(error: unknown) => ({ kind: 'failed' as const, error }),
);
let timer!: ReturnType<typeof setTimeout>;
const timeout = new Promise<{ kind: 'timeout' }>((resolve) => {
timer = setTimeout(() => resolve({ kind: 'timeout' }), options.graceMs ?? 1000);
});
const outcome = await Promise.race([protocol, timeout]);
clearTimeout(timer);
if (outcome.kind === 'failed') {
failures.push(outcome.error);
}
if (outcome.kind === 'timeout') {
// A protocol rejection can arrive after the bounded shutdown returns.
// Observe the settled outcome too, including races with the deadline.
void protocol.then((late) => {
if (late.kind !== 'failed') {
return;
}
try {
if (options.onLateProtocolError) {
options.onLateProtocolError(late.error);
} else {
console.error(
'[snowluma-mcp] protocol shutdown failed after timeout: %s',
late.error instanceof Error ? late.error.name : 'unknown',
);
}
} catch (reportError) {
console.error(
'[snowluma-mcp] late shutdown error reporting failed: %s; original: %s',
reportError instanceof Error ? reportError.name : 'unknown',
late.error instanceof Error ? late.error.name : 'unknown',
);
}
});
try {
if (options.onTimeout) {
options.onTimeout();
} else {
console.error('[snowluma-mcp] protocol shutdown timed out; closing transport');
}
} catch (error) {
failures.push(error);
}
}
if (outcome.kind !== 'closed') {
try {
await options.forceClose();
} catch (error) {
failures.push(error);
}
}
if (failures.length === 1) {
throw failures[0];
}
if (failures.length > 1) {
throw new AggregateError(failures, 'Runtime shutdown failed');
}
}
+722
View File
@@ -0,0 +1,722 @@
import { randomUUID } from 'node:crypto';
import {
ProtocolError,
type ReadResourceResult,
type Resource,
type Tool,
} from '@modelcontextprotocol/server';
import WebSocket, { type RawData } from 'ws';
import { asError, asText, RESULT_SCHEMA, type StructuredResult } from './results.js';
class EventInputError extends ProtocolError {
constructor(message: string) {
super(-32602, message);
}
}
const PREFIX = 'snowluma://onebot/events/';
const MAX_FRAME_BYTES = 256 * 1024;
const MAX_BUFFER_BYTES = 1024 * 1024;
const MAX_BUFFER_EVENTS = 256;
const MAX_SUBSCRIPTIONS = 16;
const MAX_FILTER_IDS = 100;
type EventType = 'message' | 'notice' | 'request';
type SourceStatus = 'connecting' | 'connected' | 'disconnected';
type SourceProblem =
| 'connection_failed'
| 'connection_closed'
| 'connection_timeout'
| 'invalid_event'
| 'account_mismatch'
| 'frame_too_large';
interface Filter {
selfId: number;
types: Set<EventType>;
groupIds?: Set<number>;
userIds?: Set<number>;
}
interface BufferedEvent {
cursor: number;
event: Record<string, unknown>;
bytes: number;
}
interface Subscription {
uri: string;
filter: Filter;
events: BufferedEvent[];
bytes: number;
cursor: number;
dropped: number;
status: SourceStatus;
problem?: SourceProblem;
notificationFailed: boolean;
cancelPending?: () => void;
}
interface Source {
socket: WebSocket;
selfId: number;
ready: Promise<void>;
resolve: () => void;
reject: (error: Error) => void;
verified: boolean;
stopped: boolean;
timer?: ReturnType<typeof setTimeout>;
heartbeat?: ReturnType<typeof setInterval>;
awaitingPong: boolean;
}
export interface EventSubscriptionOptions {
url: string;
accessToken?: string;
timeoutMs?: number;
}
/** Validate startup configuration without creating resources or contacting an account. */
export function normalizeEventSubscriptionOptions(
options: EventSubscriptionOptions,
): EventSubscriptionOptions & { timeoutMs: number } {
let url: URL;
try {
url = new URL(options.url);
} catch {
throw new Error('SNOWLUMA_MCP_EVENTS_URL must be an absolute WebSocket URL');
}
if (
!['ws:', 'wss:'].includes(url.protocol) ||
url.username ||
url.password ||
url.hash ||
url.search
) {
throw new Error(
'SNOWLUMA_MCP_EVENTS_URL must use ws/wss without credentials, query, or fragment; use SNOWLUMA_MCP_TOKEN for authentication',
);
}
if (
options.timeoutMs !== undefined &&
(!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0)
) {
throw new Error('Event connection timeout must be a positive integer');
}
return { ...options, url: url.href, timeoutMs: options.timeoutMs ?? 30_000 };
}
const idSchema = { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER };
const idsSchema = {
type: 'array',
items: idSchema,
minItems: 1,
maxItems: MAX_FILTER_IDS,
uniqueItems: true,
};
export const EVENT_TOOLS: Tool[] = [
{
name: 'subscribe_events',
description:
'订阅指定登录账号的实时 OneBot 事件,返回可读取的资源。消息、通知、请求可按群和用户筛选。只接收创建后的事件;有限缓存溢出和断线会明确标记缺口。通过资源更新通知获知变化,使用 unsubscribe_events 释放资源。',
inputSchema: {
type: 'object',
properties: {
self_id: {
...idSchema,
description:
'预期登录账号,必须与事件连接的账号相同。可先用 get_login_info 查询。',
},
types: {
type: 'array',
items: { type: 'string', enum: ['message', 'notice', 'request'] },
minItems: 1,
maxItems: 3,
uniqueItems: true,
},
group_ids: idsSchema,
user_ids: idsSchema,
},
required: ['self_id'],
additionalProperties: false,
},
outputSchema: RESULT_SCHEMA,
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
},
{
name: 'unsubscribe_events',
description:
'停止事件订阅并释放其缓存;最后一个事件订阅结束时断开事件连接。不发送任何 OneBot 业务操作。',
inputSchema: {
type: 'object',
properties: { uri: { type: 'string' } },
required: ['uri'],
additionalProperties: false,
},
outputSchema: RESULT_SCHEMA,
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
},
];
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function id(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
}
function readIds(value: unknown, field: string): Set<number> | undefined {
if (value === undefined) {
return undefined;
}
if (
!Array.isArray(value) ||
value.length === 0 ||
value.length > MAX_FILTER_IDS ||
!value.every(id) ||
new Set(value).size !== value.length
) {
throw new EventInputError(
`${field} must contain 1..${MAX_FILTER_IDS} distinct positive integer IDs`,
);
}
return new Set(value);
}
function filter(args: Record<string, unknown>): Filter {
if (
Object.keys(args).some(
(key) => !['self_id', 'types', 'group_ids', 'user_ids'].includes(key),
)
) {
throw new EventInputError('Unexpected event subscription parameter');
}
if (!id(args.self_id)) {
throw new EventInputError('self_id must be a positive safe integer');
}
const types = args.types ?? ['message', 'notice', 'request'];
if (
!Array.isArray(types) ||
types.length === 0 ||
types.length > 3 ||
types.some((type) => !['message', 'notice', 'request'].includes(type)) ||
new Set(types).size !== types.length
) {
throw new EventInputError('types must contain distinct message, notice, or request values');
}
return {
selfId: args.self_id,
types: new Set(types),
groupIds: readIds(args.group_ids, 'group_ids'),
userIds: readIds(args.user_ids, 'user_ids'),
};
}
function eventType(value: unknown): EventType | undefined {
if (value === 'message' || value === 'message_sent') {
return 'message';
}
if (value === 'notice' || value === 'request') {
return value;
}
return undefined;
}
function hasSafeDepth(value: Record<string, unknown>): boolean {
const pending: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];
while (pending.length > 0) {
const entry = pending.pop()!;
if (entry.value === null || typeof entry.value !== 'object') {
continue;
}
if (entry.depth >= 64) {
return false;
}
for (const child of Object.values(entry.value)) {
pending.push({ value: child, depth: entry.depth + 1 });
}
}
return true;
}
/** Private, bounded event resources for one stdio client. Constructing does not connect. */
export class EventSubscriptions {
private readonly options: EventSubscriptionOptions;
private readonly subscriptions = new Map<string, Subscription>();
private readonly listeners = new Set<(uri: string) => Promise<void>>();
private readonly pendingNotifications = new Set<string>();
private notificationTimer?: ReturnType<typeof setTimeout>;
private notifying = false;
private source?: Source;
private closed = false;
constructor(options: EventSubscriptionOptions) {
this.options = normalizeEventSubscriptionOptions(options);
}
handlesTool(name: string): boolean {
return EVENT_TOOLS.some((tool) => tool.name === name);
}
async callTool(
name: string,
args: Record<string, unknown>,
signal?: AbortSignal,
): Promise<StructuredResult> {
try {
if (signal?.aborted) {
return asError('事件订阅操作已取消。', 'cancelled');
}
if (name === 'subscribe_events') {
const subscription = await this.create(filter(args), signal);
return asText(this.snapshot(subscription, undefined));
}
if (name === 'unsubscribe_events') {
if (
typeof args.uri !== 'string' ||
Object.keys(args).some((key) => key !== 'uri')
) {
throw new EventInputError('unsubscribe_events requires only a resource uri');
}
this.remove(args.uri);
return asText({ uri: args.uri, unsubscribed: true });
}
return asError('Unknown event tool', 'not_found');
} catch (error) {
if (signal?.aborted) {
return asError('事件订阅操作已取消。', 'cancelled');
}
if (error instanceof EventInputError) {
return asError(error.message, 'invalid_arguments');
}
// Socket errors can contain URLs and server-controlled strings. Keep
// those out of both tool diagnostics and stderr.
console.error('[snowluma-mcp] event subscription establishment failed');
return asError(
'事件订阅未建立;检查事件地址、凭据、预期账号及服务端状态。',
'transport',
);
}
}
resources(): Resource[] {
return Array.from(this.subscriptions.values(), ({ uri }) => ({
uri,
name: 'OneBot live events',
mimeType: 'application/json',
description:
'有界实时事件队列。资源 URI 加 ?after=游标 可增量读取;gap=true 表示事件不完整。',
}));
}
ownsUri(uri: string): boolean {
return uri.startsWith(PREFIX);
}
readResource(uri: string): ReadResourceResult {
const { subscription, after } = this.lookup(uri);
return {
contents: [
{
uri,
mimeType: 'application/json',
text: JSON.stringify(this.snapshot(subscription, after)),
},
],
};
}
/** Legacy unsubscribe and the explicit tool both release the source lease. */
remove(uri: string): void {
const { subscription, after } = this.lookup(uri);
if (after !== undefined) {
throw new EventInputError('Use the canonical event resource URI to unsubscribe');
}
this.subscriptions.delete(subscription.uri);
subscription.cancelPending?.();
this.pendingNotifications.delete(subscription.uri);
if (this.subscriptions.size === 0) {
this.stopSource();
}
}
onUpdate(listener: (uri: string) => Promise<void>): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
close(): void {
this.closed = true;
this.stopSource();
this.subscriptions.clear();
this.listeners.clear();
this.pendingNotifications.clear();
clearTimeout(this.notificationTimer);
}
private lookup(uri: string): { subscription: Subscription; after?: number } {
const match =
/^snowluma:\/\/onebot\/events\/([a-f0-9-]{36})(?:\?after=(0|[1-9]\d*))?$/.exec(uri);
if (!match) {
throw new EventInputError('Invalid event resource URI');
}
const subscription = this.subscriptions.get(`${PREFIX}${match[1]}`);
const after = match[2] === undefined ? undefined : Number(match[2]);
if (!subscription) {
throw new EventInputError('Event resource not found or already unsubscribed');
}
if (after !== undefined && (!Number.isSafeInteger(after) || after > subscription.cursor)) {
throw new EventInputError('Event cursor is beyond the available stream');
}
return { subscription, after };
}
private snapshot(subscription: Subscription, after: number | undefined) {
const oldest = subscription.events[0]?.cursor ?? subscription.cursor + 1;
return {
uri: subscription.uri,
self_id: subscription.filter.selfId,
status: subscription.status,
...(subscription.problem ? { problem: subscription.problem } : {}),
next_cursor: subscription.cursor,
oldest_cursor: oldest,
dropped_events: subscription.dropped,
gap: subscription.status === 'disconnected' || (after ?? 0) < oldest - 1,
notification_failed: subscription.notificationFailed,
events: subscription.events
.filter((entry) => after === undefined || entry.cursor > after)
.map(({ cursor, event }) => ({ cursor, event })),
};
}
private async create(selected: Filter, signal?: AbortSignal): Promise<Subscription> {
if (this.closed) {
throw new EventInputError('Event resources are closed');
}
if (this.subscriptions.size >= MAX_SUBSCRIPTIONS) {
throw new EventInputError(`At most ${MAX_SUBSCRIPTIONS} event resources may be active`);
}
if (this.source && (this.source.selfId !== selected.selfId || this.source.stopped)) {
throw new EventInputError(
'Release existing event resources before changing accounts or reconnecting',
);
}
const subscription: Subscription = {
uri: `${PREFIX}${randomUUID()}`,
filter: selected,
events: [],
bytes: 0,
cursor: 0,
dropped: 0,
status: 'connecting',
notificationFailed: false,
};
this.subscriptions.set(subscription.uri, subscription);
let onAbort: (() => void) | undefined;
try {
const source = this.source ?? this.connect(selected.selfId);
await Promise.race([
source.ready,
new Promise<never>((_resolve, reject) => {
onAbort = () => reject(new Error('Event subscription cancelled'));
subscription.cancelPending = onAbort;
signal?.addEventListener('abort', onAbort, { once: true });
if (signal?.aborted) {
onAbort();
}
}),
]);
if (
source.stopped ||
signal?.aborted ||
this.subscriptions.get(subscription.uri) !== subscription
) {
throw new Error('Event connection unavailable');
}
subscription.status = 'connected';
return subscription;
} catch (error) {
this.subscriptions.delete(subscription.uri);
this.pendingNotifications.delete(subscription.uri);
if (this.subscriptions.size === 0) {
this.stopSource();
}
throw error;
} finally {
subscription.cancelPending = undefined;
if (onAbort) {
signal?.removeEventListener('abort', onAbort);
}
}
}
private connect(selfId: number): Source {
let resolve!: () => void;
let reject!: (error: Error) => void;
const ready = new Promise<void>((accept, fail) => {
resolve = accept;
reject = fail;
});
const socket = new WebSocket(this.options.url, {
headers: this.options.accessToken
? { Authorization: `Bearer ${this.options.accessToken}` }
: undefined,
maxPayload: MAX_FRAME_BYTES,
handshakeTimeout: this.options.timeoutMs,
followRedirects: false,
perMessageDeflate: false,
});
const source: Source = {
socket,
selfId,
ready,
resolve,
reject,
verified: false,
stopped: false,
awaitingPong: false,
};
this.source = source;
source.timer = setTimeout(
() => this.failSource(source, 'connection_timeout'),
this.options.timeoutMs,
);
source.timer.unref();
socket.on('message', (raw: RawData, binary: boolean) => this.receive(source, raw, binary));
socket.on('error', (error: Error & { code?: string }) =>
this.failSource(
source,
error.code === 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
? 'frame_too_large'
: 'connection_failed',
),
);
socket.on('close', () => this.failSource(source, 'connection_closed'));
socket.on('pong', () => {
source.awaitingPong = false;
});
return source;
}
private receive(source: Source, raw: RawData, binary: boolean): void {
if (source.stopped || source !== this.source) {
return;
}
let event: unknown;
let byteLength: number;
try {
if (binary) {
throw new Error('Binary event frame');
}
const bytes = Array.isArray(raw)
? Buffer.concat(raw)
: raw instanceof ArrayBuffer
? Buffer.from(raw)
: raw;
byteLength = bytes.length;
event = JSON.parse(bytes.toString('utf8'));
} catch {
this.failSource(source, 'invalid_event');
return;
}
if (
!record(event) ||
!id(event.self_id) ||
typeof event.post_type !== 'string' ||
!hasSafeDepth(event)
) {
this.failSource(source, 'invalid_event');
return;
}
if (event.self_id !== source.selfId) {
this.failSource(source, 'account_mismatch');
return;
}
if (!source.verified) {
source.verified = true;
clearTimeout(source.timer);
source.heartbeat = setInterval(() => {
if (source.stopped) {
return;
}
if (source.awaitingPong) {
this.failSource(source, 'connection_timeout');
return;
}
source.awaitingPong = true;
source.socket.ping();
}, 30_000);
source.heartbeat.unref();
source.resolve();
for (const subscription of this.subscriptions.values()) {
subscription.status = 'connected';
this.updated(subscription.uri);
}
}
const type = eventType(event.post_type);
if (!type) {
return;
}
for (const subscription of this.subscriptions.values()) {
const selected = subscription.filter;
if (
!selected.types.has(type) ||
(selected.groupIds &&
(!id(event.group_id) || !selected.groupIds.has(event.group_id))) ||
(selected.userIds && (!id(event.user_id) || !selected.userIds.has(event.user_id)))
) {
continue;
}
subscription.events.push({ cursor: ++subscription.cursor, event, bytes: byteLength });
subscription.bytes += byteLength;
while (
subscription.events.length > MAX_BUFFER_EVENTS ||
subscription.bytes > MAX_BUFFER_BYTES
) {
const dropped = subscription.events.shift()!;
subscription.bytes -= dropped.bytes;
subscription.dropped++;
}
this.updated(subscription.uri);
}
}
private failSource(source: Source, problem: SourceProblem): void {
if (source.stopped) {
return;
}
source.stopped = true;
clearTimeout(source.timer);
clearInterval(source.heartbeat);
source.reject(new Error('Event source unavailable'));
source.socket.terminate();
console.error('[snowluma-mcp] event source stopped: %s', problem);
for (const subscription of this.subscriptions.values()) {
subscription.status = 'disconnected';
subscription.problem = problem;
this.updated(subscription.uri);
}
}
private stopSource(): void {
if (!this.source) {
return;
}
const source = this.source;
source.stopped = true;
clearTimeout(source.timer);
clearInterval(source.heartbeat);
source.reject(new Error('Event source closed'));
source.socket.terminate();
this.source = undefined;
}
private updated(uri: string): void {
this.pendingNotifications.add(uri);
if (this.notificationTimer || this.notifying || this.closed) {
return;
}
this.notificationTimer = setTimeout(() => {
this.notificationTimer = undefined;
void this.flushNotifications();
}, 25);
this.notificationTimer.unref();
}
private async flushNotifications(): Promise<void> {
this.notifying = true;
const uris = Array.from(this.pendingNotifications);
this.pendingNotifications.clear();
try {
for (const uri of uris) {
if (!this.subscriptions.has(uri)) {
continue;
}
for (const listener of this.listeners) {
try {
await listener(uri);
} catch {
const subscription = this.subscriptions.get(uri);
if (subscription) {
subscription.notificationFailed = true;
}
console.error('[snowluma-mcp] event resource notification failed');
}
}
}
} finally {
this.notifying = false;
if (!this.closed && this.pendingNotifications.size > 0) {
this.updated(this.pendingNotifications.values().next().value!);
}
}
}
}
+956
View File
@@ -0,0 +1,956 @@
import { randomUUID } from 'node:crypto';
import { constants } from 'node:fs';
import { lstat, mkdir, open, readdir, realpath, rename, unlink } from 'node:fs/promises';
import { hostname } from 'node:os';
import path from 'node:path';
import {
ProtocolError,
ProtocolErrorCode,
specTypeSchemas,
type CallToolResult,
type InputRequests,
type InputResponses,
type Server,
type ServerContext,
type StandardSchemaV1,
} from '@modelcontextprotocol/server';
// The 2026 Tasks extension is server-directed and has get/update/cancel,
// not the deprecated 2025 tasks/result or tasks/list methods.
export const TASK_EXTENSION = 'io.modelcontextprotocol/tasks';
export const TASK_CAPABILITIES = { extensions: { [TASK_EXTENSION]: {} } };
const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const MAX_RECORD_BYTES = 16 * 1024 * 1024;
const INTERRUPTED = 'Task interrupted; remote outcome is unknown. Work was not replayed.';
const CANCELLED = 'Task cancelled; cancellation does not undo remote effects.';
const CANCELLATION_REQUESTED = 'Cancellation requested; remote effects may already have occurred.';
interface TaskBase {
taskId: string;
createdAt: string;
lastUpdatedAt: string;
ttlMs: null;
pollIntervalMs: number;
statusMessage?: string;
}
export type PersistentTask = TaskBase &
(
| { status: 'working' }
| { status: 'input_required'; inputRequests: InputRequests }
| { status: 'completed'; result: CallToolResult & { resultType: 'complete' } }
| { status: 'failed'; error: { code: number; message: string; data?: unknown } }
| { status: 'cancelled' }
);
export type TaskSummary = TaskBase & { status: PersistentTask['status'] };
export type TaskHandle = TaskSummary & { resultType: 'task'; content: [] };
export interface TaskExecutionContext {
taskId: string;
signal: AbortSignal;
requestInput(requests: InputRequests): Promise<InputResponses>;
}
export interface TaskStoreOptions {
/** Stable, non-secret digest of the configured account/endpoint and access mode. */
scopeId: string;
onChange?: (task: PersistentTask) => void | Promise<void>;
onError?: (error: Error, context: { event: string; taskId?: string }) => void;
maxConcurrent?: number;
}
interface PendingInput {
outstanding: InputRequests;
responses: InputResponses;
resolve: (responses: InputResponses) => void;
reject: (error: Error) => void;
}
interface ActiveTask {
controller: AbortController;
usedInputKeys: Set<string>;
input?: PendingInput;
}
function object(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function supportsTasks(meta?: Readonly<Record<string, unknown>>): boolean {
const capabilities = meta?.['io.modelcontextprotocol/clientCapabilities'];
if (!object(capabilities) || !object(capabilities.extensions)) {
return false;
}
const extension = capabilities.extensions[TASK_EXTENSION];
return object(extension) && Object.keys(extension).length === 0;
}
function requireTasks(ctx: ServerContext, version: string | undefined): void {
if (!version || version < '2026-07-28' || !supportsTasks(ctx.mcpReq.envelope)) {
throw new ProtocolError(-32021, 'The request must declare the Tasks extension capability', {
requiredCapabilities: TASK_CAPABILITIES,
});
}
}
function taskId(value: unknown): string {
if (typeof value !== 'string' || !ID.test(value)) {
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid task identifier');
}
return value;
}
function summary(task: PersistentTask): TaskSummary {
const { taskId, status, createdAt, lastUpdatedAt, ttlMs, pollIntervalMs, statusMessage } = task;
return {
taskId,
status,
createdAt,
lastUpdatedAt,
ttlMs,
pollIntervalMs,
...(statusMessage ? { statusMessage } : {}),
};
}
function terminal(task: PersistentTask): boolean {
return task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled';
}
function errorCode(error: unknown): string | undefined {
return object(error) && typeof error.code === 'string' ? error.code : undefined;
}
async function readPrivateJson(file: string): Promise<unknown> {
const stat = await lstat(file);
if (
!stat.isFile() ||
stat.isSymbolicLink() ||
(process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
) {
throw new Error('Task storage file must be a private regular file');
}
if (stat.size > MAX_RECORD_BYTES) {
throw new Error('Task storage record exceeds its size limit');
}
const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
try {
const contents = await handle.readFile('utf8');
try {
return JSON.parse(contents);
} catch {
throw new Error('Invalid JSON in task storage');
}
} finally {
await handle.close();
}
}
function validateRecord(value: unknown): PersistentTask {
if (!object(value) || value.version !== 1 || !object(value.task)) {
throw new Error('Invalid task storage record');
}
const task = value.task;
taskId(task.taskId);
if (
typeof task.createdAt !== 'string' ||
!Number.isFinite(Date.parse(task.createdAt)) ||
typeof task.lastUpdatedAt !== 'string' ||
!Number.isFinite(Date.parse(task.lastUpdatedAt)) ||
task.ttlMs !== null ||
task.pollIntervalMs !== 1000 ||
(task.statusMessage !== undefined && typeof task.statusMessage !== 'string')
) {
throw new Error('Invalid task storage metadata');
}
const base: TaskBase = {
taskId: taskId(task.taskId),
createdAt: task.createdAt,
lastUpdatedAt: task.lastUpdatedAt,
ttlMs: null,
pollIntervalMs: 1000,
...(typeof task.statusMessage === 'string' ? { statusMessage: task.statusMessage } : {}),
};
switch (task.status) {
case 'working':
return { ...base, status: 'working' };
case 'input_required': {
// In-flight work is never resumed, but corruption must not be hidden.
const requests = validateInputRequests(task.inputRequests);
return { ...base, status: 'input_required', inputRequests: requests };
}
case 'cancelled':
return { ...base, status: 'cancelled' };
case 'failed': {
if (
!object(task.error) ||
!Number.isSafeInteger(task.error.code) ||
typeof task.error.message !== 'string'
) {
throw new Error('Invalid persisted task error');
}
return {
...base,
status: 'failed',
error: {
code: Number(task.error.code),
message: task.error.message,
...(task.error.data !== undefined ? { data: task.error.data } : {}),
},
};
}
case 'completed': {
const validated = specTypeSchemas.CallToolResult['~standard'].validate(task.result);
if (validated.issues) {
throw new Error('Invalid persisted task result');
}
return {
...base,
status: 'completed',
result: { ...validated.value, resultType: 'complete' },
};
}
default:
throw new Error('Unknown persisted task status');
}
}
function validateInputRequests(value: unknown): InputRequests {
if (!object(value) || Object.keys(value).length === 0) {
throw new Error('Task input requests must be a non-empty object');
}
const requests: InputRequests = Object.create(null);
for (const [key, request] of Object.entries(value)) {
if (!object(request)) {
throw new Error('Invalid task input request');
}
const schema =
request.method === 'elicitation/create'
? specTypeSchemas.ElicitRequest
: request.method === 'sampling/createMessage'
? specTypeSchemas.CreateMessageRequest
: request.method === 'roots/list'
? specTypeSchemas.ListRootsRequest
: undefined;
const parsed = schema?.['~standard'].validate(request);
if (!parsed || parsed.issues) {
throw new Error('Invalid task input request');
}
requests[key] = parsed.value;
}
return requests;
}
/** One runtime owns one private directory; callbacks and credentials are never persisted. */
export class PersistentTasks {
private readonly records = new Map<string, PersistentTask>();
private readonly active = new Map<string, ActiveTask>();
private queue: Promise<void> = Promise.resolve();
private notifications: Promise<void> = Promise.resolve();
private closed = false;
private closingRequested = false;
private leaseReleased = false;
private persistenceError?: Error;
private constructor(
private readonly directory: string,
private readonly lease: string,
private readonly options: TaskStoreOptions,
) {}
static async open(directory: string, options: TaskStoreOptions): Promise<PersistentTasks> {
if (!path.isAbsolute(directory) || !/^[a-f0-9]{64}$/.test(options.scopeId)) {
throw new Error(
'Task storage requires an absolute directory and a SHA-256 scope identifier',
);
}
if (
options.maxConcurrent !== undefined &&
(!Number.isSafeInteger(options.maxConcurrent) || options.maxConcurrent < 1)
) {
throw new Error('Task concurrency must be a positive integer');
}
await mkdir(directory, { recursive: true, mode: 0o700 });
const stat = await lstat(directory);
if (
!stat.isDirectory() ||
stat.isSymbolicLink() ||
(process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
) {
throw new Error(
'Task storage directory must be private (0700) and cannot be a symlink',
);
}
const resolved = await realpath(directory);
const lease = `.lease-${randomUUID()}.json`;
const store = new PersistentTasks(resolved, lease, options);
try {
await store.save(lease, { pid: process.pid, host: hostname() });
// Publishing our lease before inspecting peers makes concurrent starts
// mutually exclusive. A dead owner's lease is recoverable after a crash.
for (const name of await readdir(resolved)) {
if (!/^\.lease-[a-f0-9-]+\.json$/.test(name) || name === lease) {
continue;
}
let owner: unknown;
try {
owner = await readPrivateJson(path.join(resolved, name));
} catch (error) {
if (errorCode(error) === 'ENOENT') {
continue;
}
throw error;
}
if (
!object(owner) ||
!Number.isSafeInteger(owner.pid) ||
Number(owner.pid) <= 0 ||
owner.host !== hostname()
) {
throw new Error('Task storage has an invalid or foreign-host lock');
}
try {
process.kill(Number(owner.pid), 0);
throw new Error('Task storage is locked by another runtime');
} catch (error) {
if (errorCode(error) !== 'ESRCH') {
throw error;
}
}
await unlink(path.join(resolved, name)).catch((error: unknown) => {
if (errorCode(error) !== 'ENOENT') {
throw error;
}
});
store.report('recovered_stale_lock');
}
const entries = await readdir(resolved);
if (entries.includes('scope.json')) {
const scope = await readPrivateJson(path.join(resolved, 'scope.json'));
if (!object(scope) || scope.version !== 1 || scope.scopeId !== options.scopeId) {
throw new Error(
'Task storage belongs to a different account or permission scope',
);
}
} else {
if (entries.some((name) => name.endsWith('.task.json'))) {
throw new Error('Task storage is missing its scope record');
}
await store.save('scope.json', { version: 1, scopeId: options.scopeId });
}
for (const name of entries) {
if (!name.endsWith('.task.json')) {
continue;
}
const id = taskId(name.slice(0, -10));
let task = validateRecord(await readPrivateJson(path.join(resolved, name)));
if (task.taskId !== id) {
throw new Error('Task storage identifier mismatch');
}
if (!terminal(task)) {
task = {
...summary(task),
status: 'failed',
lastUpdatedAt: new Date().toISOString(),
statusMessage: INTERRUPTED,
error: { code: -32603, message: INTERRUPTED },
};
await store.save(name, { version: 1, task });
store.report('interrupted_task_not_replayed', id);
}
store.records.set(id, task);
}
return store;
} catch (error) {
await unlink(path.join(resolved, lease)).catch((cleanupError: unknown) => {
if (errorCode(cleanupError) !== 'ENOENT') {
throw new AggregateError(
[error, cleanupError],
'Task startup and lock cleanup failed',
);
}
});
throw error;
}
}
private report(event: string, id?: string): void {
const error = new Error(`Task runtime: ${event}`);
if (this.options.onError) {
try {
this.options.onError(error, { event, ...(id ? { taskId: id } : {}) });
} catch {
console.error('[snowluma-mcp] task diagnostic callback failed');
}
} else {
console.error(
'[snowluma-mcp] %s',
JSON.stringify({ event, ...(id ? { taskId: id } : {}) }),
);
}
}
private async save(name: string, data: unknown): Promise<void> {
const serialized = JSON.stringify(data);
if (Buffer.byteLength(serialized) > MAX_RECORD_BYTES) {
throw new Error('Task record exceeds its size limit');
}
const temporary = path.join(this.directory, `.tmp-${randomUUID()}`);
const file = await open(temporary, 'wx', 0o600);
try {
await file.writeFile(serialized);
await file.sync();
} finally {
await file.close();
}
await rename(temporary, path.join(this.directory, name));
// Windows does not support opening directories for fsync.
if (process.platform !== 'win32') {
const directory = await open(this.directory, 'r');
try {
await directory.sync();
} finally {
await directory.close();
}
}
}
private serial<T>(operation: () => Promise<T>): Promise<T> {
const next = this.queue.then(operation);
this.queue = next.then(
() => undefined,
() => undefined,
);
return next;
}
private async put(task: PersistentTask): Promise<void> {
try {
await this.save(`${task.taskId}.task.json`, { version: 1, task });
} catch (error) {
this.persistenceError = new Error(
'Task persistence failed; stop using this runtime and inspect its storage',
{ cause: error },
);
throw this.persistenceError;
}
this.records.set(task.taskId, task);
if (this.options.onChange) {
const snapshot = structuredClone(task);
// Subscription backpressure must not block durable state or cancel.
this.notifications = this.notifications
.then(() => this.options.onChange?.(snapshot))
.catch(() => {
this.report('task_notification_failed', task.taskId);
});
}
}
get(id: string): PersistentTask {
if (this.persistenceError) {
throw this.persistenceError;
}
const task = this.records.get(taskId(id));
if (!task) {
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Unknown task identifier');
}
return structuredClone(task);
}
list(options: { cursor?: string; limit?: number } = {}): {
tasks: TaskSummary[];
nextCursor?: string;
} {
if (this.persistenceError) {
throw this.persistenceError;
}
const limit = options.limit ?? 50;
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) {
throw new ProtocolError(
ProtocolErrorCode.InvalidParams,
'Task page size must be between 1 and 100',
);
}
const entries = [...this.records.values()].sort(
(a, b) => a.createdAt.localeCompare(b.createdAt) || a.taskId.localeCompare(b.taskId),
);
const previous =
options.cursor === undefined
? -1
: entries.findIndex((task) => task.taskId === taskId(options.cursor));
if (options.cursor !== undefined && previous < 0) {
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Unknown task cursor');
}
const page = entries.slice(previous + 1, previous + 1 + limit);
return {
tasks: page.map(summary),
...(previous + 1 + page.length < entries.length
? { nextCursor: page.at(-1)!.taskId }
: {}),
};
}
async start(
execute: (context: TaskExecutionContext) => Promise<CallToolResult>,
): Promise<TaskHandle> {
if (this.closingRequested) {
throw new Error('Task runtime is closed');
}
const task = await this.serial(async () => {
if (this.closed) {
throw new Error('Task runtime is closed');
}
if (this.persistenceError) {
throw this.persistenceError;
}
if (this.active.size >= (this.options.maxConcurrent ?? 4)) {
throw new Error('Task concurrency limit reached');
}
const now = new Date().toISOString();
const task: PersistentTask = {
taskId: randomUUID(),
status: 'working',
createdAt: now,
lastUpdatedAt: now,
ttlMs: null,
pollIntervalMs: 1000,
};
await this.put(task);
this.active.set(task.taskId, {
controller: new AbortController(),
usedInputKeys: new Set(),
});
return task;
});
// Persist the handle before starting a callback that can have side effects.
void this.run(task.taskId, execute);
return { ...summary(task), resultType: 'task', content: [] };
}
private async run(
id: string,
execute: (context: TaskExecutionContext) => Promise<CallToolResult>,
): Promise<void> {
// close() owns pending records too; keep them registered until it has
// durably marked their outcome instead of dropping them in finally.
if (this.closingRequested) {
return;
}
const active = this.active.get(id)!;
try {
if (this.persistenceError) {
throw this.persistenceError;
}
if (active.controller.signal.aborted) {
throw active.controller.signal.reason;
}
const result = await execute({
taskId: id,
signal: active.controller.signal,
requestInput: (requests) => this.requestInput(id, requests),
});
const validated = specTypeSchemas.CallToolResult['~standard'].validate(result);
if (validated.issues) {
throw new Error('Invalid task execution result');
}
await this.serial(async () => {
if (this.closed || terminal(this.get(id))) {
return;
}
// A successful late completion can win a cooperative cancellation.
await this.put({
...summary(this.get(id)),
status: 'completed',
statusMessage: undefined,
lastUpdatedAt: new Date().toISOString(),
result: { ...validated.value, resultType: 'complete' },
});
});
} catch (error) {
try {
await this.serial(async () => {
if (this.closed || terminal(this.get(id))) {
return;
}
const base = {
...summary(this.get(id)),
lastUpdatedAt: new Date().toISOString(),
};
await this.put(
active.controller.signal.aborted
? { ...base, status: 'cancelled', statusMessage: CANCELLED }
: {
...base,
status: 'failed',
statusMessage:
'Task execution failed; check the correlated call diagnostics.',
error: {
code: error instanceof ProtocolError ? error.code : -32603,
message:
error instanceof ProtocolError
? error.message
: 'Task execution failed; remote outcome may be unknown.',
...(error instanceof ProtocolError && error.data !== undefined
? { data: error.data }
: {}),
},
},
);
});
} catch {
this.report('task_persistence_failed', id);
}
if (!active.controller.signal.aborted) {
this.report('task_execution_failed', id);
}
} finally {
active.input?.reject(new Error('Task execution ended'));
this.active.delete(id);
}
}
private async requestInput(id: string, requests: InputRequests): Promise<InputResponses> {
const validated = validateInputRequests(requests);
const pending = await this.serial(async () => {
const active = this.active.get(id);
if (
!active ||
active.controller.signal.aborted ||
this.closed ||
terminal(this.get(id))
) {
throw new Error(CANCELLED);
}
if (active.input) {
throw new Error('Task already has pending input');
}
if (Object.keys(validated).some((key) => active.usedInputKeys.has(key))) {
throw new Error('Task input keys must be unique for its entire lifetime');
}
await this.put({
...summary(this.get(id)),
status: 'input_required',
lastUpdatedAt: new Date().toISOString(),
inputRequests: validated,
});
let resolve!: (responses: InputResponses) => void;
let reject!: (error: Error) => void;
const promise = new Promise<InputResponses>((yes, no) => {
resolve = yes;
reject = no;
});
active.input = {
outstanding: validated,
responses: Object.create(null),
resolve,
reject,
};
for (const key of Object.keys(validated)) {
active.usedInputKeys.add(key);
}
return { promise };
});
return pending.promise;
}
async update(id: string, responses: unknown): Promise<void> {
if (!object(responses)) {
throw new ProtocolError(
ProtocolErrorCode.InvalidParams,
'Input responses must be an object',
);
}
await this.serial(async () => {
if (this.closed) {
throw new Error('Task runtime is closed');
}
const task = this.get(id);
const active = this.active.get(id);
const pending = active?.input;
if (task.status !== 'input_required' || !pending) {
return;
}
const accepted: InputResponses = Object.create(null);
for (const [key, response] of Object.entries(responses)) {
if (!Object.hasOwn(pending.outstanding, key)) {
continue;
}
const request = pending.outstanding[key];
if (!request) {
continue;
}
const schema =
request.method === 'elicitation/create'
? specTypeSchemas.ElicitResult
: request.method === 'sampling/createMessage'
? specTypeSchemas.CreateMessageResult
: specTypeSchemas.ListRootsResult;
const parsed = schema['~standard'].validate(response);
if (parsed.issues) {
throw new ProtocolError(
ProtocolErrorCode.InvalidParams,
'Invalid task input response',
);
}
accepted[key] = parsed.value;
}
if (Object.keys(accepted).length === 0) {
return;
}
const outstanding = { ...pending.outstanding };
for (const key of Object.keys(accepted)) {
delete outstanding[key];
}
const done = Object.keys(outstanding).length === 0;
await this.put(
done
? {
...summary(task),
status: 'working',
lastUpdatedAt: new Date().toISOString(),
}
: {
...summary(task),
status: 'input_required',
lastUpdatedAt: new Date().toISOString(),
inputRequests: outstanding,
},
);
Object.assign(pending.responses, accepted);
pending.outstanding = outstanding;
if (done) {
active.input = undefined;
pending.resolve(pending.responses);
}
});
}
async cancel(id: string): Promise<void> {
await this.serial(async () => {
if (this.closed) {
throw new Error('Task runtime is closed');
}
const task = this.get(id);
if (terminal(task)) {
return;
}
const active = this.active.get(id);
if (!active) {
throw new Error('Task execution is unavailable');
}
await this.put({
...task,
lastUpdatedAt: new Date().toISOString(),
statusMessage: CANCELLATION_REQUESTED,
});
active.controller.abort(new Error(CANCELLED));
active.input?.reject(new Error(CANCELLED));
});
}
async close(): Promise<void> {
this.closingRequested = true;
await this.serial(async () => {
if (this.leaseReleased) {
return;
}
this.closed = true;
const activeTasks = [...this.active.entries()];
// Abort all executions even when persistence has failed. Failed writes
// still reject close; a later process will terminate the durable state.
for (const [, active] of activeTasks) {
active.controller.abort(new Error(INTERRUPTED));
active.input?.reject(new Error(INTERRUPTED));
}
let failure: unknown;
for (const [id] of activeTasks) {
const task = this.records.get(id)!;
try {
if (!terminal(task)) {
await this.put({
...summary(task),
status: 'failed',
lastUpdatedAt: new Date().toISOString(),
statusMessage: INTERRUPTED,
error: { code: -32603, message: INTERRUPTED },
});
}
} catch (error) {
failure ??= error;
}
}
await unlink(path.join(this.directory, this.lease));
this.leaseReleased = true;
this.active.clear();
if (failure) {
throw failure;
}
});
}
}
const taskParams: StandardSchemaV1<unknown, { taskId: string }> = {
'~standard': {
version: 1 as const,
vendor: 'snowluma',
validate(value: unknown) {
if (!object(value) || typeof value.taskId !== 'string' || !ID.test(value.taskId)) {
return { issues: [{ message: 'Invalid task identifier' }] };
}
return { value: { taskId: value.taskId } };
},
},
};
export function installTaskHandlers(
server: Server,
tasks: PersistentTasks,
options: { authorize?: (ctx: ServerContext) => void } = {},
): void {
const authorize = (ctx: ServerContext) => {
requireTasks(ctx, server.getNegotiatedProtocolVersion());
options.authorize?.(ctx);
};
server.registerCapabilities(TASK_CAPABILITIES);
server.setRequestHandler('tasks/get', { params: taskParams }, (params, ctx) => {
authorize(ctx);
return { ...tasks.get(params.taskId) };
});
server.setRequestHandler('tasks/cancel', { params: taskParams }, async (params, ctx) => {
authorize(ctx);
await tasks.cancel(params.taskId);
return {};
});
server.setRequestHandler('tasks/update', { params: taskParams }, async (params, ctx) => {
authorize(ctx);
const task = tasks.get(params.taskId);
const invalidOutstanding =
task.status === 'input_required' &&
ctx.mcpReq.droppedInputResponseKeys?.some((key) =>
Object.hasOwn(task.inputRequests, key),
);
if (!ctx.mcpReq.inputResponses || invalidOutstanding) {
throw new ProtocolError(
ProtocolErrorCode.InvalidParams,
'Invalid task input responses',
);
}
await tasks.update(params.taskId, ctx.mcpReq.inputResponses);
return {};
});
}
+201 -59
View File
@@ -8,10 +8,24 @@
// Visibility is gated by `mode`, and `callTool` RE-checks every permission
// (defense in depth: a client may call a tool that was never listed).
import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';
import type { Tool } from '@modelcontextprotocol/server';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import type { CatalogAction } from './types.js';
import type { ActionClient } from './client.js';
import { MCP_UPLOAD_OWNED_FIELDS } from './client.js';
import { discover, FILTER_PROPERTIES } from './discovery.js';
import {
asText,
asError,
envelopeDiagnostics,
executionError,
RESULT_SCHEMA,
type Diagnostics,
type StructuredResult,
} from './results.js';
import { VERSION } from './version.js';
import type { TransferProgress } from './client.js';
import type { TraceContext } from './tracing.js';
export type Mode = 'docs' | 'read' | 'write';
@@ -38,26 +52,15 @@ for (const a of ACTIONS) {
}
}
/** Lightweight index entry (keeps list/search payloads small). */
function lite(a: CatalogAction) {
return {
name: a.name,
category: a.category,
summary: a.summary,
aliases: a.aliases,
readOnly: a.readOnly,
stream: a.stream ?? false,
};
}
const DOCS_TOOLS: Tool[] = [
{
name: 'list_actions',
description: '列出 OneBot action,支持按分类过滤。返回名称、摘要、别名及执行类型。',
description:
'列出 OneBot action,支持分类、读写类型、流式类型筛选和可选分页。省略分页时返回全部匹配项。',
inputSchema: {
type: 'object',
properties: {
category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' },
...FILTER_PROPERTIES,
},
additionalProperties: false,
},
@@ -65,7 +68,8 @@ const DOCS_TOOLS: Tool[] = [
},
{
name: 'get_action',
description: '获取 action 文档、参数 JSON Schema、约束和返回类型。',
description:
'获取 action 文档、参数与返回数据 JSON Schema、约束和调用示例。示例中的标识和路径需替换;流式返回结构描述单帧数据。',
inputSchema: {
type: 'object',
properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
@@ -76,10 +80,19 @@ const DOCS_TOOLS: Tool[] = [
},
{
name: 'search_actions',
description: '按名称、摘要或别名搜索 action。',
description:
'按名称、摘要或别名搜索 action。默认保留子串匹配;match=keywords 启用多关键词和常用中英文同义词,支持筛选及分页。',
inputSchema: {
type: 'object',
properties: { query: { type: 'string', description: '关键字' } },
properties: {
query: { type: 'string', description: '关键字;keywords 模式可用空格分隔多个词' },
match: {
type: 'string',
enum: ['substring', 'keywords'],
description: '默认 substring',
},
...FILTER_PROPERTIES,
},
required: ['query'],
additionalProperties: false,
},
@@ -91,6 +104,22 @@ const DOCS_TOOLS: Tool[] = [
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'get_runtime_info',
description:
'查看当前 MCP 模式、执行能力、文件限制和目录版本。默认不访问服务端;check_connection=true 仅在执行模式主动查询登录账号、状态和版本。静态目录不代表服务端支持全部动作。',
inputSchema: {
type: 'object',
properties: {
check_connection: {
type: 'boolean',
description: '主动进行三项只读查询,默认 false',
},
},
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: true },
},
];
const EXEC_INPUT_SCHEMA = {
@@ -150,23 +179,17 @@ export function computeTools(mode: Mode): Tool[] {
tools.push(invokeTool());
}
return tools;
return tools.map((tool) => ({ ...tool, outputSchema: RESULT_SCHEMA }));
}
export type ToolResult = CallToolResult;
function asText(data: unknown): ToolResult {
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
}
function asError(message: string): ToolResult {
return { content: [{ type: 'text', text: message }], isError: true };
}
export type ToolResult = StructuredResult;
export interface CallCtx {
mode: Mode;
client?: ActionClient;
signal?: AbortSignal;
trace?: TraceContext;
onProgress?: (progress: TransferProgress) => Promise<void>;
}
export async function callTool(
@@ -175,10 +198,13 @@ export async function callTool(
ctx: CallCtx,
): Promise<ToolResult> {
switch (name) {
case 'list_actions': {
const category = typeof args.category === 'string' ? args.category : undefined;
const list = ACTIONS.filter((a) => !category || a.category === category).map(lite);
return asText({ count: list.length, actions: list });
case 'list_actions':
case 'search_actions': {
try {
return asText(discover(ACTIONS, args, name === 'search_actions'));
} catch (error) {
return asError(error instanceof Error ? error.message : String(error));
}
}
case 'get_action': {
@@ -188,51 +214,64 @@ export async function callTool(
if (!action) {
return asError(
`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`,
'not_found',
'使用 list_actions / search_actions 查找动作。',
);
}
return asText(action);
}
case 'search_actions': {
const q = (typeof args.query === 'string' ? args.query : '').toLowerCase();
const list = ACTIONS.filter(
(a) =>
a.name.toLowerCase().includes(q) ||
(a.summary ?? '').toLowerCase().includes(q) ||
a.aliases.some((al) => al.toLowerCase().includes(q)),
).map(lite);
return asText({ count: list.length, actions: list });
}
case 'list_categories':
return asText(CATEGORIES);
case 'get_runtime_info':
return runtimeInfo(args, ctx);
case 'query_action':
return execute(args, ctx, 'read');
case 'invoke_action':
return execute(args, ctx, 'write');
default:
return asError(`未知工具: ${name}`);
return asError(`未知工具: ${name}`, 'not_found', '使用 tools/list 查看可用工具。');
}
}
/** Shared execution path for query_action (read) / invoke_action (write).
* Re-checks mode + readOnly routing regardless of which tools were listed. */
async function execute(
export interface PreparedActionCall {
action: string;
params: Record<string, unknown>;
inputFile?: string;
catalog: CatalogAction;
client: ActionClient;
inputSchema: Record<string, unknown>;
}
/** The same side-effect-free gate is used before execution and input collection. */
export function prepareActionCall(
args: Record<string, unknown>,
ctx: CallCtx,
kind: 'read' | 'write',
): Promise<ToolResult> {
): PreparedActionCall | ToolResult {
if (kind === 'write' && ctx.mode !== 'write') {
return asError('写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。');
return asError(
'写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。',
'permission',
'需要写操作时,请由操作者明确启用 write 模式。',
);
}
if (kind === 'read' && ctx.mode !== 'read' && ctx.mode !== 'write') {
return asError('执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。');
return asError(
'执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。',
'permission',
'配置端点并选择 read 或 write 模式后重启 MCP。',
);
}
if (!ctx.client) {
return asError('未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。');
return asError(
'未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。',
'configuration',
'检查 MCP 端点配置。',
);
}
const action = typeof args.action === 'string' ? args.action : '';
@@ -241,12 +280,16 @@ async function execute(
if (!cat) {
return asError(
`未知 action: ${JSON.stringify(action)}。用 list_actions / search_actions 查可用项。`,
'not_found',
'使用 list_actions / search_actions 查找动作。',
);
}
if (kind === 'read' && !cat.readOnly) {
return asError(
`${action} 是写操作,不能用 query_action;请用 invoke_action(需 SNOWLUMA_MCP_MODE=write)。`,
'permission',
'需写模式和 invoke_action;不要通过只读工具绕过写操作限制。',
);
}
@@ -289,15 +332,114 @@ async function execute(
return asError('execution.input_file 仅可用于 upload_file_stream。');
}
const inputSchema =
inputFile && Array.isArray(cat.inputSchema.required)
? {
...cat.inputSchema,
required: cat.inputSchema.required.filter(
(key) => !MCP_UPLOAD_OWNED_FIELDS.includes(key),
),
}
: cat.inputSchema;
return { action, params, inputFile, catalog: cat, client: ctx.client, inputSchema };
}
/** Shared execution path for query_action (read) / invoke_action (write). */
async function execute(
args: Record<string, unknown>,
ctx: CallCtx,
kind: 'read' | 'write',
): Promise<ToolResult> {
const prepared = prepareActionCall(args, ctx, kind);
if ('structuredContent' in prepared) {
return prepared;
}
const { action, params, inputFile, catalog: cat, client } = prepared;
try {
const result = cat.stream
? await ctx.client.callStream(action, params, {
...(inputFile ? { inputFile } : {}),
...(ctx.signal ? { signal: ctx.signal } : {}),
})
: await ctx.client.call(action, params);
return asText(result);
ctx.signal?.throwIfAborted();
if (cat.stream) {
const result = await client.callStream(action, params, {
...(inputFile ? { inputFile } : {}),
...(ctx.signal ? { signal: ctx.signal } : {}),
...(ctx.trace ? { trace: ctx.trace } : {}),
...(ctx.onProgress ? { onProgress: ctx.onProgress } : {}),
});
return asText(result, envelopeDiagnostics(result.terminal));
}
const result = await client.call(
action,
params,
ctx.signal || ctx.trace
? {
...(ctx.signal ? { signal: ctx.signal } : {}),
...(ctx.trace ? { trace: ctx.trace } : {}),
}
: undefined,
);
return asText(result, envelopeDiagnostics(result));
} catch (err) {
return asError(`调用失败 (${action}): ${err instanceof Error ? err.message : String(err)}`);
return executionError(action, err, ctx.signal);
}
}
async function runtimeInfo(args: Record<string, unknown>, ctx: CallCtx): Promise<ToolResult> {
if (args.check_connection !== undefined && typeof args.check_connection !== 'boolean') {
return asError('check_connection 必须是布尔值。');
}
const enabled = ctx.mode !== 'docs' && !!ctx.client;
if (args.check_connection && !enabled) {
return asError(
'当前模式不能检查连接:需配置端点并启用 read 或 write 模式。',
'permission',
'先用 get_runtime_info 查看本地模式,再由操作者配置连接。',
);
}
const overview = {
mode: ctx.mode,
execution_enabled: enabled,
write_enabled: enabled && ctx.mode === 'write',
catalog: {
version: VERSION,
action_count: ACTIONS.length,
source: 'bundled',
server_support: 'unknown',
},
transport: enabled ? (ctx.client?.info ?? null) : null,
connection_checked: args.check_connection === true,
};
if (!args.check_connection) {
return asText(overview);
}
const checks: Record<string, unknown> = {};
let outcome: Diagnostics['outcome'] = 'success';
for (const action of ['get_login_info', 'get_status', 'get_version_info']) {
const result = await execute({ action }, ctx, 'read');
checks[action] = result.structuredContent;
const diagnostics = result.structuredContent.diagnostics;
if (
diagnostics.outcome === 'unknown' ||
(diagnostics.outcome === 'failed' && outcome === 'success')
) {
outcome = diagnostics.outcome;
}
}
return asText(
{ ...overview, checks },
outcome === 'success'
? { outcome }
: { outcome, next_step: '查看 checks 中各项诊断;目录版本不等于服务端能力声明。' },
);
}
+110
View File
@@ -0,0 +1,110 @@
import { randomBytes } from 'node:crypto';
export interface TraceContext {
traceparent: string;
tracestate?: string;
}
function parentFields(value: unknown): { traceId: string; flags: string } | undefined {
if (typeof value !== 'string' || /[^\x21-\x7e]/.test(value)) {
return undefined;
}
const match = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(.*)$/.exec(value);
if (
!match ||
match[1] === 'ff' ||
/^0+$/.test(match[2]!) ||
/^0+$/.test(match[3]!) ||
(match[1] === '00' ? match[5] !== '' : match[5] !== '' && !match[5]!.startsWith('-'))
) {
return undefined;
}
// Participate using version 00, retaining only its defined sampled flag.
return { traceId: match[2]!, flags: (Number.parseInt(match[4]!, 16) & 1) === 1 ? '01' : '00' };
}
function traceState(value: unknown): string | undefined {
if (typeof value !== 'string' || value.length > 512 || /[^\x20-\x7e\t]/.test(value)) {
return undefined;
}
const members = value.split(',');
if (members.length > 32) {
return undefined;
}
const keys = new Set<string>();
const normalized: string[] = [];
for (const raw of members) {
const member = raw.replace(/^[ \t]+|[ \t]+$/g, '');
if (!member) {
continue;
}
const separator = member.indexOf('=');
const key = member.slice(0, separator);
const entry = member.slice(separator + 1);
if (
separator < 1 ||
!/^(?:[a-z][a-z0-9_*/-]{0,255}|[a-z0-9][a-z0-9_*/-]{0,240}@[a-z][a-z0-9_*/-]{0,13})$/.test(
key,
) ||
!/^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/.test(entry) ||
keys.has(key)
) {
return undefined;
}
keys.add(key);
normalized.push(member);
}
return normalized.join(',');
}
function identifier(bytes: number): string {
let value: string;
do {
value = randomBytes(bytes).toString('hex');
} while (/^0+$/.test(value));
return value;
}
/** Trace metadata is advisory: invalid fields never reject a tool or enter its params. */
export function createCallTrace(meta?: Record<string, unknown>): TraceContext {
const parent = parentFields(meta?.traceparent);
if (meta?.traceparent !== undefined && !parent) {
console.error('[snowluma-mcp] trace metadata ignored: invalid traceparent');
}
let state: string | undefined;
if (meta?.tracestate !== undefined) {
if (parent) {
state = traceState(meta.tracestate);
if (state === undefined) {
console.error('[snowluma-mcp] trace metadata ignored: invalid tracestate');
}
} else {
console.error(
'[snowluma-mcp] trace metadata ignored: tracestate without valid traceparent',
);
}
}
return {
traceparent: `00-${parent?.traceId ?? identifier(16)}-${identifier(8)}-${parent?.flags ?? '00'}`,
...(state ? { tracestate: state } : {}),
};
}
+8 -1
View File
@@ -26,8 +26,15 @@ export interface CatalogAction {
category?: string;
summary?: string;
returns?: string;
/** JSON Schema for the action's `data` payload (absent when undocumented). */
/** Successful OneBot `data`, or one successful stream frame's `data`.
* Does not describe the envelope or MCP's aggregated stream result. */
returnsSchema?: Record<string, unknown>;
/** Illustrative OneBot params; identifiers/paths must be replaced before use. */
examples?: ReadonlyArray<{
summary: string;
params: Record<string, unknown>;
notes?: string;
}>;
/** True only for pure data-fetch actions (no side effects). Drives the
* read/write tool routing: read-only → query_action, else → invoke_action.
* Classified at the source spec by what the action's `run` actually does. */
+6
View File
@@ -0,0 +1,6 @@
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {
version: string;
};
export const VERSION = pkg.version;
+245
View File
@@ -0,0 +1,245 @@
import { describe, expect, it, vi } from 'vitest';
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv-provider.js';
import { collectActionDocs } from '@snowluma/onebot/action-docs';
import { ApiHandler, type ApiActionContext } from '@snowluma/onebot/api-handler';
import type { JsonObject, JsonValue } from '@snowluma/onebot/types';
import { ACTIONS } from '../src/generated/catalog';
import { callTool } from '../src/tools';
const validator = new AjvJsonSchemaValidator();
function resultValidator(name: string) {
const action = ACTIONS.find((entry) => entry.name === name);
if (!action?.returnsSchema) {
throw new Error(`missing result schema: ${name}`);
}
return validator.getValidator(action.returnsSchema);
}
function matchesResult(name: string, data: unknown): void {
const result = resultValidator(name)(data);
expect(result.valid, `${name}: ${result.errorMessage}`).toBe(true);
}
/** Unexpected dependencies fail rather than contacting an account or a network. */
function context(values: Record<string, unknown> = {}): ApiActionContext {
return new Proxy(values, {
get(target, key) {
if (typeof key === 'string' && Object.hasOwn(target, key)) {
return target[key];
}
throw new Error(`unstubbed action context: ${String(key)}`);
},
}) as unknown as ApiActionContext;
}
describe('bundled action contracts', () => {
it('matches the owning specs, without relying on a second hand-authored registry', () => {
expect(ACTIONS).toEqual(JSON.parse(JSON.stringify(collectActionDocs())));
});
it.each(ACTIONS)('$name publishes compilable schemas and schema-valid examples', (action) => {
expect(() => resultValidator(action.name)).not.toThrow();
const validateInput = validator.getValidator(action.inputSchema);
expect(action.examples?.length).toBeGreaterThan(0);
for (const example of action.examples ?? []) {
const result = validateInput(example.params);
expect(result.valid, `${action.name}: ${result.errorMessage}`).toBe(true);
}
});
it('exposes full contracts through get_action and aliases without executing anything', async () => {
const client = { call: vi.fn(), callStream: vi.fn() };
for (const action of ACTIONS) {
for (const name of [action.name, ...action.aliases]) {
const result = await callTool('get_action', { name }, { mode: 'docs', client });
expect(result.structuredContent.result).toEqual(action);
expect(result.content[0]).toEqual({
type: 'text',
text: JSON.stringify(action, null, 2),
});
}
}
expect(client.call).not.toHaveBeenCalled();
expect(client.callStream).not.toHaveBeenCalled();
});
it.each(['list_actions', 'search_actions'])('keeps %s compact', async (name) => {
const result = await callTool(name, { query: 'send_group_msg' }, { mode: 'docs' });
const block = result.content[0];
expect(block.type).toBe('text');
if (block.type !== 'text') {
throw new Error('expected text result');
}
const payload = JSON.parse(block.text);
expect(payload.actions.length).toBeGreaterThan(0);
for (const action of payload.actions) {
expect(action).not.toHaveProperty('examples');
expect(action).not.toHaveProperty('returnsSchema');
}
});
});
describe('result schemas against actual OneBot handlers', () => {
it('preserves signed message IDs and documents the upload-only sentinel separately', async () => {
const api = new ApiHandler(
context({
sendGroupMessage: async () => ({ messageId: -123 }),
sendForwardMsg: async () => ({ forwardId: 'example-forward' }),
}),
);
const send = await api.handle('send_group_msg', { group_id: 20001, message: 'hello' });
expect(send).toEqual({ status: 'ok', retcode: 0, data: { message_id: -123 } });
matchesResult('send_group_msg', send.data);
expect(resultValidator('send_group_msg')({ message_id: 0 }).valid).toBe(false);
for (const name of ['upload_forward_msg', 'upload_foward_msg']) {
const uploaded = await api.handle(name, {
group_id: 20001,
messages: [
{
type: 'node',
data: { user_id: 10001, nickname: 'example', content: 'hello' },
},
],
});
expect(uploaded.status).toBe('ok');
expect(uploaded.data).toMatchObject({ message_id: 0, res_id: 'example-forward' });
matchesResult(name, uploaded.data);
if (name === 'upload_forward_msg') {
expect(uploaded.data).toHaveProperty('group_id', 20001);
} else {
expect(uploaded.data).not.toHaveProperty('group_id');
}
}
});
it('distinguishes null, empty objects, and failed unsupported calls', async () => {
const api = new ApiHandler(
context({
bridge: {
apis: {
friend: { setRemark: async () => {} },
profile: { setInputStatus: async () => {} },
},
},
}),
);
const empty = await api.handle('set_friend_remark', { user_id: 10001, remark: 'example' });
expect(empty.data).toBeNull();
matchesResult('set_friend_remark', empty.data);
expect(resultValidator('set_friend_remark')({}).valid).toBe(false);
const object = await api.handle('set_input_status', { user_id: 10001 });
expect(object.data).toEqual({});
matchesResult('set_input_status', object.data);
expect(resultValidator('set_input_status')(null).valid).toBe(false);
for (const name of ['set_restart', 'create_collection', '.get_word_slices']) {
const failure = await api.handle(name, {});
expect(failure.status).toBe('failed');
expect(resultValidator(name)(failure.data).valid).toBe(false);
}
});
it('documents actual media string sizes and optional converted record fields', async () => {
const media = {
file: 'https://example.com/media',
url: 'https://example.com/media',
file_size: '42',
file_name: 'voice.amr',
};
const api = new ApiHandler(
context({
getImageInfo: async () => media,
getRecordInfo: async () => media,
bridge: {
apis: {
extras: { convertRecord: async () => ({ base64: 'aGVsbG8=', size: 5 }) },
},
},
}),
);
for (const name of ['get_image', 'get_file', 'get_record']) {
const result = await api.handle(name, { file: 'cached-media' });
expect(result.status).toBe('ok');
matchesResult(name, result.data);
expect(resultValidator(name)({ ...media, file_size: 42 }).valid).toBe(false);
}
const converted = await api.handle('get_record', {
file: 'cached-media',
out_format: 'mp3',
});
expect(converted.data).toEqual({ ...media, out_format: 'mp3', base64: 'aGVsbG8=' });
matchesResult('get_record', converted.data);
});
it('describes get_msg data without the event envelope for both conversation types', async () => {
for (const messageType of ['group', 'private']) {
const event: JsonObject = {
post_type: 'message',
self_id: 10002,
message_type: messageType,
message_id: -123,
user_id: 10001,
time: 1700000000,
message: [{ type: 'text', data: { text: 'hello' } }],
raw_message: 'hello',
...(messageType === 'group' ? { group_id: 20001 } : { target_id: 10002 }),
};
const api = new ApiHandler(
context({
getMessage: async () => event,
refreshMessageMedia: async () => {},
}),
);
const result = await api.handle('get_msg', { message_id: -123 });
expect(result.status).toBe('ok');
expect(result.data).toMatchObject({ real_id: -123, message_id: -123 });
expect(result.data).not.toHaveProperty('post_type');
expect(result.data).not.toHaveProperty('self_id');
matchesResult('get_msg', result.data);
}
});
it('describes successful stream frame data, not MCP aggregate results or failed frames', async () => {
const api = new ApiHandler(context());
const frames: JsonValue[] = [];
const response = await api.handle(
'test_download_stream',
{ error: false },
{
send: async (frame) => {
frames.push(frame);
},
},
);
expect(frames).toHaveLength(10);
expect(response.status).toBe('ok');
for (const frame of [...frames, response.data]) {
matchesResult('test_download_stream', frame);
}
expect(
resultValidator('test_download_stream')({ frame_count: 11, frames, terminal: response })
.valid,
).toBe(false);
expect(
resultValidator('test_download_stream')({ type: 'error', data_type: 'error' }).valid,
).toBe(false);
const failure = await api.handle('test_download_stream', { error: true });
expect(failure.status).toBe('failed');
});
});
+275
View File
@@ -0,0 +1,275 @@
import { describe, expect, it, vi } from 'vitest';
import { callTool, computeTools } from '../src/tools';
import { ACTIONS } from '../src/generated/catalog';
import type { ActionClient, OneBotEnvelope } from '../src/client';
import { ActionCallError } from '../src/results';
const docs = { mode: 'docs' as const };
function client(
reply: OneBotEnvelope = { status: 'ok', retcode: 0, data: { message_id: -123 } },
): ActionClient {
return {
call: vi.fn(async () => reply),
callStream: vi.fn(async () => ({ frame_count: 1, frames: [], terminal: reply })),
};
}
function text(result: Awaited<ReturnType<typeof callTool>>) {
expect(result.content[0].type).toBe('text');
return result.content[0].type === 'text' ? result.content[0].text : '';
}
describe('additive structured results', () => {
it.each(['list_actions', 'list_categories', 'get_action', 'search_actions'])(
'keeps the original text payload for %s',
async (name) => {
const result = await callTool(name, { name: 'get_status', query: 'get_status' }, docs);
expect(result.structuredContent.result).toEqual(JSON.parse(text(result)));
expect(result.structuredContent.diagnostics).toEqual({ outcome: 'success' });
expect(
computeTools('docs').find((tool) => tool.name === name)?.outputSchema,
).toBeDefined();
},
);
it.each([
{ status: 'ok', retcode: 0, data: { message_id: -123 } },
{ status: 'failed', retcode: 1404, wording: 'not found' },
{ status: 'async', retcode: 1 },
])('preserves the OneBot envelope and isError contract ($status)', async (reply) => {
const result = await callTool(
'invoke_action',
{ action: 'send_group_msg' },
{ mode: 'write', client: client(reply) },
);
expect(text(result)).toBe(JSON.stringify(reply, null, 2));
expect(result.isError).toBeUndefined();
expect(result.structuredContent.result).toEqual(reply);
expect(result.structuredContent.diagnostics.outcome).toBe(
reply.status === 'ok' ? 'success' : reply.status === 'failed' ? 'failed' : 'unknown',
);
});
it('reports permission failures without contacting OneBot', async () => {
const onebot = client();
const result = await callTool(
'query_action',
{ action: 'send_group_msg' },
{ mode: 'read', client: onebot },
);
expect(result.isError).toBe(true);
expect(result.structuredContent.diagnostics).toMatchObject({
outcome: 'failed',
kind: 'permission',
});
expect(onebot.call).not.toHaveBeenCalled();
});
it.each(['timeout', 'cancelled', 'authentication', 'transport', 'invalid_response'] as const)(
'makes %s observable without claiming a write was rolled back',
async (kind) => {
const onebot = client();
onebot.call = vi.fn(async () => {
throw new ActionCallError('request failed', kind);
});
const result = await callTool(
'invoke_action',
{ action: 'send_group_msg' },
{ mode: 'write', client: onebot },
);
expect(result.isError).toBe(true);
expect(result.structuredContent.diagnostics).toMatchObject({
outcome: 'unknown',
kind,
});
expect(result.structuredContent.diagnostics.next_step).toContain('不代表撤销');
expect(onebot.call).toHaveBeenCalledTimes(1);
},
);
it('does not report an incomplete response as successful', async () => {
const onebot = client();
onebot.call = async () => JSON.parse('{"data":null}');
const result = await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot },
);
expect(result.structuredContent.diagnostics).toMatchObject({
outcome: 'unknown',
kind: 'invalid_response',
});
expect(text(result)).toBe('{\n "data": null\n}');
});
it('keeps malformed peer fields in the original payload without breaking the diagnostics schema', async () => {
const onebot = client();
onebot.call = async () =>
JSON.parse('{"status":"failed","retcode":1400,"wording":{"unexpected":true}}');
const result = await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot },
);
expect(result.structuredContent.diagnostics.message).toBe('retcode=1400');
expect(JSON.parse(text(result)).wording).toEqual({ unexpected: true });
});
});
describe('optional discovery controls', () => {
it('keeps legacy matching, ordering and response fields by default', async () => {
const result = await callTool('search_actions', { query: '群 禁言' }, docs);
expect(JSON.parse(text(result))).toEqual({ count: 0, actions: [] });
const all = JSON.parse(text(await callTool('list_actions', {}, docs)));
expect(Object.keys(all)).toEqual(['count', 'actions']);
expect(all.actions.map((action: { name: string }) => action.name)).toEqual(
ACTIONS.map((action) => action.name),
);
});
it.each([
['群 禁言', 'set_group_ban'],
['历史消息', 'get_group_msg_history'],
['私聊 history', 'get_friend_msg_history'],
['group mute', 'set_group_ban'],
])('finds %s with optional keyword matching', async (query, expected) => {
const data = JSON.parse(
text(await callTool('search_actions', { query, match: 'keywords' }, docs)),
);
expect(data.actions.map((action: { name: string }) => action.name)).toContain(expected);
});
it('ranks an exact alias first and combines filters', async () => {
const exact = JSON.parse(
text(
await callTool('search_actions', { query: 'nc_get_rkey', match: 'keywords' }, docs),
),
);
expect(exact.actions[0].name).toBe('get_rkey');
const filtered = JSON.parse(
text(
await callTool(
'search_actions',
{
query: '群',
match: 'keywords',
category: '群管理',
read_only: false,
stream: false,
},
docs,
),
),
);
expect(filtered.count).toBeGreaterThan(0);
expect(
filtered.actions.every(
(action: { category: string; readOnly: boolean; stream: boolean }) =>
action.category === '群管理' && !action.readOnly && !action.stream,
),
).toBe(true);
});
it('paginates deterministically with explicit totals and termination', async () => {
const names: string[] = [];
let offset: number | null = 0;
while (offset !== null) {
const data = JSON.parse(
text(await callTool('list_actions', { limit: 37, offset }, docs)),
);
expect(data.total).toBe(ACTIONS.length);
expect(data.count).toBe(data.actions.length);
names.push(...data.actions.map((action: { name: string }) => action.name));
offset = data.next_offset;
}
expect(names).toEqual(ACTIONS.map((action) => action.name));
const beyond = JSON.parse(text(await callTool('list_actions', { offset: 9999 }, docs)));
expect(beyond).toEqual({ count: 0, actions: [], total: ACTIONS.length, next_offset: null });
});
it.each([
{ limit: 0 },
{ limit: 201 },
{ offset: -1 },
{ offset: 0.5 },
{ stream: 'true' },
{ read_only: 1 },
{ match: 'typo' },
])('rejects invalid new options (%j)', async (options) => {
const result = await callTool('search_actions', { query: '', ...options }, docs);
expect(result.isError).toBe(true);
expect(result.structuredContent.diagnostics.kind).toBe('invalid_arguments');
});
});
describe('runtime overview and caller cancellation', () => {
it('does not contact OneBot for a local overview, even if a client exists in docs mode', async () => {
const onebot = client();
const result = await callTool('get_runtime_info', {}, { ...docs, client: onebot });
expect(result.structuredContent.result).toMatchObject({
mode: 'docs',
execution_enabled: false,
write_enabled: false,
transport: null,
connection_checked: false,
catalog: { action_count: ACTIONS.length, server_support: 'unknown' },
});
expect(onebot.call).not.toHaveBeenCalled();
const denied = await callTool(
'get_runtime_info',
{ check_connection: true },
{ ...docs, client: onebot },
);
expect(denied.isError).toBe(true);
expect(onebot.call).not.toHaveBeenCalled();
});
it('only performs the three explicit read-only checks and preserves individual failures', async () => {
const onebot = client();
const controller = new AbortController();
onebot.call = vi.fn(async (action, _params, options) => {
expect(options?.signal).toBe(controller.signal);
return action === 'get_status'
? { status: 'failed', retcode: 1401, wording: 'unauthorized' }
: { status: 'ok', retcode: 0, data: { action } };
});
const result = await callTool(
'get_runtime_info',
{ check_connection: true },
{ mode: 'read', client: onebot, signal: controller.signal },
);
expect(vi.mocked(onebot.call).mock.calls.map(([action]) => action)).toEqual([
'get_login_info',
'get_status',
'get_version_info',
]);
expect(result.structuredContent.diagnostics.outcome).toBe('failed');
expect(result.structuredContent.result).toMatchObject({
checks: {
get_status: { result: { retcode: 1401 }, diagnostics: { outcome: 'failed' } },
},
});
});
it('forwards ordinary request cancellation and does not start pre-cancelled calls', async () => {
const controller = new AbortController();
const onebot = client();
await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot, signal: controller.signal },
);
expect(onebot.call).toHaveBeenCalledWith('get_status', {}, { signal: controller.signal });
controller.abort();
const result = await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot, signal: controller.signal },
);
expect(onebot.call).toHaveBeenCalledTimes(1);
expect(result.structuredContent.diagnostics.kind).toBe('cancelled');
});
});
+124
View File
@@ -0,0 +1,124 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createServer, type Server } from 'node:http';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { makeHttpClient } from '../src/client';
const dirs: string[] = [];
const servers: Server[] = [];
afterEach(async () => {
for (const server of servers.splice(0)) {
server.closeAllConnections();
await new Promise<void>((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
}
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function directory() {
const dir = mkdtempSync(join(tmpdir(), 'mcp-cancel-'));
dirs.push(dir);
return dir;
}
describe('ordinary HTTP cancellation', () => {
it.each([false, true])(
'aborts the actual HTTP request (headers received: %s)',
async (sendHeaders) => {
const started = Promise.withResolvers<void>();
const disconnected = Promise.withResolvers<void>();
let count = 0;
const server = createServer((_request, response) => {
count++;
response.on('close', () => disconnected.resolve());
if (sendHeaders) {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.write('{"status":');
}
started.resolve();
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('missing test server port');
}
const client = makeHttpClient({
endpoint: `http://127.0.0.1:${address.port}`,
streamDir: directory(),
timeoutMs: 5000,
});
const controller = new AbortController();
const outcome = client
.call('get_status', {}, { signal: controller.signal })
.catch((error) => error);
await started.promise;
controller.abort(new Error('caller cancelled'));
expect(await outcome).toMatchObject({ kind: 'cancelled' });
await disconnected.promise;
expect(count).toBe(1);
},
);
it('does not issue an HTTP request when already cancelled', async () => {
const fetcher = vi.fn<typeof fetch>();
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir: directory(),
fetch: fetcher,
});
await expect(
client.call('get_status', {}, { signal: AbortSignal.abort() }),
).rejects.toMatchObject({ kind: 'cancelled' });
expect(fetcher).not.toHaveBeenCalled();
});
it('retains the ordinary timeout and exposes its cause', async () => {
const fetcher: typeof fetch = vi.fn(
async (_input, init) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), {
once: true,
});
}),
);
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir: directory(),
fetch: fetcher,
timeoutMs: 20,
});
await expect(client.call('get_status', {})).rejects.toMatchObject({ kind: 'timeout' });
expect(fetcher).toHaveBeenCalledTimes(1);
});
it('reports resolved limits and paths without endpoint credentials', () => {
const dir = directory();
const client = makeHttpClient({
endpoint: 'https://user:secret@example.invalid/path?token=secret',
accessToken: 'secret',
streamDir: dir,
uploadRoot: dir,
maxStreamBytes: 123,
timeoutMs: 456,
});
expect(client.info).toMatchObject({
timeout_ms: 456,
max_stream_bytes: 123,
download_quota_bytes: 246,
max_active_streams: 4,
upload_enabled: true,
});
expect(client.info?.upload_root).toBe(client.info?.download_directory);
expect(JSON.stringify(client.info)).not.toMatch(/secret|example\.invalid/);
});
});
+154 -6
View File
@@ -3,7 +3,12 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { makeHttpClient, parseMaxStreamBytes, parseTimeoutMs } from '../src/client';
import {
makeHttpClient,
parseMaxStreamBytes,
parseTimeoutMs,
type TransferProgress,
} from '../src/client';
const tempDirs: string[] = [];
@@ -169,7 +174,17 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
)) as unknown as typeof fetch;
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch });
const result = await client.callStream('test_download_stream', {});
const progress: TransferProgress[] = [];
const result = await client.callStream(
'test_download_stream',
{},
{
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(progress.map((update) => update.progress)).toEqual([1, 2]);
expect(result).toEqual({ frame_count: 2, frames: [frames[0]], terminal: frames[1] });
});
@@ -225,7 +240,18 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
streamDir,
});
const result = await client.callStream('download_file_stream', { file: 'remote-id' });
const progress: TransferProgress[] = [];
const result = await client.callStream(
'download_file_stream',
{ file: 'remote-id' },
{
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(progress.map((update) => update.progress)).toEqual([0, 997, content.length]);
expect(progress.every((update) => update.total === content.length)).toBe(true);
expect(Object.keys(result).sort()).toEqual([
'file_path',
@@ -632,11 +658,19 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
uploadRoot: root,
});
const progress: TransferProgress[] = [];
const result = await client.callStream(
'upload_file_stream',
{ file_retention: 0 },
{ inputFile },
{
inputFile,
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(progress.map((update) => update.progress)).toEqual([0, 512 * 1024, content.length]);
expect(progress.every((update) => update.total === content.length)).toBe(true);
expect(requests).toHaveLength(3);
expect(requests.every((request) => request.action === 'upload_file_stream')).toBe(true);
@@ -789,7 +823,21 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
uploadRoot: root,
});
const result = await client.callStream('upload_file_stream', {}, { inputFile });
const progress: TransferProgress[] = [];
const result = await client.callStream(
'upload_file_stream',
{},
{
inputFile,
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(
progress.every((update) => update.progress === 0 && update.total === undefined),
).toBe(true);
expect(progress).toHaveLength(2);
expect(requests).toHaveLength(2);
expect(requests[0].params).toMatchObject({
@@ -941,10 +989,110 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
streamDir,
});
const result = await client.callStream('download_file_stream', {});
const progress: TransferProgress[] = [];
const result = await client.callStream(
'download_file_stream',
{},
{
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(result.file_size).toBe(content.length);
expect(fs.readFileSync(result.file_path).equals(content)).toBe(true);
expect(progress.map((update) => update.progress)).toEqual([0, content.length]);
expect(progress.every((update) => update.total === undefined)).toBe(true);
});
it('cleans partial downloads and releases admission when progress delivery fails', async () => {
const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-progress-'));
tempDirs.push(streamDir);
const frame = {
status: 'ok',
retcode: 0,
data: { type: 'stream', data_type: 'file_info', file_name: 'test.bin', file_size: 3 },
};
const fakeFetch: typeof fetch = async () =>
new Response(`${JSON.stringify(frame)}\r\n\r\n`);
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir,
maxStreamBytes: 3,
fetch: fakeFetch,
});
for (let attempt = 0; attempt < 5; attempt++) {
await expect(
client.callStream(
'download_file_stream',
{},
{
onProgress: async () => {
throw new Error('notification failed');
},
},
),
).rejects.toThrow('notification failed');
expect(fs.readdirSync(streamDir)).toEqual([]);
}
});
it('stops processing already-buffered frames after a cancellation during progress', async () => {
const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-progress-'));
tempDirs.push(streamDir);
const frames = [
{
status: 'ok',
retcode: 0,
data: {
type: 'stream',
data_type: 'file_info',
file_name: 'test.bin',
file_size: 1,
},
},
{
status: 'ok',
retcode: 0,
data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 1, data: 'eA==' },
},
{
status: 'ok',
retcode: 0,
data: {
type: 'response',
data_type: 'file_complete',
total_bytes: 1,
total_chunks: 1,
},
},
];
const controller = new AbortController();
const fakeFetch: typeof fetch = async () =>
new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''));
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir,
fetch: fakeFetch,
});
const updates: number[] = [];
await expect(
client.callStream(
'download_file_stream',
{},
{
signal: controller.signal,
onProgress: async (update) => {
updates.push(update.progress);
controller.abort();
},
},
),
).rejects.toThrow(/cancelled/);
expect(updates).toEqual([0]);
expect(fs.readdirSync(streamDir)).toEqual([]);
});
it('requires file_info as the first successful frame for known file-download actions', async () => {
+585
View File
@@ -0,0 +1,585 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import { createMcpHandler, Server, type ClientCapabilities } from '@modelcontextprotocol/server';
import { Client as LegacyClient } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import {
createInputCompletion,
inputCompletionBaseTool,
inputCompletionTools,
isInputCompletionTool,
} from '../src/elicitation';
import { asError, asText } from '../src/results';
import { computeTools, prepareActionCall, type Mode } from '../src/tools';
import type { ActionClient } from '../src/client';
import { createMcpServer } from '../src/server-factory';
const cleanup: Array<() => void | Promise<void>> = [];
const completeCapabilities: ClientCapabilities = { elicitation: { form: {} } };
const ORIGINAL = { action: 'send_private_msg', params: { message: 'private original message' } };
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
vi.useRealTimers();
vi.restoreAllMocks();
});
function harness(options: Parameters<typeof createInputCompletion>[0] = {}, mode: Mode = 'write') {
const completion = createInputCompletion(options);
const execute = vi.fn(async (args: Record<string, unknown>) => asText(args.params));
const client: ActionClient = {
call: vi.fn(async () => ({ status: 'ok', retcode: 0 })),
callStream: vi.fn(async () => ({
frame_count: 1,
frames: [],
terminal: { status: 'ok', retcode: 0 },
})),
};
const preflight = vi.fn((args: Record<string, unknown>, kind: 'read' | 'write') => {
const result = prepareActionCall(args, { mode, client }, kind);
return 'structuredContent' in result
? result
: {
action: result.action,
params: result.params,
inputSchema: result.inputSchema,
};
});
const factory = () => {
const server = new Server(
{ name: 'input-test', version: '1' },
{
capabilities: { tools: {} },
requestState: { verify: completion.verifyRequestState },
},
);
server.setRequestHandler('tools/list', async () => ({
tools: inputCompletionTools(computeTools('write')),
}));
server.setRequestHandler('tools/call', (request, context) => {
if (!isInputCompletionTool(request.params.name)) {
return asError('unknown tool');
}
const name = request.params.name;
return completion.handle(name, request.params.arguments ?? {}, context, {
capabilities:
context.mcpReq.envelope?.['io.modelcontextprotocol/clientCapabilities'] ??
server.getClientCapabilities(),
preflight: (args) =>
preflight(
args,
inputCompletionBaseTool(name) === 'query_action' ? 'read' : 'write',
),
execute,
});
});
return server;
};
const handler = createMcpHandler(factory);
cleanup.push(
() => completion.close(),
() => handler.close(),
);
async function raw(
arguments_: Record<string, unknown> = ORIGINAL,
retry: Record<string, unknown> = {},
capabilities: ClientCapabilities = completeCapabilities,
name = 'invoke_action_with_input',
token?: string,
) {
const response = await handler.fetch(
new Request('http://input.invalid/mcp', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
'Mcp-Method': 'tools/call',
'Mcp-Name': name,
'Mcp-Protocol-Version': '2026-07-28',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name,
arguments: arguments_,
...retry,
_meta: {
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
'io.modelcontextprotocol/clientCapabilities': capabilities,
'io.modelcontextprotocol/clientInfo': {
name: 'input-test',
version: '1',
},
},
},
}),
}),
token ? { authInfo: { token, clientId: 'test-app', scopes: [] } } : undefined,
);
return response.json();
}
return { completion, handler, factory, execute, preflight, raw };
}
function answer(requestState: string, content: unknown = { params_json: '{"user_id":123}' }) {
return { requestState, inputResponses: { missing_parameters: { action: 'accept', content } } };
}
describe('optional action input completion', () => {
it('integrates with the production factory and preserves the original action result contract', async () => {
const completion = createInputCompletion();
const onebot: ActionClient = {
call: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { message_id: -42 } })),
callStream: vi.fn(),
};
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
const handler = createMcpHandler(() =>
createMcpServer({ mode: 'write', client: onebot, inputCompletion: completion }),
);
const client = new Client(
{ name: 'production-input-test', version: '1' },
{
capabilities: completeCapabilities,
versionNegotiation: { mode: { pin: '2026-07-28' } },
},
);
client.setRequestHandler('elicitation/create', async () => {
expect(onebot.call).not.toHaveBeenCalled();
return { action: 'accept', content: { params_json: '{"user_id":123}' } };
});
cleanup.push(
() => completion.close(),
() => handler.close(),
() => client.close(),
);
await client.connect(
new StreamableHTTPClientTransport(new URL('http://input.invalid/mcp'), {
fetch: (input, init) => handler.fetch(new Request(input, init)),
}),
);
const result = await client.callTool({
name: 'invoke_action_with_input',
arguments: ORIGINAL,
});
expect(result.structuredContent).toEqual({
result: { status: 'ok', retcode: 0, data: { message_id: -42 } },
diagnostics: { outcome: 'success' },
});
expect(onebot.call).toHaveBeenCalledExactlyOnceWith(
'send_private_msg',
{ user_id: 123, message: ORIGINAL.params.message },
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
expect(JSON.stringify(log.mock.calls)).not.toContain(ORIGINAL.params.message);
expect(log.mock.calls.map(([, value]) => JSON.parse(String(value)).event)).toEqual([
'call_started',
'call_input_required',
'call_started',
'call_finished',
]);
});
it.each(['docs', 'read'] as const)(
'keeps the production factory mode gate before input collection in %s mode',
async (mode) => {
const onebot: ActionClient = { call: vi.fn(), callStream: vi.fn() };
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
const handler = createMcpHandler(() => createMcpServer({ mode, client: onebot }));
const client = new Client(
{ name: 'permission-input-test', version: '1' },
{
capabilities: completeCapabilities,
versionNegotiation: { mode: { pin: '2026-07-28' } },
},
);
const ask = vi.fn(async () => ({
action: 'accept' as const,
content: { params_json: '{"user_id":123}' },
}));
client.setRequestHandler('elicitation/create', ask);
cleanup.push(
() => handler.close(),
() => client.close(),
);
await client.connect(
new StreamableHTTPClientTransport(new URL('http://input.invalid/mcp'), {
fetch: (input, init) => handler.fetch(new Request(input, init)),
}),
);
const result = await client.callTool({
name: 'invoke_action_with_input',
arguments: ORIGINAL,
});
expect(result.structuredContent).toMatchObject({ diagnostics: { kind: 'permission' } });
expect(ask).not.toHaveBeenCalled();
expect(onebot.call).not.toHaveBeenCalled();
expect(log.mock.calls.map(([, value]) => JSON.parse(String(value)).event)).toEqual([
'call_started',
'call_finished',
]);
},
);
it('inherits tool visibility and existing schemas without altering the original list', () => {
expect(inputCompletionTools(computeTools('docs'))).toEqual([]);
expect(inputCompletionTools(computeTools('read')).map((tool) => tool.name)).toEqual([
'query_action_with_input',
]);
const tools = computeTools('write');
expect(inputCompletionTools(tools).map((tool) => tool.name)).toEqual([
'query_action_with_input',
'invoke_action_with_input',
]);
expect(tools.some((tool) => tool.name.endsWith('_with_input'))).toBe(false);
expect(inputCompletionTools(tools)[1].inputSchema).toEqual(
tools.find((tool) => tool.name === 'invoke_action')?.inputSchema,
);
});
it('asks before executing, never discloses existing values, and merges only validated missing fields', async () => {
const { raw, execute } = harness();
const first = await raw();
expect(first.result.resultType).toBe('input_required');
expect(execute).not.toHaveBeenCalled();
expect(first.result.inputRequests.missing_parameters).toMatchObject({
method: 'elicitation/create',
});
expect(JSON.stringify(first)).not.toContain(ORIGINAL.params.message);
const decodedToken = Buffer.from(
first.result.requestState.split('.')[1],
'base64url',
).toString();
expect(decodedToken).not.toContain(ORIGINAL.params.message);
const result = await raw(ORIGINAL, answer(first.result.requestState));
expect(result.result).toMatchObject({
resultType: 'complete',
structuredContent: { result: { user_id: 123, message: ORIGINAL.params.message } },
});
expect(execute).toHaveBeenCalledExactlyOnceWith({
action: ORIGINAL.action,
params: { ...ORIGINAL.params, user_id: 123 },
});
});
it('executes complete arguments without requiring elicitation capability or prompting', async () => {
const { raw, execute } = harness();
const result = await raw({ action: 'get_msg', params: { message_id: -123 } }, {}, {});
expect(result.result.structuredContent.result).toEqual({ message_id: -123 });
expect(execute).toHaveBeenCalledOnce();
});
it('honors permission failure before asking for input or executing', async () => {
const { raw, execute, preflight } = harness();
preflight.mockReturnValue(asError('write mode required', 'permission'));
const result = await raw();
expect(result.result.structuredContent.diagnostics.kind).toBe('permission');
expect(result.result.inputRequests).toBeUndefined();
expect(execute).not.toHaveBeenCalled();
});
it.each(['docs', 'read'] as const)(
'enforces actual write permission in %s mode',
async (mode) => {
const { raw, execute } = harness({}, mode);
const result = await raw();
expect(result.result.structuredContent.diagnostics.kind).toBe('permission');
expect(result.result.inputRequests).toBeUndefined();
expect(execute).not.toHaveBeenCalled();
},
);
it('does not turn a write action into a read action through the input helper', async () => {
const { raw, execute } = harness();
const result = await raw(ORIGINAL, {}, completeCapabilities, 'query_action_with_input');
expect(result.result.structuredContent.diagnostics.kind).toBe('permission');
expect(result.result.inputRequests).toBeUndefined();
expect(execute).not.toHaveBeenCalled();
});
it('fails visibly when the client has no form capability', async () => {
const { raw, execute } = harness();
for (const capabilities of [{}, { elicitation: { url: {} } }]) {
const result = await raw(ORIGINAL, {}, capabilities);
expect(result.result.structuredContent.diagnostics.kind).toBe('configuration');
}
expect(execute).not.toHaveBeenCalled();
});
it.each(['decline', 'cancel'])(
'stops on %s instead of repeatedly prompting',
async (action) => {
const { raw, execute } = harness();
const first = await raw();
const result = await raw(ORIGINAL, {
requestState: first.result.requestState,
inputResponses: { missing_parameters: { action } },
});
expect(result.result.structuredContent.diagnostics.kind).toBe('cancelled');
expect(result.result.inputRequests).toBeUndefined();
expect(execute).not.toHaveBeenCalled();
},
);
it.each([
{ params_json: '{' },
{ params_json: '{}' },
{ params_json: '{"user_id":0}' },
{ params_json: '{"user_id":"123"}' },
{ params_json: '{"user_id":123,"message":"replacement"}' },
{ params_json: '{"user_id":123,"auto_escape":true}' },
{ params_json: '[]' },
{ params_json: '{"user_id":123}', unexpected: 'value' },
])('rejects invalid or extraneous answers without executing: %j', async (content) => {
const { raw, execute } = harness();
const first = await raw();
const result = await raw(ORIGINAL, answer(first.result.requestState, content));
expect(result.result.isError).toBe(true);
expect(execute).not.toHaveBeenCalled();
});
it('accepts complex missing message data without guessing or normalizing it', async () => {
const { raw, execute } = harness();
const args = { action: 'send_private_msg', params: { user_id: 123 } };
const message = [
{ type: 'reply', data: { id: -42 } },
{ type: 'text', data: { text: 'hello' } },
];
const first = await raw(args);
await raw(
args,
answer(first.result.requestState, { params_json: JSON.stringify({ message }) }),
);
expect(execute).toHaveBeenCalledExactlyOnceWith({
action: args.action,
params: { user_id: 123, message },
});
});
it('rejects tampered, mismatched and state-less retries', async () => {
const { raw, execute } = harness();
const first = await raw();
const tampered = await raw(ORIGINAL, answer(`${first.result.requestState}x`));
expect(tampered.error.code).toBe(-32602);
const changed = await raw(
{ ...ORIGINAL, params: { message: 'different message' } },
answer(first.result.requestState),
);
expect(changed.result.isError).toBe(true);
const crossed = await raw(
ORIGINAL,
answer(first.result.requestState),
completeCapabilities,
'query_action_with_input',
);
expect(crossed.result.isError).toBe(true);
const noState = await raw(ORIGINAL, { inputResponses: answer('').inputResponses });
expect(noState.result.isError).toBe(true);
expect(execute).not.toHaveBeenCalled();
});
it('binds retries to the validated caller, including users sharing the same OAuth client', async () => {
const { raw, execute } = harness();
const first = await raw(
ORIGINAL,
{},
completeCapabilities,
'invoke_action_with_input',
'user-a-token',
);
const result = await raw(
ORIGINAL,
answer(first.result.requestState),
completeCapabilities,
'invoke_action_with_input',
'user-b-token',
);
expect(result.error.code).toBe(-32602);
expect(execute).not.toHaveBeenCalled();
});
it('allows exactly one concurrent completion and refuses later replay', async () => {
const { raw, execute } = harness();
const first = await raw();
const results = await Promise.all([
raw(ORIGINAL, answer(first.result.requestState)),
raw(ORIGINAL, answer(first.result.requestState)),
]);
expect(execute).toHaveBeenCalledOnce();
expect(results.filter((result) => result.result.isError)).toHaveLength(1);
expect((await raw(ORIGINAL, answer(first.result.requestState))).result.isError).toBe(true);
expect(execute).toHaveBeenCalledOnce();
});
it('expires pending input and bounds outstanding prompts without evicting live ones', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const { raw, execute } = harness({ ttlSeconds: 1, maxPending: 1 });
const first = await raw();
expect((await raw()).result.structuredContent.diagnostics.kind).toBe('execution');
vi.setSystemTime(Date.now() + 2_000);
expect((await raw(ORIGINAL, answer(first.result.requestState))).error.code).toBe(-32602);
expect((await raw()).result.resultType).toBe('input_required');
expect(execute).not.toHaveBeenCalled();
});
it('does not resume an unfinished prompt after closing the runtime', async () => {
const { raw, execute, completion } = harness();
const first = await raw();
completion.close();
expect((await raw(ORIGINAL, answer(first.result.requestState))).error.code).toBe(-32602);
expect(execute).not.toHaveBeenCalled();
});
it('lets a modern client drive the standard MRTR cycle', async () => {
const { handler, execute } = harness();
const client = new Client(
{ name: 'modern-input-test', version: '1' },
{
capabilities: completeCapabilities,
versionNegotiation: { mode: { pin: '2026-07-28' } },
},
);
client.setRequestHandler('elicitation/create', async () => ({
action: 'accept',
content: { params_json: '{"user_id":123}' },
}));
cleanup.push(() => client.close());
await client.connect(
new StreamableHTTPClientTransport(new URL('http://input.invalid/mcp'), {
fetch: (input, init) => handler.fetch(new Request(input, init)),
}),
);
const result = await client.callTool({
name: 'invoke_action_with_input',
arguments: ORIGINAL,
});
expect(result.structuredContent).toMatchObject({
result: { user_id: 123, message: ORIGINAL.params.message },
});
expect(execute).toHaveBeenCalledOnce();
});
it('does not execute when the caller aborts while the input form is open', async () => {
const { handler, execute } = harness();
const entered = Promise.withResolvers<void>();
const inputAborted = Promise.withResolvers<void>();
const client = new Client(
{ name: 'cancel-input-test', version: '1' },
{
capabilities: completeCapabilities,
versionNegotiation: { mode: { pin: '2026-07-28' } },
},
);
client.setRequestHandler('elicitation/create', async (_request, context) => {
context.mcpReq.signal.addEventListener('abort', () => inputAborted.resolve(), {
once: true,
});
entered.resolve();
await inputAborted.promise;
return { action: 'cancel' };
});
cleanup.push(() => client.close());
await client.connect(
new StreamableHTTPClientTransport(new URL('http://input.invalid/mcp'), {
fetch: (input, init) => handler.fetch(new Request(input, init)),
}),
);
const controller = new AbortController();
const result = client
.callTool(
{ name: 'invoke_action_with_input', arguments: ORIGINAL },
{ signal: controller.signal },
)
.catch((error: unknown) => error);
await entered.promise;
controller.abort(new Error('cancel test'));
await inputAborted.promise;
expect(await result).toBeInstanceOf(Error);
expect(execute).not.toHaveBeenCalled();
});
it('integrates the production factory through the legacy elicitation shim', async () => {
const onebot: ActionClient = {
call: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { message_id: -42 } })),
callStream: vi.fn(),
};
vi.spyOn(console, 'error').mockImplementation(() => {});
const server = createMcpServer({ mode: 'write', client: onebot });
const client = new LegacyClient(
{ name: 'legacy-input-test', version: '1' },
{ capabilities: { elicitation: {} } },
);
client.setRequestHandler(ElicitRequestSchema, async () => {
expect(onebot.call).not.toHaveBeenCalled();
return { action: 'accept', content: { params_json: '{"user_id":123}' } };
});
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
cleanup.push(
() => server.close(),
() => client.close(),
);
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: 'invoke_action_with_input',
arguments: ORIGINAL,
});
expect(result.structuredContent).toMatchObject({
result: { status: 'ok', retcode: 0, data: { message_id: -42 } },
});
expect(result.resultType).toBeUndefined();
expect(onebot.call).toHaveBeenCalledExactlyOnceWith(
'send_private_msg',
{ user_id: 123, message: ORIGINAL.params.message },
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
});
it('keeps automatic local uploads complete without asking for runtime-owned transfer fields', async () => {
const streamResult = {
frame_count: 1,
frames: [],
terminal: { status: 'ok', retcode: 0, data: { file: 'uploaded-file' } },
};
const onebot: ActionClient = { call: vi.fn(), callStream: vi.fn(async () => streamResult) };
vi.spyOn(console, 'error').mockImplementation(() => {});
const server = createMcpServer({ mode: 'write', client: onebot });
const client = new LegacyClient({ name: 'auto-upload-input-test', version: '1' });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
cleanup.push(
() => server.close(),
() => client.close(),
);
await server.connect(serverTransport);
await client.connect(clientTransport);
const args = {
action: 'upload_file_stream',
execution: { input_file: '/fixture/media.bin' },
};
const original = await client.callTool({ name: 'invoke_action', arguments: args });
const extended = await client.callTool({
name: 'invoke_action_with_input',
arguments: args,
});
expect(extended.structuredContent).toEqual(original.structuredContent);
expect(extended.isError).toBeUndefined();
expect(onebot.callStream).toHaveBeenCalledTimes(2);
expect(onebot.callStream).toHaveBeenLastCalledWith(
'upload_file_stream',
{},
expect.objectContaining({ inputFile: args.execution.input_file }),
);
});
});
+474
View File
@@ -0,0 +1,474 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { App } from '@modelcontextprotocol/ext-apps';
import { AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';
import { InMemoryTransport } from '@modelcontextprotocol/client';
import { Client as LegacyClient } from '@modelcontextprotocol/sdk/client/index.js';
import { createMcpHandler } from '@modelcontextprotocol/server';
import { createMcpServer } from '../src/server-factory.js';
import type { ActionClient } from '../src/client.js';
import type { Mode } from '../src/tools.js';
import {
MESSAGE_APP_MIME_TYPE,
MESSAGE_APP_URI,
messageAppResources,
messagePreviewTool,
previewMessage,
readMessageAppResource,
supportsMessageApp,
} from '../src/message-app.js';
import { mountMessagePreview, type PreviewApp } from '../apps/preview-view.js';
import { buildMessageApp } from '../scripts/build-message-app.mjs';
const temporary: string[] = [];
const close: Array<() => Promise<void>> = [];
afterEach(async () => {
for (const cleanup of close.splice(0).reverse()) {
await cleanup();
}
await Promise.all(
temporary.splice(0).map((path) => rm(path, { recursive: true, force: true })),
);
});
const draft = { message_type: 'group', target_id: 12345, text: '你好' };
function fakeOneBot(): ActionClient {
return {
call: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { message_id: -42 } })),
callStream: vi.fn(async () => ({
frame_count: 0,
frames: [],
terminal: { status: 'ok', retcode: 0 },
})),
};
}
const appCapabilities = {
extensions: { 'io.modelcontextprotocol/ui': { mimeTypes: [MESSAGE_APP_MIME_TYPE] } },
};
describe('message preview server integration', () => {
it.each(['docs', 'read', 'write'] as Mode[])(
'keeps legacy preview side-effect free and applies %s mode and negotiated UI capability',
async (mode) => {
for (const ui of [false, true]) {
const onebot = fakeOneBot();
const server = createMcpServer({ mode, client: onebot });
const client = new LegacyClient(
{ name: 'preview-legacy-test', version: '1.0.0' },
{ capabilities: ui ? appCapabilities : {} },
);
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
close.push(
() => server.close(),
() => client.close(),
);
await server.connect(serverTransport);
await client.connect(clientTransport);
const tools = await client.listTools();
const preview = tools.tools.find((tool) => tool.name === 'preview_message');
expect(preview).toBeDefined();
expect(preview?._meta).toEqual(
ui
? { ui: { resourceUri: MESSAGE_APP_URI, visibility: ['model', 'app'] } }
: undefined,
);
const resources = await client.listResources();
expect(
resources.resources.some((resource) => resource.uri === MESSAGE_APP_URI),
).toBe(ui);
const result = await client.callTool({ name: 'preview_message', arguments: draft });
expect(result.isError).toBeUndefined();
expect(result.structuredContent).toMatchObject({
result: { can_send: mode === 'write', draft },
});
expect(onebot.call).not.toHaveBeenCalled();
expect(onebot.callStream).not.toHaveBeenCalled();
if (mode !== 'write') {
expect(
await client.callTool({
name: 'invoke_action',
arguments: {
action: 'send_group_msg',
params: { group_id: 12345, message: '你好' },
},
}),
).toMatchObject({ isError: true });
expect(onebot.call).not.toHaveBeenCalled();
}
}
},
);
it('negotiates UI metadata independently for each modern request and never sends a preview', async () => {
const onebot = fakeOneBot();
const handler = createMcpHandler(() => createMcpServer({ mode: 'write', client: onebot }));
close.push(() => handler.close());
const request = async (method: string, params: Record<string, unknown>, ui: boolean) => {
const response = await handler.fetch(
new Request('http://mcp.invalid/mcp', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
'Mcp-Method': method,
'Mcp-Protocol-Version': '2026-07-28',
...(typeof params.name === 'string' ? { 'Mcp-Name': params.name } : {}),
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method,
params: {
...params,
_meta: {
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
'io.modelcontextprotocol/clientCapabilities': ui
? appCapabilities
: {},
'io.modelcontextprotocol/clientInfo': {
name: 'preview-modern-test',
version: '1.0.0',
},
},
},
}),
}),
);
expect(response.status).toBe(200);
return await response.json();
};
for (const ui of [true, false, true]) {
const tools = await request('tools/list', {}, ui);
expect(
tools.result.tools.find((tool: { name: string }) => tool.name === 'preview_message')
._meta,
).toEqual(
ui
? { ui: { resourceUri: MESSAGE_APP_URI, visibility: ['model', 'app'] } }
: undefined,
);
const resources = await request('resources/list', {}, ui);
expect(
resources.result.resources.some(
(resource: { uri: string }) => resource.uri === MESSAGE_APP_URI,
),
).toBe(ui);
expect(resources.result.cacheScope).toBe('private');
const preview = await request(
'tools/call',
{ name: 'preview_message', arguments: draft },
ui,
);
expect(preview.result.structuredContent).toMatchObject({
result: { can_send: true, draft },
});
}
expect(onebot.call).not.toHaveBeenCalled();
expect(onebot.callStream).not.toHaveBeenCalled();
});
});
describe('message preview tool', () => {
it('negotiates optional HTML support and retains text-only tool discovery', () => {
for (const capabilities of [
undefined,
{},
{ extensions: {} },
{ extensions: { 'io.modelcontextprotocol/ui': {} } },
]) {
expect(supportsMessageApp(capabilities)).toBe(false);
}
expect(
supportsMessageApp({
extensions: {
'io.modelcontextprotocol/ui': { mimeTypes: [MESSAGE_APP_MIME_TYPE] },
},
}),
).toBe(true);
expect(messagePreviewTool(false)._meta).toBeUndefined();
expect(messagePreviewTool(true)._meta).toEqual({
ui: { resourceUri: MESSAGE_APP_URI, visibility: ['model', 'app'] },
});
expect(messageAppResources(false)).toEqual([]);
expect(messageAppResources(true)).toEqual([
expect.objectContaining({ uri: MESSAGE_APP_URI, mimeType: MESSAGE_APP_MIME_TYPE }),
]);
});
it('returns a literal text draft and preserves negative quoted-message identifiers without executing', () => {
const result = previewMessage(
{ ...draft, text: '[CQ:at,qq=all]<script>bad()</script>', reply_to: -42 },
true,
);
expect(result.isError).toBeUndefined();
expect(result.structuredContent.result).toEqual({
draft: { ...draft, text: '[CQ:at,qq=all]<script>bad()</script>', reply_to: -42 },
can_send: true,
notice: '此为待发送草稿,尚未发送。',
invocation: {
name: 'invoke_action',
arguments: {
action: 'send_group_msg',
params: {
group_id: 12345,
message: [
{ type: 'reply', data: { id: '-42' } },
{
type: 'text',
data: { text: '[CQ:at,qq=all]<script>bad()</script>' },
},
],
},
},
},
});
expect(result.content).toEqual([
{ type: 'text', text: JSON.stringify(result.structuredContent.result, null, 2) },
]);
expect(
previewMessage({ ...draft, message_type: 'private' }, false).structuredContent.result,
).toMatchObject({
can_send: false,
invocation: { arguments: { action: 'send_private_msg', params: { user_id: 12345 } } },
});
});
it.each([
{ ...draft, message_type: 'other' },
{ ...draft, target_id: 0 },
{ ...draft, target_id: '12345' },
{ ...draft, target_id: Number.MAX_SAFE_INTEGER + 1 },
{ ...draft, text: ' \n' },
{ ...draft, reply_to: 0 },
{ ...draft, reply_to: 2147483648 },
{ ...draft, reply_to: -2147483649 },
{ ...draft, message: [] },
])('rejects an invalid draft without discarding fields: %j', (args) => {
expect(previewMessage(args, true)).toMatchObject({
isError: true,
structuredContent: { diagnostics: { kind: 'invalid_arguments' } },
});
});
it('does not hide a missing packaged panel', async () => {
await expect(readMessageAppResource('unrelated://resource')).resolves.toBeUndefined();
// Tests run from source; only an actual build supplies the sibling HTML.
await expect(readMessageAppResource(MESSAGE_APP_URI)).rejects.toMatchObject({
code: 'ENOENT',
});
});
it('builds a self-contained panel with exact CSP hashes and no external assets', async () => {
const directory = await mkdtemp(join(tmpdir(), 'snowluma-message-app-'));
temporary.push(directory);
const path = await buildMessageApp(directory);
const html = await readFile(path, 'utf8');
const script = html.match(/<script>([\s\S]*?)<\/script>/)?.[1];
const style = html.match(/<style>([\s\S]*?)<\/style>/)?.[1];
expect(script).toBeTruthy();
expect(style).toBeTruthy();
expect(html).toContain(
`script-src 'sha256-${createHash('sha256').update(script!).digest('base64')}'`,
);
expect(html).toContain(
`style-src 'sha256-${createHash('sha256').update(style!).digest('base64')}'`,
);
expect(html).toContain("connect-src 'none'");
expect(html).not.toMatch(/<(?:script|img|iframe)\b[^>]*\bsrc\s*=/i);
expect(html).not.toContain('unsafe-inline');
expect(html).not.toContain('unsafe-eval');
expect(html).toContain('ui/initialize');
expect(html).toContain('发送这条消息');
});
});
class TestElement {
textContent = '';
disabled = true;
private readonly listeners = new Map<string, () => void | Promise<void>>();
set innerHTML(_value: string) {
throw new Error('Untrusted markup must never be rendered');
}
addEventListener(type: string, callback: () => void | Promise<void>): void {
this.listeners.set(type, callback);
}
async click(): Promise<void> {
await this.listeners.get('click')?.();
}
}
async function panel(options: { writable?: boolean; hostTools?: boolean } = {}) {
const elements = Object.fromEntries(
['target', 'message', 'reply', 'status', 'send', 'cancel'].map((id) => [
id,
new TestElement(),
]),
);
const app: PreviewApp = {
ontoolresult: undefined,
ontoolcancelled: undefined,
onerror: undefined,
onclose: undefined,
connect: vi.fn(async () => {}),
getHostCapabilities: () => (options.hostTools === false ? {} : { serverTools: {} }),
callServerTool: vi.fn(async () => ({
content: [],
structuredContent: {
result: { status: 'ok', retcode: 0, data: { message_id: -42 } },
diagnostics: { outcome: 'success' },
},
})),
};
mountMessagePreview(app, {
getElementById: (id: string) => elements[id],
} as unknown as Document);
await Promise.resolve();
app.ontoolresult?.(previewMessage({ ...draft, reply_to: -42 }, options.writable !== false));
return { elements, app };
}
describe('message preview interaction', () => {
it('uses the official app handshake, tool-result notification and host-proxied send', async () => {
const app = new App(
{ name: 'preview-test', version: '1.0.0' },
{},
{ autoResize: false, strict: true },
);
const bridge = new AppBridge(
null,
{ name: 'isolated-host', version: '1.0.0' },
{ serverTools: {} },
);
bridge.oncalltool = vi.fn(async () => ({
content: [],
structuredContent: { result: { status: 'ok', retcode: 0, data: { message_id: -99 } } },
}));
const [appTransport, hostTransport] = InMemoryTransport.createLinkedPair();
close.push(
() => app.close(),
() => bridge.close(),
);
await bridge.connect(hostTransport);
const originalConnect = app.connect.bind(app);
let connected: Promise<void> | undefined;
vi.spyOn(app, 'connect').mockImplementation(() => {
connected = originalConnect(appTransport);
return connected;
});
const elements = Object.fromEntries(
['target', 'message', 'reply', 'status', 'send', 'cancel'].map((id) => [
id,
new TestElement(),
]),
);
mountMessagePreview(app, {
getElementById: (id: string) => elements[id],
} as unknown as Document);
await connected;
await bridge.sendToolInput({ arguments: draft });
await bridge.sendToolResult(previewMessage(draft, true));
await new Promise((resolve) => setImmediate(resolve));
expect(bridge.oncalltool).not.toHaveBeenCalled();
expect(elements.target.textContent).toBe('群聊 · 12345');
await elements.send.click();
expect(bridge.oncalltool).toHaveBeenCalledTimes(1);
expect(elements.status.textContent).toBe('服务端已接受消息。消息编号:-99');
});
it('renders untrusted text without markup and never sends on load or repeated results', async () => {
const { app, elements } = await panel();
app.ontoolresult?.(
previewMessage({ ...draft, text: '<img src=x onerror=alert(1)>' }, true),
);
expect(elements.message.textContent).toBe('<img src=x onerror=alert(1)>');
expect(app.callServerTool).not.toHaveBeenCalled();
expect(elements.send.disabled).toBe(false);
});
it('sends once only on click through the existing invocation and displays a signed result', async () => {
const { app, elements } = await panel();
await Promise.all([elements.send.click(), elements.send.click()]);
app.ontoolresult?.(previewMessage(draft, true));
await elements.send.click();
expect(app.callServerTool).toHaveBeenCalledExactlyOnceWith({
name: 'invoke_action',
arguments: {
action: 'send_group_msg',
params: {
group_id: 12345,
message: [
{ type: 'reply', data: { id: '-42' } },
{ type: 'text', data: { text: '你好' } },
],
},
},
});
expect(elements.status.textContent).toBe('服务端已接受消息。消息编号:-42');
expect(elements.send.disabled).toBe(true);
});
it.each([{ writable: false }, { hostTools: false }])(
'keeps unsupported or read-only panels non-sending: %j',
async (options) => {
const { app, elements } = await panel(options);
await elements.send.click();
expect(elements.send.disabled).toBe(true);
expect(app.callServerTool).not.toHaveBeenCalled();
},
);
it('cancels drafts locally and does not re-arm after another notification', async () => {
const { app, elements } = await panel();
await elements.cancel.click();
app.ontoolresult?.(previewMessage(draft, true));
await elements.send.click();
expect(app.callServerTool).not.toHaveBeenCalled();
expect(elements.status.textContent).toContain('未发送消息');
});
it('does not retry or claim success after a transport failure', async () => {
const { app, elements } = await panel();
vi.mocked(app.callServerTool).mockRejectedValueOnce(new Error('connection lost'));
await elements.send.click();
await elements.send.click();
expect(app.callServerTool).toHaveBeenCalledTimes(1);
expect(elements.status.textContent).toContain('尚未确认');
expect(elements.send.disabled).toBe(true);
});
it('recognizes business failures even when MCP isError is false', async () => {
const { app, elements } = await panel();
vi.mocked(app.callServerTool).mockResolvedValueOnce({
content: [],
structuredContent: {
result: { status: 'failed', retcode: 1400 },
diagnostics: { outcome: 'failed', message: '<b>拒绝</b>' },
},
});
await elements.send.click();
expect(elements.status.textContent).toContain('发送失败:<b>拒绝</b>');
expect(elements.send.disabled).toBe(true);
});
it('stops sending when the host disconnects', async () => {
const { app, elements } = await panel();
app.onclose?.();
await elements.send.click();
expect(app.callServerTool).not.toHaveBeenCalled();
expect(elements.status.textContent).toContain('连接已断开');
});
});
Loaded 100 of 423 files, more files were not shown because too many files have changed in this diff. Show more