Compare commits

..

11 Commits

Author SHA1 Message Date
MliKiowa
92a1a02dd3 Enhance bug report template for TRACE logs
Updated the bug report template to emphasize the need for original messages and complete Trace content.
2026-10-16 10:43:35 +08:00
DrSmoothl
87527cb764 chore(release): v1.14.22 2026-10-07 11:04:07 +08:00
DrSmoothl
44679bebd4 fix(protocol): keep the highway upload address
The session response address was discarded, so uploads used the default host.

Fixes #513
2026-10-06 15:20:24 +08:00
DrSmoothl
f95d247e73 feat(runtime): override deploy settings from the environment
SNOWLUMA_ variables can set the factory OneBot listen ports, WebUI TLS,
packet and hook timeouts, the stream directory, file download timeout,
and notification HTTP timeout. The values apply in memory and are not
written back to saved config.
2026-10-06 00:48:34 +08:00
DrSmoothl
c989c764e3 fix(onebot): allow a custom session release deadline
Operators can set SNOWLUMA_SESSION_RELEASE_DEADLINE_MS, in milliseconds.
The wait stays at 10 seconds when that variable is absent or not a positive integer.
2026-10-06 00:34:48 +08:00
DrSmoothl
940b823571 fix(onebot): bring an account back when shutdown stalls
If the previous OneBot session does not finish closing, the account now
comes back online instead of staying disconnected until QQ is restarted.

Fixes #509
2026-10-06 00:11:44 +08:00
DrSmoothl
e0801ff9eb feat(sdk): type the group category tag actions
The action map now includes get_group_tags, add_group_tag, and
delete_group_tag.

Refs #506
2026-10-05 23:51:18 +08:00
DrSmoothl
a71377ff17 feat(onebot): add actions for group category tags
get_group_tags lists the tags under one group category. add_group_tag
and delete_group_tag add or remove a tag by name. Callers pass the
category number as group_class. An empty name is rejected.

Refs #506
2026-10-05 23:51:18 +08:00
DrSmoothl
f0203823e9 feat(protocol): read and change group category tags
A group profile category can be listed, and a tag name can be added or
removed. An empty name is rejected instead of being dropped.

Refs #506
2026-10-05 23:51:10 +08:00
DrSmoothl
914e9a004f fix(video): update ffmpeg addon so group video sends stay up
Group video sends could exit the process with no error after the file was
staged. Refresh the bundled addon from the build that covers this case.

Fixes #507
2026-10-05 23:01:55 +08:00
DrSmoothl
f588f0345c docs(contributing): add guidance for coding agents
Document contributor expectations, validation steps, and manual issue submission requirements for AI-assisted contributions. Provide a shared project guide for coding agents.
2026-10-05 14:22:31 +08:00
65 changed files with 1617 additions and 42 deletions

View File

@@ -123,7 +123,7 @@ body:
attributes:
label: TRACE 日志 / 错误堆栈
description: |
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现,务必保留原始报文和完整Trace内容。
开启 TRACE 的两种方式(任选其一):
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。

104
AGENTS.md Normal file
View File

@@ -0,0 +1,104 @@
# Working on SnowLuma
SnowLuma translates QQ client sessions into OneBot v11 actions and events, with a WebUI, TypeScript SDK, and MCP server. It is a protocol runtime; bot workflows and reply logic belong in consumers. This guide is for contributors and their coding agents.
## Before making changes
- Read [CONTRIBUTING.md](CONTRIBUTING.md) for contribution requirements, [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community expectations, and [LICENSE](LICENSE) for contribution and redistribution terms.
- **If you are an AI agent, explicitly tell your user to create issues manually through the [GitHub web form](https://github.com/SnowLuma/SnowLuma/issues/new/choose). Issues created directly with a CLI will be automatically closed.** Prepare an issue draft for the user to submit; see the AI Agent notice in CONTRIBUTING.md.
- Check `git status` and preserve unrelated work. Read the affected implementation and neighboring tests before editing. Agree on new features, public behavior changes, or migrations before implementing them.
- Target PRs at `dev`. `main` is the release pointer. Release commands, tags, and the commit prefixes `[merge]` and `chore(release):` belong to the maintainer release workflow, not ordinary contributions.
## Repository map
This is a pnpm workspace. Package ownership matters more than directory names:
| Location | Responsibility |
| --- | --- |
| `packages/core` | Application entry, per-account Bridge orchestration, WebUI backend, notifications, release assembly |
| `packages/bridge` | QQ process discovery, Hook sessions, native transport lifecycle |
| `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers |
| `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters |
| `packages/common` | Shared logging, configuration and utilities without business dependencies |
| `packages/proto-defs` | Typed protocol schemas |
| `packages/proton` | Compile-time protobuf codecs and build integration |
| `packages/websocket` | WebSocket implementation and native binding integration |
| `packages/runtime` | Distribution manifest, launchers and supplied native artifacts |
| `packages/webui` | Vite/React management console; workspace name is `webui` |
| `packages/sdk` | Public TypeScript client |
| `packages/mcp` | MCP server and generated action catalog |
| `packages/ui` | Published UI component package |
| `tools`, `.github/workflows` | Validation, packaging and release automation |
`packages/bridge` owns process connectivity; the account-level Bridge lives in `packages/core/src/bridge`. Start at [the application entry](packages/core/src/index.ts) to follow their composition.
Read the relevant owner before changing a path:
| Change | Start here |
| --- | --- |
| Connection or account lifecycle | [Hook manager](packages/bridge/src/hook-manager.ts), [Bridge manager](packages/core/src/bridge/manager.ts), [OneBot instance](packages/onebot/src/instance.ts) |
| Incoming QQ events or identity | [Packet pipeline](packages/protocol/src/packet-pipeline.ts), [message decoders](packages/protocol/src/msg-push/index.ts), [identity service](packages/protocol/src/identity-service.ts) |
| OneBot actions or message segments | [Action definitions](packages/onebot/src/actions/index.ts), [validation helpers](packages/onebot/src/action-kit.ts), [event conversion](packages/onebot/src/event-converter/index.ts) |
| WebUI | [Interaction conventions](packages/webui/README.md), `packages/webui/src`, `packages/core/src/webui` |
| SDK or MCP | [SDK guide](packages/sdk/README.md), [SDK versioning](packages/sdk/VERSIONING.md), [MCP guide](packages/mcp/README.md) |
| Protocol codec generation | [Proton guide](packages/proton/README.md), the affected package's `vitest.config.ts` |
## Setup and validation
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.
Run commands from the repository root:
```sh
pnpm typecheck # all workspace packages with a typecheck script
pnpm lint
pnpm test # all workspace packages with a test script
pnpm run build:all # release inputs and published packages
pnpm test:core # Core only; not a substitute for workspace tests
pnpm --filter @snowluma/onebot test # example: tests for the affected package
pnpm --filter webui test # the frontend package has no @snowluma/ prefix
```
Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check.
- **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.
- **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.
- **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.
## 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.
- **Make errors observable.** Do not turn exceptions into empty results or successful responses. Preserve error context and use the shared logger for important transitions and failures. If evidence is insufficient, add targeted diagnostics and describe what remains unknown.
- **Preserve account isolation.** Identity, message storage and session state belong to their account. Keep teardown ordering and in-flight work handling intact when changing lifecycle code.
- **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.
- **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 two-space indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
- **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports.
## Generated files and related changes
OneBot action definitions own validation and catalog metadata. After changing an action name, parameter, result description or execution mode:
1. Update the owning definition in `packages/onebot/src/actions` and its tests.
2. Run `pnpm --filter @snowluma/mcp gen`.
3. Inspect and include the corresponding changes in `packages/mcp/src/generated/catalog.ts` and `catalog.json`. Do not hand-edit generated catalog entries.
4. Check affected SDK types and callers, run their relevant tests, and run workspace typechecking.
`pnpm test` also runs the MCP catalog generator and may change these tracked snapshots. CI's `node tools/check-action-catalog.mjs` rejects a working-tree catalog diff; it is a clean-checkout drift check, not the generator itself.
SDK breaking changes also update [CHANGELOG.md](packages/sdk/CHANGELOG.md) and [VERSIONING.md](packages/sdk/VERSIONING.md). WebUI changes follow its [interaction conventions](packages/webui/README.md). Keep user-facing documentation aligned with behavior.
Edit sources rather than `dist` outputs. Native artifacts in `packages/runtime/native` are supplied build inputs; do not substitute arbitrary local binaries to make a build pass. Packaging changes must preserve the checks in [Core's build configuration](packages/core/vite.config.ts) and [the release layout validator](tools/check-release-layout.mjs).
## Handoff and instruction maintenance
Report the behavior changed, the exact validation commands and results, and any unverified runtime or platform behavior. Keep public PR and commit text focused on the contribution; omit local environment details and private research. Use English Conventional Commit messages as described in CONTRIBUTING.md.
`AGENTS.md` is the canonical contributor guide; `CLAUDE.md` is a relative symlink to it. Edit this file once. When package ownership, validation commands or contribution policy changes, update the affected instructions in the same change. Link to checked-in sources and keep the guide usable from a fresh clone without maintainer-local notes, tools or absolute paths.

1
CLAUDE.md Symbolic link
View File

@@ -0,0 +1 @@
AGENTS.md

View File

@@ -19,6 +19,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
### AI Agent 贡献须知
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
---
## 项目结构速览

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.14.21",
"version": "1.14.22",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.14.21",
"version": "1.14.22",
"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).",
@@ -24,6 +24,10 @@
"types": "./src/hook-packet-client.ts",
"default": "./src/hook-packet-client.ts"
},
"./packet-timeout": {
"types": "./src/packet-timeout.ts",
"default": "./src/packet-timeout.ts"
},
"./injector": {
"types": "./src/injector.ts",
"default": "./src/injector.ts"

View File

@@ -1,4 +1,5 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { packetTimeoutMs } from './packet-timeout';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
@@ -16,7 +17,7 @@ export class HookPacketClient implements PacketSender {
private readonly onOutboundHealthChanged?: OutboundHealthListener,
) { }
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
}

View File

@@ -0,0 +1,8 @@
import { positiveIntEnv } from '@snowluma/common/env';
/** Default wait for a QQ reply when the caller does not pass one. */
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
}

View File

@@ -10,6 +10,7 @@ import { isRealUin } from '@snowluma/common/uin';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import path from 'path';
import { positiveIntEnv } from '@snowluma/common/env';
import { resolveHookRuntimeDir } from './hook-runtime-dir';
export const PIPE_MAGIC = 0x31504851;
@@ -471,7 +472,7 @@ export class QqHookClient extends EventEmitter {
private loginWaiters: Deferred<QqHookLoginState>[] = [];
constructor(pid: number, {
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
runtimeDir = resolveHookRuntimeDir(pid),
}: QqHookClientOptions = {}) {

View File

@@ -0,0 +1,30 @@
import { afterEach, describe, expect, it } from 'vitest';
import { QqHookClient } from '../src/qq-hook-client';
import { packetTimeoutMs } from '../src/packet-timeout';
const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
afterEach(() => {
delete process.env[PACKET];
delete process.env[ACK];
});
describe('packet and hook ack timeouts', () => {
it('keeps the 15 second packet default', () => {
expect(packetTimeoutMs({})).toBe(15_000);
});
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
});
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
process.env[ACK] = '1200';
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
expect(client.defaultAckTimeoutMs).toBe(1200);
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
expect(explicit.defaultAckTimeoutMs).toBe(50);
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.14.21",
"version": "1.14.22",
"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).",
@@ -20,6 +20,10 @@
"types": "./src/coerce.ts",
"default": "./src/coerce.ts"
},
"./env": {
"types": "./src/env.ts",
"default": "./src/env.ts"
},
"./single-flight-cache": {
"types": "./src/single-flight-cache.ts",
"default": "./src/single-flight-cache.ts"

View File

@@ -0,0 +1,28 @@
import { createLogger } from './logger';
const log = createLogger('Env');
/** Node's setTimeout delay is a signed 32-bit integer. */
const MAX_POSITIVE_INT = 2_147_483_647;
/** Read a positive integer environment variable.
*
* A blank value is absent and returns `fallback`. A present but unusable
* value is ignored, with a warning, and also returns `fallback`.
*/
export function positiveIntEnv(
name: string,
fallback: number,
options?: { max?: number; env?: NodeJS.ProcessEnv },
): number {
const max = options?.max ?? MAX_POSITIVE_INT;
const raw = (options?.env ?? process.env)[name];
if (typeof raw !== 'string' || !raw.trim()) return fallback;
const value = raw.trim();
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
if (!Number.isSafeInteger(parsed) || parsed > max) {
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
return fallback;
}
return parsed;
}

View File

@@ -108,6 +108,9 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
);
if (logPerUin !== undefined) out.logPerUin = logPerUin;
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls };
return out;
}

View File

@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { positiveIntEnv } from '../src/env';
describe('positiveIntEnv', () => {
it('returns the fallback when the variable is absent or blank', () => {
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15);
});
it('reads a positive integer and honors the max', () => {
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500);
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
max: 65535,
env: { SNOWLUMA_TEST_INT: '80' },
})).toBe(80);
});
it('ignores zero, negatives, fractions, and values above the max', () => {
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
max: 65535,
env: { SNOWLUMA_TEST_INT: raw },
})).toBe(15);
}
});
});

View File

@@ -124,6 +124,17 @@ describe('resolveRuntimeEnvOverrides', () => {
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
});
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
webuiTls: { enabled: true },
});
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
webuiTls: { enabled: false },
});
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' }))
.toThrow(/SNOWLUMA_WEBUI_TLS/);
});
it('ignores an out-of-range / non-numeric port env', () => {
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.14.21",
"version": "1.14.22",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",

View File

@@ -31,6 +31,9 @@ import {
type GroupMemberPermission,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
import { AddGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/add-group-category-tag';
import { DeleteGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/delete-group-category-tag';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
import { OidbError } from '@snowluma/protocol/oidb-service';
@@ -117,6 +120,18 @@ export class GroupAdminApi {
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
}
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
}
addCategoryTag(groupClass: number, name: string): Promise<void> {
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
removeCategoryTag(groupClass: number, name: string): Promise<void> {
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,

View File

@@ -1,4 +1,5 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
import { createLogger } from '@snowluma/common/logger';
import type {
AlbumCreator,
@@ -179,7 +180,7 @@ export class GroupAlbumApi {
body.length,
);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
@@ -297,7 +298,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -359,7 +360,7 @@ export class GroupAlbumApi {
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, 15000);
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to comment on album media');
@@ -431,7 +432,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -470,7 +471,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -571,7 +572,7 @@ export class GroupAlbumApi {
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, 15000);
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to fetch album feed');
}

View File

@@ -4,6 +4,7 @@ import {
runWithTraceRequest,
} from '@snowluma/common/logger';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
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';
@@ -296,7 +297,7 @@ export class Bridge implements BridgeInterface {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
if (!this.packetClient_) {
return runWithTraceRequest(() => {
const startedAt = Date.now();

View File

@@ -8,6 +8,7 @@
// Side-effecting collaborators (config load, per-UIN channel ids, webhook POST,
// SMTP send, the clock) are injected so the class is fully unit-testable; the
// real wiring lives in `createNotificationManager()` at the bottom.
import { positiveIntEnv } from '@snowluma/common/env';
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager';
@@ -262,7 +263,9 @@ export class NotificationManager {
/** Default outbound POST: a single attempt with a timeout, JSON content-type
* (the common case for 钉钉/Discord/飞书). Never throws. */
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
export function createDefaultPost(
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
): NotificationManagerDeps['post'] {
return async (url, body, headers) => {
try {
const res = await fetch(url, {

View File

@@ -23,6 +23,11 @@ import type {
OidbSetAdmin,
OidbSpecialTitle,
} from '@snowluma/proto-defs/oidb-actions/base';
import type {
OidbChangeGroupCategoryTag,
OidbGetGroupCategoryTags,
OidbGetGroupCategoryTagsResp,
} from '@snowluma/proto-defs/oidb-actions/group-category-tag';
// Post-namespace migration: GroupAdminApi forwards through namespaces
// under @snowluma/protocol/oidb-services/group-admin. Tests assert
@@ -705,4 +710,54 @@ describe('apis/group-admin', () => {
remain_at_all_count_for_uin: 0,
});
});
it('lists category tags and keeps category 0 on the wire', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({
body: { tags: [{ id: 7, name: '学习', type: 1 }, { name: '未编号' }] },
}),
));
const out = await new GroupAdminApi(bridge as any).listCategoryTags(0);
expect(out).toEqual({
tags: [
{ id: 7, name: '学习', type: 1 },
{ id: 0, name: '未编号', type: 0 },
],
});
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x967c_0');
const env = protobuf_decode<OidbBase<OidbGetGroupCategoryTags>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(env.command).toBe(0x967C);
expect(env.body?.groupClass).toBe(0);
});
it('returns an empty tag list when the category has none', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({ body: {} }),
));
await expect(new GroupAdminApi(bridge as any).listCategoryTags(2)).resolves.toEqual({ tags: [] });
});
it('adds and removes a category tag by its name', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).addCategoryTag(3, ' 户外 ');
await new GroupAdminApi(bridge as any).removeCategoryTag(3, '户外');
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x967d_0',
'OidbSvcTrpcTcp.0x967e_0',
]);
const added = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(added.body).toMatchObject({ groupClass: 3, name: ' 户外 ' });
const removed = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(removed.body).toMatchObject({ groupClass: 3, name: '户外' });
});
it('refuses an empty tag name instead of sending it', async () => {
const bridge = mockBridge();
await expect(new GroupAdminApi(bridge as any).addCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
await expect(new GroupAdminApi(bridge as any).removeCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
});

View File

@@ -302,6 +302,27 @@ describe('fetchHighwaySession trace lifecycle', () => {
}
});
it('keeps a server address encoded as a fixed 32-bit field', async () => {
// Address field 2 is four raw bytes. The fixture is not produced by the
// schema encoder, so a varint declaration cannot hide itself.
const responseData = Buffer.from('8a50150a02aabb1201cc1a0c08011208150102030418903f', 'hex');
const bridge = {
identity: { uin: '10001' },
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
})),
} as unknown as BridgeContext;
const session = await fetchHighwaySession(bridge);
expect(session.host).toBe('1.2.3.4');
expect(session.port).toBe(8080);
});
it('records a thrown control request as one failed terminal', async () => {
const bridge = {
identity: { uin: '10001' },

View File

@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
NotificationManager,
createDefaultPost,
selectChannels,
type MailPayload,
type NotificationManagerDeps,
@@ -321,3 +322,28 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
expect(events).toEqual([]);
});
});
describe('createDefaultPost timeout', () => {
const name = 'SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS';
const saved = process.env[name];
afterEach(() => {
if (saved === undefined) delete process.env[name];
else process.env[name] = saved;
vi.unstubAllGlobals();
});
it('uses SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', async () => {
process.env[name] = '1234';
const seen: number[] = [];
const timeout = AbortSignal.timeout.bind(AbortSignal);
vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => {
seen.push(ms);
return timeout(50);
});
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200 })));
const post = createDefaultPost();
await post('http://127.0.0.1/hook', '{}');
expect(seen).toEqual([1234]);
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.14.21",
"version": "1.14.22",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",

View File

@@ -440,6 +440,54 @@
},
"category": "扩展"
},
{
"name": "add_group_tag",
"aliases": [],
"summary": "向某个群分类添加资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "bot_exit",
"aliases": [],
@@ -1422,6 +1470,54 @@
},
"category": "扩展"
},
{
"name": "delete_group_tag",
"aliases": [],
"summary": "从某个群分类移除资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "delete_msg",
"aliases": [],
@@ -6107,6 +6203,75 @@
},
"category": "群信息"
},
{
"name": "get_group_tags",
"aliases": [],
"summary": "读取某个群分类下的资料标签",
"returns": "该分类下的资料标签列表。",
"returnsSchema": {
"type": "object",
"properties": {
"tags": {
"type": "array",
"description": "资料标签",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "标签编号"
},
"name": {
"type": "string",
"description": "标签名"
},
"type": {
"type": "integer",
"description": "标签类型"
}
},
"required": [
"id",
"name",
"type"
]
}
}
},
"required": [
"tags"
]
},
"readOnly": true,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
"required": [
"group_class"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "get_group_todo_list",
"aliases": [],
@@ -13154,7 +13319,7 @@
},
{
"category": "群管理",
"count": 18
"count": 21
},
{
"category": "群文件",

View File

@@ -443,6 +443,54 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "扩展"
},
{
"name": "add_group_tag",
"aliases": [],
"summary": "向某个群分类添加资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "bot_exit",
"aliases": [],
@@ -1425,6 +1473,54 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "扩展"
},
{
"name": "delete_group_tag",
"aliases": [],
"summary": "从某个群分类移除资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "delete_msg",
"aliases": [],
@@ -6110,6 +6206,75 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "群信息"
},
{
"name": "get_group_tags",
"aliases": [],
"summary": "读取某个群分类下的资料标签",
"returns": "该分类下的资料标签列表。",
"returnsSchema": {
"type": "object",
"properties": {
"tags": {
"type": "array",
"description": "资料标签",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "标签编号"
},
"name": {
"type": "string",
"description": "标签名"
},
"type": {
"type": "integer",
"description": "标签类型"
}
},
"required": [
"id",
"name",
"type"
]
}
}
},
"required": [
"tags"
]
},
"readOnly": true,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
"required": [
"group_class"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "get_group_todo_list",
"aliases": [],
@@ -13158,7 +13323,7 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "群管理",
"count": 18
"count": 21
},
{
"category": "群文件",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.14.21",
"version": "1.14.22",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",

View File

@@ -1,3 +1,4 @@
import { positiveIntEnv } from '@snowluma/common/env';
import { readFile } from 'node:fs/promises';
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
@@ -21,7 +22,11 @@ import { groupInfoReturnsSchema } from './group-info';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
const DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
function downloadFileTimeoutMs(): number {
return positiveIntEnv('SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS', DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS);
}
const profileLikeUserSchema = {
type: 'object',
@@ -2592,7 +2597,7 @@ export const actions = [
buf = Buffer.from(base64, 'base64');
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
} else {
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS);
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, downloadFileTimeoutMs());
}
try {
const safe = await saveDownloadBuffer(buf, name);

View File

@@ -166,6 +166,60 @@ export const actions = [
},
}),
defineAction({
name: 'get_group_tags',
summary: '读取某个群分类下的资料标签',
readOnly: true,
returns: '该分类下的资料标签列表。',
returnsSchema: {
type: 'object',
properties: {
tags: {
type: 'array',
description: '资料标签',
items: {
type: 'object',
properties: {
id: { type: 'integer', description: '标签编号' },
name: { type: 'string', description: '标签名' },
type: { type: 'integer', description: '标签类型' },
},
required: ['id', 'name', 'type'],
},
},
},
required: ['tags'],
},
params: { group_class: f.int({ min: 0, max: 0xFFFFFFFF }) },
run: async (p, ctx) => okResponse(await ctx.bridge.apis.groupAdmin.listCategoryTags(p.group_class)),
}),
defineAction({
name: 'add_group_tag',
summary: '向某个群分类添加资料标签',
params: {
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.addCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
defineAction({
name: 'delete_group_tag',
summary: '从某个群分类移除资料标签',
params: {
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.removeCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_admin',
summary: '设置/取消管理员',

View File

@@ -1,3 +1,4 @@
import { positiveIntEnv } from '@snowluma/common/env';
import { createLogger } from '@snowluma/common/logger';
import { isRealUin } from '@snowluma/common/uin';
import { randomBytes } from 'crypto';
@@ -110,7 +111,69 @@ export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions =
saveOneBotConfig(uin, config, { mode: globalRaw ? 'overlay' : 'snapshot' });
}
return config;
// Listen-port overrides stay in memory. Persisting them would bake a
// machine-specific port into onebot_<uin>.json.
return applyOneBotListenPortOverrides(config);
}
const HTTP_DEFAULT_SERVER = 'http-default';
const WS_DEFAULT_SERVER = 'ws-default';
/** Override only the factory listeners. Other adapters keep their saved ports. */
export function applyOneBotListenPortOverrides(
config: OneBotConfig,
env: NodeJS.ProcessEnv = process.env,
): OneBotConfig {
const httpPort = readListenPort('SNOWLUMA_ONEBOT_HTTP_PORT', env);
const wsPort = readListenPort('SNOWLUMA_ONEBOT_WS_PORT', env);
if (httpPort === undefined && wsPort === undefined) return config;
const next = structuredClone(config);
const httpApplied = httpPort !== undefined && assignFactoryPort(
next.networks.httpServers,
HTTP_DEFAULT_SERVER,
httpPort,
'SNOWLUMA_ONEBOT_HTTP_PORT',
);
const wsApplied = wsPort !== undefined && assignFactoryPort(
next.networks.wsServers,
WS_DEFAULT_SERVER,
wsPort,
'SNOWLUMA_ONEBOT_WS_PORT',
);
if (!httpApplied && !wsApplied) return config;
try {
assertValidOneBotConfig(next);
} catch (error) {
log.warn(
'OneBot listen port override ignored: %s',
error instanceof Error ? error.message : String(error),
);
return config;
}
return next;
}
function readListenPort(name: string, env: NodeJS.ProcessEnv): number | undefined {
const raw = env[name];
if (typeof raw !== 'string' || !raw.trim()) return undefined;
const port = positiveIntEnv(name, 0, { max: 65535, env });
return port > 0 ? port : undefined;
}
function assignFactoryPort(
servers: Array<{ name: string; port: number }>,
name: string,
port: number,
envName: string,
): boolean {
const server = servers.find((entry) => entry.name === name);
if (!server) {
log.warn('%s is ignored; no %s listener', envName, name);
return false;
}
server.port = port;
return true;
}
export interface SaveOneBotConfigOptions {

View File

@@ -273,6 +273,20 @@ export class OneBotInstance {
this.ctx.musicSignUrl = globalSettings.musicSignUrl;
}
/** Drop listeners and sockets without waiting for shutdown to finish.
* Used when dispose() does not settle and a replacement session must bind. */
forceRelease(): void {
try {
this.quiesce();
} catch (error) {
this.log.warn(
'quiesce during forced release failed: %s',
error instanceof Error ? error.message : String(error),
);
}
this.networkManager.forceRelease();
}
/** Synchronously stop every ingress seam for this instance generation.
*
* This operation is sticky and idempotent. It is intentionally separate

View File

@@ -43,7 +43,43 @@ export interface DatabaseMigrationTask {
cancel(): void;
}
/** A peer that never finishes a close handshake must not keep the next
* account session offline. Ten seconds covers a normal drain.
* SNOWLUMA_SESSION_RELEASE_DEADLINE_MS overrides the configured value. */
const DEFAULT_SESSION_RELEASE_DEADLINE_MS = 10_000;
const SESSION_RELEASE_DEADLINE_ENV = 'SNOWLUMA_SESSION_RELEASE_DEADLINE_MS';
const MAX_SESSION_RELEASE_DEADLINE_MS = 2_147_483_647;
/** Positive integer milliseconds, or `undefined` when the raw value is absent
* or not usable. Callers decide the fallback. */
export function parseSessionReleaseDeadlineMs(raw: string | undefined): number | undefined {
if (raw === undefined) return undefined;
const value = raw.trim();
if (!/^[1-9]\d*$/.test(value)) return undefined;
const parsed = Number(value);
if (!Number.isSafeInteger(parsed) || parsed > MAX_SESSION_RELEASE_DEADLINE_MS) return undefined;
return parsed;
}
/** Env wins over an explicit deadline. An unusable env value is ignored. */
export function resolveSessionReleaseDeadlineMs(configured?: number, envRaw?: string): number {
const fromEnv = parseSessionReleaseDeadlineMs(envRaw);
if (fromEnv !== undefined) return fromEnv;
if (
configured !== undefined
&& Number.isSafeInteger(configured)
&& configured > 0
&& configured <= MAX_SESSION_RELEASE_DEADLINE_MS
) {
return configured;
}
return DEFAULT_SESSION_RELEASE_DEADLINE_MS;
}
export interface OneBotManagerOptions {
/** How long a retiring instance may block the replacement session.
* SNOWLUMA_SESSION_RELEASE_DEADLINE_MS overrides this when it is set. */
sessionReleaseDeadlineMs?: number;
createDatabaseMigrationTask?: (uin: string) => DatabaseMigrationTask;
createInstance?: (
uin: string,
@@ -91,8 +127,21 @@ export class OneBotManager {
private readonly createInstance: NonNullable<OneBotManagerOptions['createInstance']>;
private disposePromise: Promise<void> | null = null;
private disposed = false;
private readonly sessionReleaseDeadlineMs: number;
constructor(options: OneBotManagerOptions = {}) {
const envRaw = process.env[SESSION_RELEASE_DEADLINE_ENV];
if (envRaw !== undefined && envRaw.trim() && parseSessionReleaseDeadlineMs(envRaw) === undefined) {
log.warn(
'%s=%j is ignored; expected a positive integer number of milliseconds',
SESSION_RELEASE_DEADLINE_ENV,
envRaw,
);
}
this.sessionReleaseDeadlineMs = resolveSessionReleaseDeadlineMs(
options.sessionReleaseDeadlineMs,
envRaw,
);
this.createDatabaseMigrationTask = options.createDatabaseMigrationTask
?? createMessageStoreMigrationTask;
this.createInstance = options.createInstance
@@ -447,20 +496,58 @@ export class OneBotManager {
return result;
}
private async releaseRetiringInstance(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
instance: OneBotInstance,
): Promise<void> {
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs);
timer.unref?.();
});
// Map rejection here so a dispose() that fails after the deadline still
// has a handler. The race may already have moved on.
const releasing = instance.dispose().then(
() => 'released' as const,
(error: unknown) => ({ failed: error }),
);
try {
const outcome = await Promise.race([releasing, timeout]);
if (outcome === 'timeout') {
log.error(
'session release timed out; forcing adapters closed and starting the replacement: UIN=%s',
uin,
);
try {
instance.forceRelease?.();
} catch (error) {
log.error(
'forced session release failed: UIN=%s: %s',
uin,
error instanceof Error ? error.message : String(error),
);
}
return;
}
if (typeof outcome === 'object') {
// Do not leave this UIN permanently guarded by a failed handoff. A
// later session-start observation may retry the still-visible retire.
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
throw new InstanceLifecycleError(instance, outcome.failed);
}
} finally {
if (timer) clearTimeout(timer);
}
}
private async finishRetiringBeforeStart(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
retiring: OneBotInstance[],
): Promise<void> {
for (const instance of retiring) {
try {
await instance.dispose();
} catch (error) {
// Do not leave this UIN permanently guarded by a failed handoff. A
// later session-start observation may retry the still-visible retire.
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
throw new InstanceLifecycleError(instance, error);
}
await this.releaseRetiringInstance(uin, pending, instance);
this.retirementSucceeded(instance);
}
if (this.pendingStarts.get(uin) !== pending) return;

View File

@@ -61,6 +61,11 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
/** Drop sockets and listeners without waiting for a peer handshake.
* Graceful `close()` can sit forever on a half-open connection; shutdown
* uses this so the next account session can bind the same ports. */
forceClose(): void { /* adapters that own a listener override this */ }
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** Report live connection health for the WebUI dashboard. */

View File

@@ -25,6 +25,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
private server: Server | null = null;
private webSocketServer: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
@@ -113,6 +114,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
try {
await attempt;
} catch (error) {
if (this.releaseForced) return;
if (!httpReleased && server?.listening === true) {
// A failed HTTP close callback cannot prove the listener was released.
// The upgrade handler is still attached, so the old ingress can accept
@@ -128,6 +130,26 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
}
override forceClose(): void {
this.releaseForced = true;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.isEnabled = false;
this.listening = false;
this.webSocketConnections.terminateAll();
const webSocketServer = this.webSocketServer;
this.webSocketServer = null;
const server = this.server;
this.server = null;
if (webSocketServer) {
try { webSocketServer.destroy(); } catch { /* already dropping */ }
}
if (server) {
try { server.closeAllConnections(); } catch { /* already closed */ }
try { server.close(() => undefined); } catch { /* already closed */ }
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };

View File

@@ -228,6 +228,20 @@ export class OneBotNetworkManager {
return this.shutdown();
}
/** Best-effort immediate release. Does not wait for the operation queue,
* in-flight dispatches, or peer close handshakes. */
forceRelease(): void {
this.acceptingReconciles = false;
this.acceptingEvents = false;
for (const { adapter } of this.adapters.values()) {
try {
adapter.forceClose();
} catch (error) {
log.error('forced adapter release failed: %s', errMessage(error));
}
}
}
emitEvent(event: JsonObject): Promise<void> {
if (!this.acceptingEvents) {
return Promise.reject(new Error('network manager is shutting down; event dispatch rejected'));

View File

@@ -60,6 +60,21 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
override forceClose(): void {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
this.heartbeatStop?.();
this.heartbeatStop = null;
const socket = this.socket;
this.socket = null;
if (socket) {
try { socket.terminate(); } catch { /* already gone */ }
}
}
async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;

View File

@@ -15,6 +15,7 @@ const moduleLog = createLogger('OneBot.WS-Server');
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private readonly connections: WsServerConnections;
@@ -66,6 +67,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
await attempt;
if (wss && this.wss === wss) this.wss = null;
} catch (error) {
if (this.releaseForced) return;
// A failed close callback leaves release ambiguous. Retain the server
// reference and active binding state so a later shutdown can retry.
this.isEnabled = wasEnabled;
@@ -77,6 +79,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
}
override forceClose(): void {
this.releaseForced = true;
this.isEnabled = false;
this.listening = false;
this.connections.stopAccepting();
this.connections.terminateAll();
const wss = this.wss;
this.wss = null;
if (wss) {
try { wss.destroy(); } catch { /* already dropping */ }
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };

View File

@@ -212,6 +212,17 @@ export class WsServerConnections {
this.connections.clear();
}
/** Destroy sockets immediately. A graceful close frame can leave the
* listener waiting on a peer that will never answer. */
terminateAll(): void {
this.stopAccepting();
for (const connection of this.connections.values()) {
connection.stopHeartbeat();
try { connection.socket.terminate(); } catch { /* already gone */ }
}
this.connections.clear();
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
const text = rawDataToString(raw);
if (!text) {

View File

@@ -1,7 +1,10 @@
import { createLogger } from '@snowluma/common/logger';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const log = createLogger('OneBot.Stream');
export interface StreamStorageSnapshot {
totalBytes: number;
fileCount: number;
@@ -273,7 +276,23 @@ function resolveManagedRoot(input: string): string {
return path.join(fs.realpathSync(parent), path.basename(absolute));
}
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'onebot-stream'));
export function createStreamStorage(env: NodeJS.ProcessEnv = process.env): StreamStorage {
const fallback = path.join(os.tmpdir(), 'onebot-stream');
const raw = env.SNOWLUMA_STREAM_DIR?.trim();
if (!raw) return new StreamStorage(fallback);
try {
return new StreamStorage(raw);
} catch (error) {
log.warn(
'SNOWLUMA_STREAM_DIR=%j is ignored: %s',
raw,
error instanceof Error ? error.message : String(error),
);
return new StreamStorage(fallback);
}
}
export const streamStorage = createStreamStorage();
export const STREAM_ROOT = streamStorage.root;
export const STREAM_UPLOAD_DIR = streamStorage.uploadDir;
export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir;

View File

@@ -40,6 +40,9 @@ const setGroupMemberInvitePolicy = requireAction('set_group_member_invite_policy
const setGroupNewMemberHistoryVisibility = requireAction('set_group_new_member_history_visibility');
const setGroupMemberPermissions = requireAction('set_group_member_permissions');
const getGroupAdminSettings = requireAction('get_group_admin_settings');
const getGroupTags = requireAction('get_group_tags');
const addGroupTag = requireAction('add_group_tag');
const deleteGroupTag = requireAction('delete_group_tag');
const setGroupAdmin = requireAction('set_group_admin');
const setGroupCard = requireAction('set_group_card');
const setGroupName = requireAction('set_group_name');
@@ -62,6 +65,9 @@ describe('group admin actions catalog', () => {
['set_group_new_member_history_visibility'],
['set_group_member_permissions'],
['get_group_admin_settings'],
['get_group_tags'],
['add_group_tag'],
['delete_group_tag'],
['set_group_admin'],
['set_group_card'],
['set_group_name'],
@@ -74,7 +80,7 @@ describe('group admin actions catalog', () => {
expect(actions.map((action) => action.kind)).toEqual([
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
]);
});
});
@@ -1223,3 +1229,92 @@ describe('set_group_portrait toHandler', () => {
expect(setGroupAvatar).not.toHaveBeenCalled();
});
});
describe('get_group_tags parse', () => {
it('accepts category 0 and a numeric string', () => {
expect(getGroupTags.parse({ group_class: 0 })).toEqual({
ok: true,
value: { group_class: 0 },
});
expect(getGroupTags.parse({ group_class: '12' })).toEqual({
ok: true,
value: { group_class: 12 },
});
});
it('rejects a missing, negative, or oversized category', () => {
expect(getGroupTags.parse({})).toEqual({
ok: false,
field: 'group_class',
reason: 'is required',
});
expect(getGroupTags.parse({ group_class: -1 })).toEqual({
ok: false,
field: 'group_class',
reason: 'must be >= 0',
});
expect(getGroupTags.parse({ group_class: 0x1_0000_0000 })).toEqual({
ok: false,
field: 'group_class',
reason: 'must be <= 4294967295',
});
});
});
describe('get_group_tags toHandler', () => {
it('returns the tag list for the category', async () => {
const listCategoryTags = vi.fn(async () => ({
tags: [{ id: 7, name: '学习', type: 1 }],
}));
const { ctx } = adminCtx({ listCategoryTags });
await expect(getGroupTags.toHandler(ctx)({ group_class: 4 })).resolves.toEqual({
status: 'ok',
retcode: 0,
data: { tags: [{ id: 7, name: '学习', type: 1 }] },
});
expect(listCategoryTags.mock.calls).toEqual([[4]]);
});
});
describe('add_group_tag and delete_group_tag', () => {
it('rejects an empty name and does not call the bridge', async () => {
const addCategoryTag = vi.fn(async () => {});
const removeCategoryTag = vi.fn(async () => {});
const { ctx } = adminCtx({ addCategoryTag, removeCategoryTag });
await expect(addGroupTag.toHandler(ctx)({ group_class: 1, name: '' })).resolves.toEqual({
status: 'failed',
retcode: 1400,
data: null,
wording: 'name: must not be empty',
});
await expect(deleteGroupTag.toHandler(ctx)({ group_class: 1, name: '' })).resolves.toEqual({
status: 'failed',
retcode: 1400,
data: null,
wording: 'name: must not be empty',
});
expect(addCategoryTag).not.toHaveBeenCalled();
expect(removeCategoryTag).not.toHaveBeenCalled();
});
it('forwards the category and the exact name', async () => {
const addCategoryTag = vi.fn(async () => {});
const removeCategoryTag = vi.fn(async () => {});
const { ctx } = adminCtx({ addCategoryTag, removeCategoryTag });
await expect(addGroupTag.toHandler(ctx)({ group_class: 0, name: ' 户外 ' })).resolves.toEqual({
status: 'ok',
retcode: 0,
data: null,
});
await expect(deleteGroupTag.toHandler(ctx)({ group_class: '2', name: '户外' })).resolves.toEqual({
status: 'ok',
retcode: 0,
data: null,
});
expect(addCategoryTag.mock.calls).toEqual([[0, ' 户外 ']]);
expect(removeCategoryTag.mock.calls).toEqual([[2, '户外']]);
});
});

View File

@@ -640,3 +640,61 @@ describe('OneBotConfig login history sync', () => {
.toThrow(/historySync\.enabled must be a boolean/);
});
});
describe('OneBot listen port environment overrides', () => {
let tempDir = '';
let previous = '';
const saved: Record<string, string | undefined> = {};
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-port-env-'));
previous = process.cwd();
process.chdir(tempDir);
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
saved[name] = process.env[name];
delete process.env[name];
}
});
afterEach(() => {
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
if (saved[name] === undefined) delete process.env[name];
else process.env[name] = saved[name];
}
process.chdir(previous);
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('overrides only the factory listeners and does not write the port back', () => {
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
process.env.SNOWLUMA_ONEBOT_WS_PORT = '3801';
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
expect(loaded.networks.httpServers[0]?.port).toBe(3800);
expect(loaded.networks.wsServers[0]?.port).toBe(3801);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8')) as {
networks: { httpServers: Array<{ port: number }>; wsServers: Array<{ port: number }> };
};
expect(onDisk.networks.httpServers[0]?.port).toBe(3000);
expect(onDisk.networks.wsServers[0]?.port).toBe(3001);
});
it('leaves a custom listener alone', () => {
const config = makeDefaultOneBotConfig();
config.networks.httpServers = [{
...config.networks.httpServers[0]!,
name: 'public-http',
port: 4000,
}];
saveOneBotConfig('10001', config);
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
const loaded = loadOneBotConfig('10001');
expect(loaded.networks.httpServers.map((server) => server.port)).toEqual([4000]);
});
it('keeps the saved port when the override is not a port', () => {
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = 'nope';
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
expect(loaded.networks.httpServers[0]?.port).toBe(3000);
});
});

View File

@@ -0,0 +1,55 @@
import { once } from 'node:events';
import http from 'node:http';
import net from 'node:net';
import type { AddressInfo } from 'node:net';
import { describe, expect, it } from 'vitest';
import type { NetworkAdapterContext } from '../src/network/adapter';
import { HttpServerAdapter } from '../src/network/http-server-adapter';
import type { HttpServerNetwork } from '../src/types';
describe('HttpServerAdapter forced release', () => {
it('drops a held connection so the port can be bound again', async () => {
const ctx = {
uin: '10001',
api: { handle: async () => ({ status: 'ok', retcode: 0, data: null }), isStreamAction: () => false },
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
} as unknown as NetworkAdapterContext;
const config: HttpServerNetwork = {
name: 'http-force-close',
host: '127.0.0.1',
port: 0,
path: '/',
messageFormat: 'array',
reportSelfMessage: false,
};
const adapter = new HttpServerAdapter(config.name, config, ctx);
let socket: net.Socket | null = null;
try {
await adapter.open();
const server = (adapter as unknown as { server: http.Server | null }).server;
expect(server).not.toBeNull();
const port = (server!.address() as AddressInfo).port;
socket = net.connect({ host: '127.0.0.1', port });
await once(socket, 'connect');
adapter.forceClose();
expect(server!.listening).toBe(false);
await expect(listenOn(port)).resolves.toBeUndefined();
} finally {
socket?.destroy();
await adapter.close();
}
});
});
function listenOn(port: number): Promise<void> {
const server = net.createServer();
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, '127.0.0.1', () => {
server.close(() => resolve());
});
});
}

View File

@@ -7,6 +7,8 @@ import type { AdapterStatus } from '../src/network';
import type { OneBotInstance } from '../src/instance';
import {
OneBotManager,
parseSessionReleaseDeadlineMs,
resolveSessionReleaseDeadlineMs,
type DatabaseMigrationCallbacks,
type DatabaseMigrationTask,
} from '../src/manager';
@@ -38,6 +40,26 @@ function fakeInstance(
} as unknown as OneBotInstance;
}
describe('session release deadline', () => {
it('keeps 10 seconds when nothing overrides it', () => {
expect(resolveSessionReleaseDeadlineMs(undefined, undefined)).toBe(10_000);
expect(resolveSessionReleaseDeadlineMs(undefined, ' ')).toBe(10_000);
});
it('lets SNOWLUMA_SESSION_RELEASE_DEADLINE_MS override a configured deadline', () => {
expect(resolveSessionReleaseDeadlineMs(30, '2500')).toBe(2500);
expect(parseSessionReleaseDeadlineMs('0')).toBeUndefined();
expect(parseSessionReleaseDeadlineMs('-5')).toBeUndefined();
expect(parseSessionReleaseDeadlineMs('1.5')).toBeUndefined();
expect(parseSessionReleaseDeadlineMs('nope')).toBeUndefined();
});
it('ignores an unusable environment value and keeps the configured deadline', () => {
expect(resolveSessionReleaseDeadlineMs(30, 'nope')).toBe(30);
expect(resolveSessionReleaseDeadlineMs(undefined, 'nope')).toBe(10_000);
});
});
describe('database migration estimates', () => {
it('waits for measured throughput and reaches zero on completion', () => {
expect(estimateRemainingSeconds(
@@ -569,6 +591,108 @@ describe('OneBotManager lifecycle failure accounting', () => {
expect((manager as unknown as { pendingStarts: Map<string, unknown> }).pendingStarts.has('10001')).toBe(false);
});
it('starts the replacement account when release never finishes', async () => {
const originalCwd = process.cwd();
const savedDeadline = process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
delete process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-manager-release-'));
process.chdir(root);
const forceRelease = vi.fn();
const old = {
...fakeInstance('10001', () => new Promise(() => undefined)),
forceRelease,
} as unknown as OneBotInstance;
const replacement = {
...fakeInstance('10001', async () => undefined),
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
startLoginHistorySync: vi.fn(),
startGroupRequestPolling: vi.fn(),
} as unknown as OneBotInstance;
let created = false;
const manager = new OneBotManager({
sessionReleaseDeadlineMs: 30,
createDatabaseMigrationTask: () => ({
beginMigration: vi.fn(),
cancel: vi.fn(),
start: (next) => { next.onReady(); },
}),
createInstance: () => {
created = true;
return replacement;
},
});
const internals = manager as unknown as {
retiringInstances: Set<OneBotInstance>;
onSessionStarted(uin: string, bridge: never): void;
pendingStarts: Map<string, unknown>;
};
try {
internals.retiringInstances.add(old);
internals.onSessionStarted('10001', fakeBridge() as never);
await vi.waitFor(() => {
expect(created).toBe(true);
});
expect(forceRelease).toHaveBeenCalledOnce();
expect(manager.getInstance('10001')).toBe(replacement);
expect(internals.pendingStarts.has('10001')).toBe(false);
expect(internals.retiringInstances.has(old)).toBe(false);
} finally {
if (savedDeadline === undefined) delete process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
else process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS = savedDeadline;
process.chdir(originalCwd);
rmSync(root, { recursive: true, force: true });
}
});
it('uses SNOWLUMA_SESSION_RELEASE_DEADLINE_MS instead of a longer configured deadline', async () => {
const originalCwd = process.cwd();
const savedDeadline = process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS = '40';
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-manager-release-env-'));
process.chdir(root);
const forceRelease = vi.fn();
const old = {
...fakeInstance('10001', () => new Promise(() => undefined)),
forceRelease,
} as unknown as OneBotInstance;
let created = false;
const replacement = {
...fakeInstance('10001', async () => undefined),
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
startLoginHistorySync: vi.fn(),
startGroupRequestPolling: vi.fn(),
} as unknown as OneBotInstance;
const manager = new OneBotManager({
sessionReleaseDeadlineMs: 60_000,
createDatabaseMigrationTask: () => ({
beginMigration: vi.fn(),
cancel: vi.fn(),
start: (next) => { next.onReady(); },
}),
createInstance: () => {
created = true;
return replacement;
},
});
const internals = manager as unknown as {
retiringInstances: Set<OneBotInstance>;
onSessionStarted(uin: string, bridge: never): void;
};
try {
internals.retiringInstances.add(old);
internals.onSessionStarted('10001', fakeBridge() as never);
await vi.waitFor(() => {
expect(created).toBe(true);
});
expect(forceRelease).toHaveBeenCalledOnce();
} finally {
if (savedDeadline === undefined) delete process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
else process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS = savedDeadline;
process.chdir(originalCwd);
rmSync(root, { recursive: true, force: true });
}
});
it('allows a later same-UIN start observation to retry a failed handoff', async () => {
const manager = new OneBotManager();
let attempts = 0;

View File

@@ -0,0 +1,36 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { createStreamStorage } from '../src/stream-storage';
describe('SNOWLUMA_STREAM_DIR', () => {
const created: string[] = [];
afterEach(() => {
for (const directory of created.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
it('uses the system temp directory by default', () => {
const storage = createStreamStorage({});
expect(storage.root.endsWith(`${path.sep}onebot-stream`)).toBe(true);
created.push(storage.root);
});
it('uses a caller directory when the variable is set', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-stream-env-'));
created.push(root);
const storage = createStreamStorage({ SNOWLUMA_STREAM_DIR: root });
expect(storage.root).toBe(fs.realpathSync(root));
});
it('falls back when the variable does not name a usable directory', () => {
const file = path.join(os.tmpdir(), `snowluma-stream-not-dir-${process.pid}`);
fs.writeFileSync(file, 'x');
created.push(file);
const storage = createStreamStorage({ SNOWLUMA_STREAM_DIR: file });
expect(storage.root.endsWith(`${path.sep}onebot-stream`)).toBe(true);
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.14.21",
"version": "1.14.22",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",

View File

@@ -1,4 +1,4 @@
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
import type { pb, pb_repeated, int_32, uint_32, uint_64, fixed_32, bool, bytes } from '@snowluma/proton';
import type {
IndexNode,
PictureInfo,
@@ -185,7 +185,7 @@ export interface HttpConn0x6FF501Request {
export interface ServerAddr {
type?: pb<1, uint_32>;
ip?: pb<2, uint_32>;
ip?: pb<2, fixed_32>;
port?: pb<3, uint_32>;
area?: pb<4, uint_32>;
}

View File

@@ -0,0 +1,23 @@
import type { pb, pb_optional, pb_repeated, uint_32 } from '@snowluma/proton';
/** One tag shown under a group-profile category. */
export interface OidbGroupCategoryTag {
id?: pb<1, uint_32>;
name?: pb<2, string>;
type?: pb<3, uint_32>;
}
/** List the tags of one category. Category 0 is a real value and must be sent. */
export interface OidbGetGroupCategoryTags {
groupClass?: pb_optional<1, uint_32>;
}
export interface OidbGetGroupCategoryTagsResp {
tags?: pb_repeated<1, OidbGroupCategoryTag>;
}
/** Add or remove one tag name in a category. */
export interface OidbChangeGroupCategoryTag {
groupClass?: pb_optional<1, uint_32>;
name?: pb<2, string>;
}

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.14.21",
"version": "1.14.22",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",

View File

@@ -0,0 +1,39 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbChangeGroupCategoryTag } from '@snowluma/proto-defs/oidb-actions/group-category-tag';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace AddGroupCategoryTag {
export const command = 0x967D;
export const subCommand = 0;
export interface Params {
groupClass: number;
name: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbChangeGroupCategoryTag => {
assertTagChange(p.groupClass, p.name);
return { groupClass: p.groupClass, name: p.name };
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbChangeGroupCategoryTag>): Uint8Array =>
protobuf_encode<OidbBase<OidbChangeGroupCategoryTag>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, AddGroupCategoryTag, params);
}
function assertTagChange(groupClass: number, name: string): void {
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xFFFFFFFF) {
throw new Error(`group class ${groupClass} is out of range`);
}
if (name.length === 0) throw new Error('tag name must not be empty');
}

View File

@@ -0,0 +1,39 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbChangeGroupCategoryTag } from '@snowluma/proto-defs/oidb-actions/group-category-tag';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace DeleteGroupCategoryTag {
export const command = 0x967E;
export const subCommand = 0;
export interface Params {
groupClass: number;
name: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbChangeGroupCategoryTag => {
assertTagChange(p.groupClass, p.name);
return { groupClass: p.groupClass, name: p.name };
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbChangeGroupCategoryTag>): Uint8Array =>
protobuf_encode<OidbBase<OidbChangeGroupCategoryTag>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, DeleteGroupCategoryTag, params);
}
function assertTagChange(groupClass: number, name: string): void {
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xFFFFFFFF) {
throw new Error(`group class ${groupClass} is out of range`);
}
if (name.length === 0) throw new Error('tag name must not be empty');
}

View File

@@ -0,0 +1,60 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGetGroupCategoryTags,
OidbGetGroupCategoryTagsResp,
OidbGroupCategoryTag,
} from '@snowluma/proto-defs/oidb-actions/group-category-tag';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupCategoryTag {
id: number;
name: string;
type: number;
}
export namespace GetGroupCategoryTags {
export const command = 0x967C;
export const subCommand = 0;
export interface Params {
groupClass: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGetGroupCategoryTags => {
assertGroupClass(p.groupClass);
return { groupClass: p.groupClass };
};
export const deserialize = (
_ctx: Deps,
body: OidbGetGroupCategoryTagsResp,
): { tags: GroupCategoryTag[] } => ({
tags: (body.tags ?? []).map(toTag),
});
export const encode = (env: OidbBase<OidbGetGroupCategoryTags>): Uint8Array =>
protobuf_encode<OidbBase<OidbGetGroupCategoryTags>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGetGroupCategoryTagsResp> =>
protobuf_decode<OidbBase<OidbGetGroupCategoryTagsResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<{ tags: GroupCategoryTag[] }> =>
invokeOidb(deps, GetGroupCategoryTags, params);
}
function assertGroupClass(groupClass: number): void {
if (!Number.isInteger(groupClass) || groupClass < 0 || groupClass > 0xFFFFFFFF) {
throw new Error(`group class ${groupClass} is out of range`);
}
}
function toTag(tag: OidbGroupCategoryTag): GroupCategoryTag {
return {
id: tag.id ?? 0,
name: tag.name ?? '',
type: tag.type ?? 0,
};
}

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.14.21",
"version": "1.14.22",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.14.21",
"version": "1.14.22",
"private": true,
"type": "module",
"main": "index.mjs",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.14.21",
"version": "1.14.22",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",

View File

@@ -30,6 +30,8 @@ import type {
GetPrivateFileUrlParams,
GroupForwardMessageParams,
GroupIdParams,
GroupClassParams,
GroupCategoryTagNameParams,
GroupNoticeParams,
GroupPokeParams,
MarkGroupMsgAsReadParams,
@@ -88,6 +90,7 @@ import type {
FriendCategoryResult,
FriendMessageHistory,
GroupAdminSettings,
GroupCategoryTagList,
GroupAtAllRemainInfo,
GroupFileSystemInfo,
GroupFileUrl,
@@ -142,6 +145,9 @@ export interface SnowLumaActionMap {
set_group_add_option: { params: SetGroupAddOptionParams; data: EmptyData };
set_group_search: { params: GroupIdParams; data: EmptyData };
get_group_admin_settings: { params: GroupIdParams; data: GroupAdminSettings };
get_group_tags: { params: GroupClassParams; data: GroupCategoryTagList };
add_group_tag: { params: GroupCategoryTagNameParams; data: EmptyData };
delete_group_tag: { params: GroupCategoryTagNameParams; data: EmptyData };
set_group_admin: { params: SetGroupAdminParams; data: EmptyData };
set_group_card: { params: SetGroupCardParams; data: EmptyData };
set_group_name: { params: SetGroupNameParams; data: EmptyData };

View File

@@ -28,6 +28,14 @@ export interface GroupIdParams extends JsonObject {
group_id: number;
}
export interface GroupClassParams extends JsonObject {
group_class: number;
}
export interface GroupCategoryTagNameParams extends GroupClassParams {
name: string;
}
export interface UserIdParams extends JsonObject {
user_id: number;
}

View File

@@ -219,6 +219,16 @@ export interface GroupAtAllRemainInfo {
remain_at_all_count_for_uin: number;
}
export interface GroupCategoryTag {
id: number;
name: string;
type: number;
}
export interface GroupCategoryTagList {
tags: GroupCategoryTag[];
}
export type GroupAdminSettings = {
add_type: number;
group_question: string;

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.14.21",
"version": "1.14.22",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.14.21",
"version": "1.14.22",
"private": true,
"type": "module",
"main": "./src/index.ts",

View File

@@ -282,4 +282,21 @@ export class WebSocketServer extends EventEmitter {
setImmediate(cb);
}
}
/** Destroy clients and, when this server owns the HTTP listener, that
* listener too. An external HTTP server is left to its owner. */
destroy(): void {
for (const ws of this.clients) {
try { ws.terminate(); } catch { /* noop */ }
}
if (this._externalServer && this._upgradeHandler) {
this._externalServer.removeListener('upgrade', this._upgradeHandler);
this._upgradeHandler = null;
}
if (this._server) {
try { this._server.closeAllConnections(); } catch { /* noop */ }
try { this._server.close(() => undefined); } catch { /* noop */ }
this._server = null;
}
}
}

View File

@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.14.21",
"version": "1.14.22",
"type": "module",
"scripts": {
"dev": "vite",