Merge pull request #210 from SnowLuma/dev

chore: promote dev → main (b6fb5bd)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-07-07 14:38:33 +00:00
commit fbc2aa052b
47 files changed
+1644 -90

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.11.4",
"version": "1.12.0",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.11.4",
"version": "1.12.0",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.11.4",
"version": "1.12.0",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.11.4",
"version": "1.12.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+3 -1
View File
@@ -163,7 +163,9 @@ async function buildForwardPushBody(
subType: 4,
msgId: random,
sequence: seq,
timestamp: now,
// Honour a custom per-node display time (#209); default to now. `now`
// still drives the c2c-file expireTime above, which must stay real.
timestamp: node.time && node.time > 0 ? node.time : now,
c2cCmd: 0,
},
body: {
+2
View File
@@ -4,6 +4,7 @@ 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, parseMsgPush, SysMsgDedup } 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 { buildApiHub, type ApiHub } from './apis';
import {
@@ -65,6 +66,7 @@ export class Bridge implements BridgeInterface {
},
});
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_));
this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT);
}
dispose(): void {
+35 -3
View File
@@ -14,13 +14,26 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => []),
}));
import { gzipSync } from 'zlib';
import { protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgResp, LongMsgResult, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { gunzipSync, gzipSync } from 'zlib';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
/** Decode the SsoSendLongMsg packet body back into the per-node contentHead
* timestamps of the MultiMsg action — how #209's custom time is verified on
* the wire. */
function sentNodeTimestamps(body: Uint8Array): number[] {
const req = protobuf_decode<SendLongMsgReq>(body);
const payload = req.info?.payload;
if (!payload) return [];
const longMsg = protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
const main = longMsg.action?.find((a) => a?.actionCommand === 'MultiMsg');
const bodies = Array.isArray(main?.actionData?.msgBody) ? main!.actionData!.msgBody : [];
return bodies.map((b) => Number(b.contentHead?.timestamp ?? 0));
}
function uploadResponseWithResId(resId: string) {
const encoded = protobuf_encode<SendLongMsgResp>({ result: { resId } });
return {
@@ -65,6 +78,25 @@ describe('actions/forward', () => {
expect((body as Uint8Array).length).toBeGreaterThan(0);
});
it('honours a custom per-node time on the wire, and defaults to now when absent (#209)', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-time')) as any,
});
const customTime = 1600000000; // 2020-09-13, clearly not "now"
await new ForwardApi(bridge as any).upload([
{ userUin: 10001, nickname: 'alice', elements: [], time: customTime },
{ userUin: 10002, nickname: 'bob', elements: [] }, // no time → fallback
]);
const [, body] = bridge.sendRawPacket.mock.calls[0]!;
const [tsAlice, tsBob] = sentNodeTimestamps(body as Uint8Array);
expect(tsAlice).toBe(customTime);
// Bob falls back to the current time (seconds).
expect(Math.abs(tsBob - Math.floor(Date.now() / 1000))).toBeLessThan(5);
});
it('uploadForwardNodes throws when sendRawPacket reports failure', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
@@ -14,6 +14,8 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
// inline-extract the kind.
import type {
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin,
InputStatusNotify, NotifyMessageBody, GroupNameChange, GroupSpecialTitleChange,
ProfileLikeTip,
} from '@snowluma/proto-defs/notify';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type {
@@ -254,6 +256,193 @@ describe('parseMsgPush Event0x210 subType=179/226 (NewFriend → friend_add)', (
});
});
describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输入)', () => {
// RE'd from wrapper.linux.node aio_input_state_worker.cc: 0x210/0x115 sys_msg,
// body = InputStatusNotify {fromUid, toUid, notifyItem{eventType@f4}}.
type FriendInputStatusEvent = Extract<QQEventVariant, { kind: 'friend_input_status' }>;
function makeInputStatusPacket(fromUid: string, eventType: number): PacketInfo {
const content = protobuf_encode<InputStatusNotify>({
fromUid,
toUid: 'u_self',
notifyItem: { eventType },
});
return makeEvent0x210PacketAny(277, content);
}
it('emits friend_input_status (typing) for eventType 1', () => {
const member = makeGroupMember(77777, 'u_typer');
const [event] = parseMsgPush(
makeInputStatusPacket(member.uid, 1),
makeIdentity([member]),
) as FriendInputStatusEvent[];
expect(event.kind).toBe('friend_input_status');
expect(event.userUin).toBe(77777);
expect(event.eventType).toBe(1);
expect(event.statusText).toBe('对方正在输入...');
});
it('surfaces eventType 3 as the voice-recording status text', () => {
const member = makeGroupMember(77777, 'u_typer');
const [event] = parseMsgPush(
makeInputStatusPacket(member.uid, 3),
makeIdentity([member]),
) as FriendInputStatusEvent[];
expect(event.eventType).toBe(3);
expect(event.statusText).toBe('对方正在讲话...');
});
it('drops a body with no fromUid (nothing to key user_id on)', () => {
const events = parseMsgPush(
makeEvent0x210PacketAny(277, protobuf_encode<InputStatusNotify>({ notifyItem: { eventType: 1 } })),
makeIdentity(),
);
expect(events).toEqual([]);
});
});
describe('parseMsgPush Event0x210 subType=39 (profile like → 名片赞)', () => {
// 0x210/39 is multiplexed; body.msgContent decodes as ProfileLikeTip and is a
// like only when inner msgType==0 && subType==203. Proto shape from NapCat's
// raw-bytes decoder (pending a real like capture to validate byte-exactly).
type FriendProfileLikeEvent = Extract<QQEventVariant, { kind: 'friend_profile_like' }>;
function makeLikePacket(opts: { msgType?: number; subType?: number; uin?: number; nick?: string; txt?: string; time?: number }): PacketInfo {
const content = protobuf_encode<ProfileLikeTip>({
msgType: opts.msgType ?? 0,
subType: opts.subType ?? 203,
content: { msg: {
time: opts.time ?? 1710001111,
detail: { txt: opts.txt ?? '', uin: BigInt(opts.uin ?? 0), nickname: opts.nick ?? '' },
} },
});
return makeEvent0x210PacketAny(39, content);
}
it('emits friend_profile_like with liker uin, nick and parsed count', () => {
// txt shape taken from a real capture: "赞了我的资料卡N次".
const [event] = parseMsgPush(
makeLikePacket({ uin: 1206069534, nick: '墨白灵MotricLuck', txt: '赞了我的资料卡2次' }),
makeIdentity(),
) as FriendProfileLikeEvent[];
expect(event.kind).toBe('friend_profile_like');
expect(event.operatorUin).toBe(1206069534);
expect(event.operatorNick).toBe('墨白灵MotricLuck');
expect(event.times).toBe(2);
expect(event.time).toBe(1710001111);
});
it('ignores a non-like 39 variant (inner subType != 203)', () => {
const events = parseMsgPush(
makeLikePacket({ subType: 999, uin: 1787882683 }),
makeIdentity(),
);
expect(events).toEqual([]);
});
});
describe('parseMsgPush Event0x2DC subType=16 field13=6 (group special title)', () => {
// Built from a REAL on-wire capture: eventParam f2 = the gray-tip template
// "恭喜<{member}>获得群主授予的<{…"text":TITLE…}>头衔", f5 = member uin. The title
// is the last <{…}> token's text.
type GroupTitleChangeEvent = Extract<QQEventVariant, { kind: 'group_title_change' }>;
const TIP = '恭喜<{"cmd":5,"data":"3433035623","text":"星屿"}>获得群主授予的'
+ '<{"cmd":1,"data":"https://qun.qq.com/x?medal=302&uin=3433035623","text":"摸鱼冠军",'
+ '"url":"https://qun.qq.com/x?medal=302&uin=3433035623"}>头衔';
function makeTitlePacket(memberUin: number, tip: string): PacketInfo {
const notify = protobuf_encode<NotifyMessageBody>({
groupUin: GROUP_ID,
field13: 6,
eventParam: protobuf_encode<GroupSpecialTitleChange>({ tipText: tip, memberUin }),
});
const content = new Uint8Array(7 + notify.length);
content.set(notify, 7);
const body = protobuf_encode<PushMsg>({
message: {
responseHead: { fromUin: 0, type: 0, sigMap: 0 },
contentHead: { msgType: 732, subType: 16, timestamp: 1710000000 },
body: { msgContent: content },
},
status: 0,
});
return { pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, retCode: 0, fromClient: false, body };
}
it('emits group_title_change with the granted title + member', () => {
const [event] = parseMsgPush(
makeTitlePacket(22222, TIP),
makeIdentity([makeGroupMember(22222, 'u_member')]),
) as GroupTitleChangeEvent[];
expect(event.kind).toBe('group_title_change');
expect(event.groupId).toBe(GROUP_ID);
expect(event.userUin).toBe(22222);
expect(event.title).toBe('摸鱼冠军'); // last <{…}> token's text
});
it('drops a title tip with no parseable title token', () => {
const events = parseMsgPush(
makeTitlePacket(22222, '恭喜获得头衔'),
makeIdentity(),
);
expect(events).toEqual([]);
});
});
describe('parseMsgPush Event0x2DC subType=16 field13=12 (group name change)', () => {
// RE cross-ref: Lagrange Event0x2DCSubType16Field13.GroupNameChangeNotice = 12,
// EventParam(f5) → GroupNameChange{f2=name}, operator = NotifyMessageBody.f21.
// The 0x2DC subType16 body carries a 7-byte prefix (groupUin+byte+len) before
// the NotifyMessageBody proto — the decoder strips it via subarray(7).
type GroupNameChangeEvent = Extract<QQEventVariant, { kind: 'group_name_change' }>;
function makeGroupNamePacket(groupUin: number, operatorUid: string, name: string): PacketInfo {
const notify = protobuf_encode<NotifyMessageBody>({
groupUin,
field13: 12,
operatorUid,
eventParam: protobuf_encode<GroupNameChange>({ name }),
});
const content = new Uint8Array(7 + notify.length); // 7-byte prefix + proto
content.set(notify, 7);
const body = protobuf_encode<PushMsg>({
message: {
responseHead: { fromUin: 0, type: 0, sigMap: 0 },
contentHead: { msgType: 732, subType: 16, timestamp: 1710000000 },
body: { msgContent: content },
},
status: 0,
});
return { pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, retCode: 0, fromClient: false, body };
}
it('emits group_name_change with the new name + operator', () => {
const member = makeGroupMember(54321, 'u_operator');
const [event] = parseMsgPush(
makeGroupNamePacket(GROUP_ID, member.uid, '新的群名'),
makeIdentity([member]),
) as GroupNameChangeEvent[];
expect(event.kind).toBe('group_name_change');
expect(event.groupId).toBe(GROUP_ID);
expect(event.name).toBe('新的群名');
expect(event.operatorUin).toBe(54321);
});
it('drops a name-change body with an empty name', () => {
const events = parseMsgPush(
makeGroupNamePacket(GROUP_ID, 'u_operator', ''),
makeIdentity(),
);
expect(events).toEqual([]);
});
});
describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => {
// 138 = friend recalled their own message sent to bot
// (peer in friend_recall event = fromUid)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.11.4",
"version": "1.12.0",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.11.4",
"version": "1.12.0",
"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>'`.",
@@ -6,16 +6,22 @@ import {
convertTempMessage,
} from './to-message';
import {
convertBotOffline,
convertFriendAdd,
convertFriendInputStatus,
convertFriendProfileLike,
convertFriendPoke,
convertFriendRecall,
convertGroupAdmin,
convertGroupCardChange,
convertGroupEssence,
convertGroupFileUpload,
convertGroupMemberJoin,
convertGroupMemberLeave,
convertGroupMsgEmojiLike,
convertGroupMute,
convertGroupNameChange,
convertGroupTitleChange,
convertGroupPoke,
convertGroupRecall,
} from './to-notice';
@@ -78,6 +84,12 @@ const CONVERTERS: ConverterRegistry = {
group_essence: convertGroupEssence,
group_file_upload: convertGroupFileUpload,
friend_add: convertFriendAdd,
friend_input_status: convertFriendInputStatus,
friend_profile_like: convertFriendProfileLike,
bot_offline: convertBotOffline,
group_name_change: convertGroupNameChange,
group_title_change: convertGroupTitleChange,
group_card_change: convertGroupCardChange,
group_msg_emoji_like: convertGroupMsgEmojiLike,
// Requests.
friend_request: convertFriendRequest,
@@ -17,6 +17,12 @@ type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
type FriendInputStatus = Extract<QQEventVariant, { kind: 'friend_input_status' }>;
type GroupNameChange = Extract<QQEventVariant, { kind: 'group_name_change' }>;
type GroupCardChange = Extract<QQEventVariant, { kind: 'group_card_change' }>;
type GroupTitleChange = Extract<QQEventVariant, { kind: 'group_title_change' }>;
type FriendProfileLike = Extract<QQEventVariant, { kind: 'friend_profile_like' }>;
type BotOffline = Extract<QQEventVariant, { kind: 'bot_offline' }>;
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
return notice(ctx, event, {
@@ -156,6 +162,77 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO
});
}
export function convertGroupCardChange(ctx: ConverterContext, event: GroupCardChange): JsonObject {
// Mirrors NapCat's OB11GroupCardEvent: notice_type group_card with the new and
// old group cards.
return notice(ctx, event, {
notice_type: 'group_card',
group_id: event.groupId,
user_id: event.userUin,
card_new: event.cardNew,
card_old: event.cardOld,
});
}
export function convertBotOffline(ctx: ConverterContext, event: BotOffline): JsonObject {
// Mirrors NapCat's OB11BotOfflineEvent: notice_type bot_offline with the bot's
// own uin plus the tag/message describing why it went offline.
return notice(ctx, event, {
notice_type: 'bot_offline',
user_id: event.selfUin,
tag: event.tag,
message: event.message,
});
}
export function convertFriendProfileLike(ctx: ConverterContext, event: FriendProfileLike): JsonObject {
// Mirrors NapCat's OB11ProfileLikeEvent: notify/profile_like with the liker's
// uin, nickname and like count.
return notice(ctx, event, {
notice_type: 'notify',
sub_type: 'profile_like',
operator_id: event.operatorUin,
operator_nick: event.operatorNick,
times: event.times,
});
}
export function convertGroupTitleChange(ctx: ConverterContext, event: GroupTitleChange): JsonObject {
// Mirrors NapCat's OB11GroupTitleEvent: notify/title with the recipient's uin
// and the granted title text.
return notice(ctx, event, {
notice_type: 'notify',
sub_type: 'title',
group_id: event.groupId,
user_id: event.userUin,
title: event.title,
});
}
export function convertGroupNameChange(ctx: ConverterContext, event: GroupNameChange): JsonObject {
// Mirrors NapCat's OB11GroupNameEvent: notify/group_name with the operator's
// uin as user_id and the new name in `name_new`.
return notice(ctx, event, {
notice_type: 'notify',
sub_type: 'group_name',
group_id: event.groupId,
user_id: event.operatorUin,
name_new: event.name,
});
}
export function convertFriendInputStatus(ctx: ConverterContext, event: FriendInputStatus): JsonObject {
// Mirrors NapCat's OB11InputStatusEvent: notify/input_status with the peer's
// uin, the raw event_type (1 = typing, 3 = recording voice) and status_text.
return notice(ctx, event, {
notice_type: 'notify',
sub_type: 'input_status',
user_id: event.userUin,
event_type: event.eventType,
status_text: event.statusText,
});
}
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
+6
View File
@@ -70,6 +70,12 @@ const NOTICE_KINDS = [
'group_essence',
'group_file_upload',
'friend_add',
'friend_input_status',
'friend_profile_like',
'bot_offline',
'group_name_change',
'group_title_change',
'group_card_change',
'group_msg_emoji_like',
] as const satisfies readonly QQEventVariant['kind'][];
@@ -1240,6 +1240,12 @@ async function parseForwardNodes(
}
const node: ForwardNodePayload = { userUin, nickname, elements };
// Honour an explicit per-node display time (OneBot `data.time`, unix
// seconds) so a custom forward can set/back-date each node's timestamp
// (#209). The wire field is uint32, so reject a millisecond value or any
// out-of-range input (it would overflow/throw) and fall back to now.
const nodeTime = toPositiveInt(nodeData.time);
if (nodeTime > 0 && nodeTime < 0xffffffff) node.time = nodeTime;
if (innerForward) node.innerForward = innerForward;
nodes.push(node);
}
+62
View File
@@ -49,6 +49,68 @@ export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): vo
socket.close(code, reason);
}
/** RFC6455 transport-level keepalive for a reverse-WS connection.
*
* The OneBot app-level `meta_event` heartbeat is a one-way outbound push, so it
* cannot detect a connection that is writable but no longer readable — a
* half-open link left behind when the peer restarts behind a proxy/NAT. In that
* state events keep flowing out while inbound action frames silently never
* arrive, and only a full restart recovers it (issue #208).
*
* This pings every `intervalMs` and counts consecutive silent intervals. ANY
* inbound activity — a pong OR a message — resets the counter, so a connection
* carrying real traffic is never reaped. Death is declared once `maxMissed`
* pings have gone unanswered, i.e. after roughly `(maxMissed + 1) * intervalMs`
* of total silence (the counter is checked at the top of each tick, so the
* tick that observes the threshold is one interval past the last ping). The
* tolerance plus a conservative interval keeps the false-positive rate near
* zero: a single GC pause, event-loop stall, or transient latency spike is
* absorbed (Node fires an overdue interval once, not N catch-up times), and
* death is declared only on genuine sustained silence.
*
* Returns an idempotent stop function; the timer is `unref`'d so it never keeps
* the process alive. */
export function startHeartbeat(
socket: WebSocket,
opts: { intervalMs: number; maxMissed: number },
onDead: () => void,
): () => void {
let missed = 0;
let stopped = false;
const onActivity = (): void => { missed = 0; };
socket.on('pong', onActivity);
socket.on('message', onActivity);
const timer = setInterval(() => {
if (missed >= opts.maxMissed) {
// `maxMissed` consecutive intervals with zero inbound traffic — the read
// direction is dead. Stop first so onDead()'s terminate→close→reconnect
// can't re-enter this tick.
stop();
onDead();
return;
}
missed += 1;
try {
socket.ping();
} catch {
// Ping on an already-dead socket — treat as dead immediately.
stop();
onDead();
}
}, opts.intervalMs);
timer.unref?.();
function stop(): void {
if (stopped) return;
stopped = true;
clearInterval(timer);
socket.off?.('pong', onActivity);
socket.off?.('message', onActivity);
}
return stop;
}
export function normalizePath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
@@ -8,10 +8,17 @@ import {
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend, safeSendAsync } from './utils';
import { rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
// Transport-level keepalive: ping every 30s, declare the link dead only after 2
// consecutive pings go unanswered — ~90s of total silence (see startHeartbeat
// for the +1-interval timing). Conservative on purpose so transient jitter/GC
// never reaps a healthy connection. See issue #208.
const HEARTBEAT_INTERVAL_MS = 30_000;
const HEARTBEAT_MAX_MISSED = 2;
const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
@@ -20,6 +27,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
// Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it
// immediately instead of waiting for the deferred 'close' event. The per-socket
// closure in connect() still owns the #97 stale-socket case; this is idempotent
// with it (both call the same stop).
private heartbeatStop: (() => void) | null = null;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
@@ -41,6 +53,8 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
this.heartbeatStop?.();
this.heartbeatStop = null;
if (this.socket) {
safeClose(this.socket);
this.socket = null;
@@ -90,11 +104,30 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
const socket = new WebSocket(this.config.url, { headers });
this.socket = socket;
// Per-socket so a hot-reload overlap (old close firing after the new socket
// is assigned, see #97) can only ever stop its own keepalive.
let stopHeartbeat: (() => void) | null = null;
socket.on('open', () => {
// Symmetric with the 'close' guard (#97): if this socket was already
// replaced, a late 'open' must not flip `connected` or install a stale
// heartbeat onto the current connection's slot.
if (this.socket !== socket) return;
this.connected = true;
this.log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
// Only meaningful once OPEN — ping() no-ops before the handshake completes.
stopHeartbeat = startHeartbeat(
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
if (this.explicitlyClosed || !this.isEnabled) return;
this.log.warn('[%s] no inbound response for ~%ds, reconnecting half-open connection %s', this.name, HEARTBEAT_DEAD_AFTER_S, this.config.url);
// terminate → 'close' → scheduleReconnect, reusing the normal path.
socket.terminate();
},
);
this.heartbeatStop = stopHeartbeat;
});
socket.on('message', (raw: Buffer) => {
@@ -104,6 +137,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
});
socket.on('close', () => {
stopHeartbeat?.();
// Drop the instance handle only if it still points at THIS socket's stop
// (a newer socket may already own it after a hot-reload overlap).
if (this.heartbeatStop === stopHeartbeat) this.heartbeatStop = null;
stopHeartbeat = null;
// Ignore close events from a socket that is no longer the current
// connection. A hot reload (signature change) calls close() then open()
// back-to-back; the old socket's `'close'` event fires AFTER the new
@@ -9,14 +9,22 @@ import {
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync } from './utils';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
// Transport keepalive for each attached client, symmetric with the ws-client
// adapter: ping every 30s, reap a client only after 2 consecutive pings go
// unanswered — ~90s of total silence (see startHeartbeat for the +1-interval
// timing). Any inbound frame resets the counter — see issue #208.
const HEARTBEAT_INTERVAL_MS = 30_000;
const HEARTBEAT_MAX_MISSED = 2;
const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000;
interface ForwardConn {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
stopHeartbeat: () => void;
}
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
@@ -50,7 +58,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.isEnabled = false;
this.listening = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
for (const conn of this.connections.values()) {
conn.stopHeartbeat();
safeClose(conn.socket);
}
this.connections.clear();
this.wss?.close();
this.wss = null;
@@ -115,7 +126,15 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
const role = this.config.role ?? classifyForwardRole(request);
const conn: ForwardConn = { socket, role, options: this.options };
const stopHeartbeat = startHeartbeat(
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
this.log.warn('[%s] client silent for ~%ds, terminating half-open connection', this.name, HEARTBEAT_DEAD_AFTER_S);
socket.terminate(); // → 'close' → connections.delete; the client reconnects on its own
},
);
const conn: ForwardConn = { socket, role, options: this.options, stopHeartbeat };
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
@@ -123,7 +142,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
});
socket.on('close', () => this.connections.delete(socket));
socket.on('close', () => {
stopHeartbeat();
this.connections.delete(socket);
});
socket.on('error', (err: Error) => {
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
});
@@ -97,6 +97,31 @@ describe('forward — nested {type:"node"} content', () => {
expect(sendGroupMessage).toHaveBeenCalledOnce();
});
it('threads an explicit data.time onto the node payload, leaving absent ones for the default (#209)', async () => {
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
const messages = [
{ type: 'node', data: { user_id: 111, nickname: 'a', time: 1600000000, content: [{ type: 'text', data: { text: 'hi' } }] } },
{ type: 'node', data: { user_id: 222, nickname: 'b', content: [{ type: 'text', data: { text: 'yo' } }] } },
{ type: 'node', data: { user_id: 333, nickname: 'c', time: 1700000000000, content: [{ type: 'text', data: { text: 'ms' } }] } }, // ms → out of uint32 range
{ type: 'node', data: { user_id: 444, nickname: 'd', time: -5, content: [{ type: 'text', data: { text: 'neg' } }] } },
];
await sendGroupForwardMessage(ctx, 12345, messages as any);
const [nodes] = uploadForwardNodes.mock.calls[0]!;
expect((nodes as any[])[0].time).toBe(1600000000); // explicit seconds carried through
expect((nodes as any[])[1].time).toBeUndefined(); // absent → default to now
expect((nodes as any[])[2].time).toBeUndefined(); // millisecond input rejected (uint32 overflow guard)
expect((nodes as any[])[3].time).toBeUndefined(); // negative rejected → default to now
});
it('private: nested forward threads userId into uploadForwardNodes', async () => {
// Same shape but routed via sendPrivateForwardMessage. The c2c path
// passes `userId` instead of `groupId` so the upload pipeline can
@@ -0,0 +1,225 @@
// Issue #208: after a reverse-WS reconnect the link could end up half-open —
// writable (events keep flowing out) but not readable (inbound action frames
// never arrive), a state only a full restart recovered. The fix adds a
// transport-level ping/pong keepalive that reconnects a genuinely silent link.
//
// These tests pin BOTH sides of the contract: it must reconnect a dead link,
// and — the harder half — it must NOT reap a healthy one. The false-positive
// guards are the point: death is declared only after `maxMissed` consecutive
// intervals with zero inbound traffic (pong OR message), so pong round-trips
// and live message flow both keep a connection alive indefinitely.
//
// Mock `@snowluma/websocket` (native addon isn't built in a plain checkout),
// mirroring ws-client-stale-close.test.ts. Timers are faked and driven.
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { FakeWebSocket, instances } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { EventEmitter } = require('node:events') as typeof import('node:events');
const instances: FakeWebSocket[] = [];
class FakeWebSocket extends EventEmitter {
public readyState = 1; // 1 = OPEN, 2 = CLOSING, 3 = CLOSED
public pings = 0;
public terminated = false;
public readonly url: string;
constructor(url: string, _opts: unknown) {
super();
this.url = url;
instances.push(this);
}
send(_payload: string, cb?: (err?: Error | null) => void): void { cb?.(null); }
ping(): void { this.pings += 1; }
terminate(): void {
if (this.readyState === 3) return;
this.terminated = true;
this.readyState = 3;
this.emit('close'); // real terminate → destroy → deferred 'close'; sync here
}
close(code = 1000, reason = 'normal'): void {
void code; void reason;
if (this.readyState >= 2) return;
this.readyState = 2; // do NOT auto-emit 'close' (matches the real deferral)
}
simulateOpen(): void { this.emit('open'); }
simulatePong(): void { this.emit('pong', Buffer.alloc(0)); }
simulateMessage(): void { this.emit('message', Buffer.from('{}'), false); }
simulateClose(): void { this.readyState = 3; this.emit('close'); }
}
return { FakeWebSocket, instances };
});
vi.mock('@snowluma/websocket', () => ({ WebSocket: FakeWebSocket }));
import { WsClientAdapter } from '../src/network/ws-client-adapter';
import type { NetworkAdapterContext } from '../src/network/adapter';
import type { WsClientNetwork } from '../src/types';
// Must match the adapter's module constants.
const INTERVAL = 30_000;
const MAX_MISSED = 2;
function ctx(): NetworkAdapterContext {
return {
uin: '10001',
api: { processStreamRequest: async () => {} } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
}
function cfg(over: Partial<WsClientNetwork> = {}): WsClientNetwork {
return {
enabled: true,
url: 'ws://127.0.0.1:8080/',
role: 'Universal',
reconnectIntervalMs: 1000,
...over,
} as WsClientNetwork;
}
describe('WsClientAdapter — transport heartbeat (issue #208)', () => {
beforeEach(() => { instances.length = 0; });
it('reconnects a silent (half-open) connection, but only after maxMissed intervals', () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
const a = instances[0];
a.simulateOpen();
// maxMissed silent intervals are TOLERATED — the counter absorbs transient
// jitter/GC without reaping. Still alive here.
vi.advanceTimersByTime(INTERVAL * MAX_MISSED);
expect(a.terminated).toBe(false);
expect(instances).toHaveLength(1);
// The next silent interval crosses the threshold: terminate → 'close' →
// scheduleReconnect (no new socket until the reconnect interval elapses).
vi.advanceTimersByTime(INTERVAL);
expect(a.terminated).toBe(true);
expect(instances).toHaveLength(1);
vi.advanceTimersByTime(1000);
expect(instances).toHaveLength(2); // reconnect spun up a fresh socket
expect(instances[1]).not.toBe(a);
} finally {
vi.useRealTimers();
}
});
it('never reaps a healthy connection whose pong lags a full interval', () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
const a = instances[0];
a.simulateOpen();
// Each cycle lets TWO intervals pass with no pong (missed climbs 0→1→2)
// before a pong arrives, so a non-zero `missed` is carried across a check
// boundary. A broken 1-strike (`missed >= 1`) impl reaps on the 2nd tick;
// the real 2-strike tolerance survives (the fatal `>= 2` check never sees
// 2 because the pong resets first).
for (let i = 0; i < 10; i++) {
vi.advanceTimersByTime(INTERVAL); // silent tick → missed = 1
vi.advanceTimersByTime(INTERVAL); // silent tick → missed = 2 (still alive)
a.simulatePong(); // pong resets missed → 0
}
expect(a.terminated).toBe(false);
expect(instances).toHaveLength(1);
expect(a.pings).toBeGreaterThan(0); // it WAS actively probing
} finally {
vi.useRealTimers();
}
});
it('treats inbound message traffic as liveness (no pong needed)', () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
const a = instances[0];
a.simulateOpen();
// No pongs at all, but a message arrives every interval. A busy link is
// provably alive, so it must never be reaped.
for (let i = 0; i < 10; i++) {
vi.advanceTimersByTime(INTERVAL);
a.simulateMessage();
}
expect(a.terminated).toBe(false);
expect(instances).toHaveLength(1);
} finally {
vi.useRealTimers();
}
});
it('close() proactively stops the heartbeat — no lingering pings on the socket', () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
const a = instances[0];
a.simulateOpen();
vi.advanceTimersByTime(INTERVAL); // one real tick → a.pings === 1
// close() must halt the keepalive immediately, NOT wait for the deferred
// 'close' event (a real ws defers it). No further pings, no reap.
adapter.close();
const pingsAtClose = a.pings;
vi.advanceTimersByTime(INTERVAL * 5);
expect(a.pings).toBe(pingsAtClose);
expect(a.terminated).toBe(false);
expect(adapter.describeStatus().status).toBe('disabled');
} finally {
vi.useRealTimers();
}
});
it('a hot-reload does not let the old socket heartbeat reap the new one (#97 + #208)', async () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
const a = instances[0];
a.simulateOpen();
vi.advanceTimersByTime(INTERVAL); // a's heartbeat has ticked once
// Hot reload (URL change) → base class close() then open(); close() stops
// a's heartbeat proactively before b is created.
await adapter.reload(cfg({ url: 'ws://127.0.0.1:8081/' }));
expect(instances).toHaveLength(2);
const b = instances[1];
b.simulateOpen();
const aPingsAfterReload = a.pings;
// Advance well past a's would-be death window. a's heartbeat was stopped by
// the reload, so it never pings/terminates; b keeps its own healthy loop.
for (let i = 0; i < 6; i++) {
vi.advanceTimersByTime(INTERVAL);
b.simulatePong();
}
// Stale socket's delayed close finally lands — must not disturb b.
a.simulateClose();
vi.advanceTimersByTime(INTERVAL);
b.simulatePong(); // b stays healthy through the stale event
expect(a.pings).toBe(aPingsAfterReload); // a's timer never fired again
expect(a.terminated).toBe(false);
expect(b.terminated).toBe(false);
expect(instances).toHaveLength(2); // no stray reconnect socket
expect(adapter.describeStatus().status).toBe('ok');
} finally {
vi.useRealTimers();
}
});
});
@@ -0,0 +1,148 @@
// Issue #208 (server side): symmetric transport keepalive for the reverse-WS
// SERVER. Each attached client is pinged; a client that goes fully silent for
// maxMissed consecutive intervals is terminated (and drops out of the
// connection set) so a half-open client can't wedge forever. A healthy or
// actively-messaging client must never be reaped — the same false-positive
// guard as the client adapter.
//
// Mock `@snowluma/websocket` (native addon isn't built in a plain checkout),
// mirroring network-bootstrap-meta.test.ts. Timers are faked and driven.
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { FakeWebSocket, FakeWebSocketServer, servers } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { EventEmitter } = require('node:events') as typeof import('node:events');
const servers: FakeWebSocketServer[] = [];
class FakeWebSocket extends EventEmitter {
public readyState = 1; // OPEN
public pings = 0;
public terminated = false;
send(_payload: string, cb?: (err?: Error | null) => void): void { cb?.(null); }
ping(): void { this.pings += 1; }
terminate(): void {
if (this.readyState === 3) return;
this.terminated = true;
this.readyState = 3;
this.emit('close');
}
close(): void { if (this.readyState < 2) this.readyState = 2; }
simulatePong(): void { this.emit('pong', Buffer.alloc(0)); }
simulateMessage(): void { this.emit('message', Buffer.from('{}'), false); }
}
class FakeWebSocketServer extends EventEmitter {
public closed = false;
constructor(_opts: unknown) { super(); servers.push(this); }
close(): void { this.closed = true; }
simulateConnection(socket: FakeWebSocket, request: unknown): void {
this.emit('connection', socket, request);
}
}
return { FakeWebSocket, FakeWebSocketServer, servers };
});
vi.mock('@snowluma/websocket', () => ({
WebSocket: FakeWebSocket,
WebSocketServer: FakeWebSocketServer,
}));
import { WsServerAdapter } from '../src/network/ws-server-adapter';
import type { NetworkAdapterContext } from '../src/network/adapter';
import type { WsServerNetwork } from '../src/types';
const INTERVAL = 30_000;
const MAX_MISSED = 2;
function ctx(): NetworkAdapterContext {
return {
uin: '10001',
api: { processStreamRequest: async () => {} } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
}
function cfg(over: Partial<WsServerNetwork> = {}): WsServerNetwork {
return { enabled: true, host: '0.0.0.0', port: 8080, path: '/', role: 'Universal', ...over } as WsServerNetwork;
}
const REQUEST = { url: '/', headers: {} } as unknown;
function connect(): { adapter: WsServerAdapter; socket: InstanceType<typeof FakeWebSocket> } {
const adapter = new WsServerAdapter('ws', cfg(), ctx());
adapter.open();
const server = servers[servers.length - 1];
server.emit('listening'); // adapter marks itself listening → status 'ok'
const socket = new FakeWebSocket();
server.simulateConnection(socket, REQUEST);
return { adapter, socket };
}
describe('WsServerAdapter — transport heartbeat (issue #208)', () => {
beforeEach(() => { servers.length = 0; });
it('reaps a silent client only after maxMissed intervals, then drops it', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
expect(adapter.describeStatus().detail).toBe('1 个客户端');
vi.advanceTimersByTime(INTERVAL * MAX_MISSED); // tolerated
expect(socket.terminated).toBe(false);
vi.advanceTimersByTime(INTERVAL); // threshold crossed
expect(socket.terminated).toBe(true);
expect(adapter.describeStatus().detail).toBe('0 个客户端');
} finally {
vi.useRealTimers();
}
});
it('never reaps a client that keeps ponging', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
for (let i = 0; i < 10; i++) {
vi.advanceTimersByTime(INTERVAL);
socket.simulatePong();
}
expect(socket.terminated).toBe(false);
expect(adapter.describeStatus().detail).toBe('1 个客户端');
expect(socket.pings).toBeGreaterThan(0);
} finally {
vi.useRealTimers();
}
});
it('treats inbound messages as liveness', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
for (let i = 0; i < 10; i++) {
vi.advanceTimersByTime(INTERVAL);
socket.simulateMessage();
}
expect(socket.terminated).toBe(false);
expect(adapter.describeStatus().detail).toBe('1 个客户端');
} finally {
vi.useRealTimers();
}
});
it('stops all client heartbeats on adapter close — no lingering pings', () => {
vi.useFakeTimers();
try {
const { adapter, socket } = connect();
adapter.close();
const pingsAtClose = socket.pings;
vi.advanceTimersByTime(INTERVAL * 5);
expect(socket.pings).toBe(pingsAtClose);
expect(socket.terminated).toBe(false); // closed cleanly, not reaped
} finally {
vi.useRealTimers();
}
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.11.4",
"version": "1.12.0",
"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).",
+77
View File
@@ -262,3 +262,80 @@ export interface GroupReactNotify {
field13?: pb<13, uint_32>;
groupReactionData?: pb<44, GroupReactionData>;
}
// Forced-offline ("被迫下线") push — SSO cmd
// `trpc.qq_new_tech.status_svc.StatusService.KickNT`. QQ NT's unified offline
// notification (kick / login-elsewhere / risk-control-triggered offline all
// arrive here; the reason is in the strings). Field layout RE'd from
// wrapper.linux.node (log fmt "tips_title:{} tips_content:{}") + Lagrange's
// ServiceKickNTResponse: f4 = tips_title (short title), f3 = tips_content (desc).
export interface KickNTResponse {
uin?: pb<1, uint_32>;
tips?: pb<3, string>; // tips_content — the longer description
title?: pb<4, string>; // tips_title — the short title
}
// Group-name change (Event 0x2DC subType 16, NotifyMessageBody.field13 == 12).
// Rides in `NotifyMessageBody.eventParam` (field 5). Field layout matches
// Lagrange's `GroupNameChange` (RE'd from wrapper.linux.node): only the new
// name at field 2. The operator uid is `NotifyMessageBody.operatorUid` (f21).
export interface GroupNameChange {
name?: pb<2, string>;
}
// Group special-title granted (Event 0x2DC subType 16, NotifyMessageBody.field13
// == 6). Rides in `NotifyMessageBody.eventParam` (field 5). Field layout captured
// on-wire: f2 = the gray-tip template text ("恭喜<{…}>获得群主授予的<{…"text":TITLE…}>头衔"),
// f5 = the member uin who received the title. The title text itself is embedded in
// the last `<{…}>` rich token of f2 (the kernel parses that template into a clean
// string; on the raw wire we parse it ourselves).
export interface GroupSpecialTitleChange {
tipText?: pb<2, string>;
memberUin?: pb<5, uint_32>;
}
// Profile-like ("名片赞") notify — Event 0x210 subType 39, whose body.msgContent
// decodes as this ProfileLikeTip. subType 39 is multiplexed; only inner
// msgType==0 && subType==203 is a like. Field numbers CONFIRMED byte-exact against
// real on-wire captures (detail.txt = "赞了我的资料卡N次", f3=liker uin, f5=nick);
// the like count is parsed from `detail.txt`.
export interface ProfileLikeDetail {
txt?: pb<1, string>;
uin?: pb<3, uint_64>;
nickname?: pb<5, string>;
}
export interface ProfileLikeMsg {
times?: pb<1, int_32>;
time?: pb<2, int_32>;
detail?: pb<3, ProfileLikeDetail>;
}
export interface ProfileLikeSubTip {
msg?: pb<14, ProfileLikeMsg>;
}
export interface ProfileLikeTip {
msgType?: pb<1, int_32>;
subType?: pb<2, int_32>;
content?: pb<203, ProfileLikeSubTip>;
}
// C2C input-status notify — the "对方正在输入…" push. Delivered as a system
// message (msgType 0x210 / subMsgType 0x115) whose `MsgBody.msgContent` carries
// this body. Field layout RE'd from `wrapper.linux.node`
// `aio_input_state_worker.cc::ProcessInputStateNotifySysMsg` (reads f1=fromUid,
// f2=toUid, f3=notifyItem; the item's f4 is the event type).
export interface InputStatusNotifyItem {
field2?: pb<2, uint_32>;
field3?: pb<3, uint_64>;
eventType?: pb<4, uint_32>; // 1 = 正在输入 (typing), 3 = 正在讲话 (recording voice)
field5?: pb<5, uint_32>;
statusText?: pb<6, string>;
}
export interface InputStatusNotify {
fromUid?: pb<1, string>;
toUid?: pb<2, string>;
notifyItem?: pb<3, InputStatusNotifyItem>;
}
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.11.4",
"version": "1.12.0",
"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>'`.",
@@ -28,6 +28,10 @@
"types": "./src/packet-pipeline.ts",
"default": "./src/packet-pipeline.ts"
},
"./kick-nt": {
"types": "./src/kick-nt.ts",
"default": "./src/kick-nt.ts"
},
"./element-builder": {
"types": "./src/element-builder.ts",
"default": "./src/element-builder.ts"
+78 -1
View File
@@ -294,6 +294,77 @@ export interface PttTransResultEvent extends QQEvent {
text: string;
}
/**
* The bot account was forced offline (kicked / logged in elsewhere / risk-control)
* — SSO push `StatusService.KickNT`. Mirrors NapCat's OB11BotOfflineEvent →
* `notice_type:'bot_offline'`. `tag` = short title, `message` = description.
*/
export interface BotOfflineEvent extends QQEvent {
kind: 'bot_offline';
tag: string;
message: string;
}
/**
* A group member's card (群名片) changed — detected from message traffic when
* the sender's live card differs from the cached one (same mechanism as NapCat's
* `parseCardChangedEvent`). Maps to OB11 `notice_type:'group_card'`.
*/
export interface GroupCardChangeEvent extends QQEvent {
kind: 'group_card_change';
groupId: number;
userUin: number;
cardNew: string;
cardOld: string;
}
/**
* A group member was granted a special title (群头衔) — Event 0x2DC subType 16,
* field13 == 6. Maps to OB11 `notice/notify` `sub_type:'title'`.
*/
export interface GroupTitleChangeEvent extends QQEvent {
kind: 'group_title_change';
groupId: number;
userUin: number; // the member who received the title
title: string;
}
/**
* Group name changed (Event 0x2DC subType 16, field13 == 12). Mirrors NapCat's
* OB11GroupNameEvent → `notice/notify` `sub_type:'group_name'`.
*/
export interface GroupNameChangeEvent extends QQEvent {
kind: 'group_name_change';
groupId: number;
operatorUin: number; // who renamed the group
name: string; // the new group name
}
/**
* Someone liked the bot's profile card ("名片赞") — Event 0x210 subType 39,
* inner ProfileLikeTip msgType 0 / subType 203. Mirrors NapCat's
* OB11ProfileLikeEvent → `notice/notify` `sub_type:'profile_like'`.
*/
export interface FriendProfileLikeEvent extends QQEvent {
kind: 'friend_profile_like';
operatorUin: number; // who liked
operatorNick: string;
times: number; // like count from this event
}
/**
* C2C "对方正在输入…" input-status push (Event 0x210 subType 0x115 / 277).
* `eventType` 1 = typing, 3 = recording a voice message. Mirrors NapCat's
* `onInputStatusPush` → OB11 `notice/notify` `sub_type:'input_status'`.
*/
export interface FriendInputStatusEvent extends QQEvent {
kind: 'friend_input_status';
userUin: number; // the peer whose input status changed (the typer)
userUid: string;
eventType: number; // 1 = 正在输入, 3 = 正在讲话(录音)
statusText: string;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -312,4 +383,10 @@ export type QQEventVariant =
| GroupFileUploadEvent
| FriendAddEvent
| GroupMsgEmojiLikeEvent
| PttTransResultEvent;
| PttTransResultEvent
| FriendInputStatusEvent
| GroupNameChangeEvent
| GroupCardChangeEvent
| GroupTitleChangeEvent
| FriendProfileLikeEvent
| BotOfflineEvent;
+33
View File
@@ -0,0 +1,33 @@
// Forced-offline push. QQ NT tells a client it was kicked / logged in elsewhere /
// dropped for risk-control via the SSO command
// `trpc.qq_new_tech.status_svc.StatusService.KickNT`, whose body is a
// `KickNTResponse`. We surface it as a `bot_offline` event (NapCat parity).
//
// The push arrives on the same StatusService channel SnowLuma already receives
// (e.g. StatusService.SsoHeartBeat), so it just needs its own cmd handler.
// Command + field layout RE-confirmed against wrapper.linux.node + Lagrange's
// KickNTService/ServiceKickNTResponse.
import { protobuf_decode } from '@snowluma/proton';
import type { KickNTResponse } from '@snowluma/proto-defs/notify';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { IdentityService } from './identity-service';
import type { QQEventVariant } from './events';
export const KICK_NT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.KickNT';
type BotOfflineEvent = Extract<QQEventVariant, { kind: 'bot_offline' }>;
export function parseKickNT(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
const resp = protobuf_decode<KickNTResponse>(pkt.body);
if (!resp) return [];
const ev: BotOfflineEvent = {
kind: 'bot_offline',
// KickNT carries no timestamp — stamp with receive time.
time: Math.floor(Date.now() / 1000),
selfUin: Number(pkt.uin) || Number(identity.uin) || 0,
tag: resp.title ?? '', // tips_title — the short title
message: resp.tips ?? '', // tips_content — the description / reason
};
return [ev];
}
@@ -10,7 +10,9 @@ import type {
FriendRecall,
FriendRequest,
GeneralGrayTipInfo,
InputStatusNotify,
NewFriend,
ProfileLikeTip,
} from '@snowluma/proto-defs/notify';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import type { MsgPushContext } from '../context';
@@ -23,6 +25,8 @@ import {
import type { MsgPushDecoder } from '../registry';
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
type FriendInputStatusEvent = Extract<QQEventVariant, { kind: 'friend_input_status' }>;
type FriendProfileLikeEvent = Extract<QQEventVariant, { kind: 'friend_profile_like' }>;
const unknownLog = createLogger('MsgPush.Unknown');
@@ -37,6 +41,8 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
case Event0x210SubType.FriendRecallSelfNotice:
return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx);
case Event0x210SubType.ProfileLikeNotice: return decodeProfileLike(ctx);
// 179 + 226 both carry the NewFriend payload — see enum comment.
case Event0x210SubType.NewFriendNotice:
case Event0x210SubType.NewFriendNoticeAlt:
@@ -128,6 +134,60 @@ function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
return [ev];
}
// C2C "对方正在输入…" input-status push. Body (`InputStatusNotify`) rides in
// `body.msgContent` (= ctx.content). Layout + event-type semantics RE'd from
// `aio_input_state_worker.cc::ProcessInputStateNotifySysMsg`: the notify item's
// field 4 is the event type (1 = typing, 3 = recording voice). The client
// synthesises the status text from that type, so we do the same for OneBot
// parity (NapCat's `onInputStatusPush` → `notice/notify` `input_status`).
function decodeInputStatus(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<InputStatusNotify>(ctx.content);
const fromUid = notify?.fromUid ?? '';
if (!fromUid) return [];
const eventType = notify.notifyItem?.eventType ?? 1;
const ev: FriendInputStatusEvent = {
kind: 'friend_input_status',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, fromUid, ctx.fromUin),
userUid: fromUid,
eventType,
statusText: inputStatusText(eventType),
};
return [ev];
}
// The client's own strings (wrapper.linux.node @0xB8FFE0 / @0xB90000).
function inputStatusText(eventType: number): string {
return eventType === 3 ? '对方正在讲话...' : '对方正在输入...';
}
// subType 39 is multiplexed; body.msgContent decodes as ProfileLikeTip and is a
// profile-like ("名片赞") only when inner msgType==0 && subType==203. Other 39
// variants (multi-device sync etc.) decode to a non-matching tip → dropped.
// `times` is the like count parsed out of `detail.txt` ("赞了我的资料卡N次").
// Field layout confirmed byte-exact against real on-wire captures.
function decodeProfileLike(ctx: MsgPushContext): QQEventVariant[] {
const tip = protobuf_decode<ProfileLikeTip>(ctx.content);
// msgType 0 is the proto default → omitted on the wire → decodes as undefined,
// so treat missing as 0 (matches NapCat's `msgType !== 0` check).
if (!tip || (tip.msgType ?? 0) !== 0 || (tip.subType ?? 0) !== 203) return [];
const msg = tip.content?.msg;
const detail = msg?.detail;
const operatorUin = Number(detail?.uin ?? 0n);
if (!operatorUin) return [];
const times = Number.parseInt((detail?.txt ?? '').match(/\d+/)?.[0] ?? '0', 10) || 0;
const ev: FriendProfileLikeEvent = {
kind: 'friend_profile_like',
time: msg?.time || ctx.head.timestamp,
selfUin: ctx.selfUin,
operatorUin,
operatorNick: detail?.nickname ?? '',
times,
};
return [ev];
}
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
@@ -4,12 +4,16 @@ import type {
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupNameChangeEvent,
GroupTitleChangeEvent,
GroupPokeEvent,
GroupRecallEvent,
QQEventVariant,
} from '../../events';
import type {
GroupMute,
GroupNameChange,
GroupSpecialTitleChange,
GroupReactNotify,
NotifyMessageBody,
} from '@snowluma/proto-defs/notify';
@@ -28,7 +32,7 @@ const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeSubType16(ctx);
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
@@ -123,6 +127,84 @@ const GROUP_REACT_PREFIX_BYTES = 7;
// for other notify variants, only 35 means "emoji react". Anything
// else falls through to MsgPush.Unknown for protocol-drift visibility.
const GROUP_REACT_DISCRIMINATOR = 35;
// Event 0x2DC subType 16 multiplexes several group notices, discriminated by
// `NotifyMessageBody.field13`. RE cross-ref (Lagrange Event0x2DCSubType16Field13,
// itself RE'd from wrapper.linux.node): 6=special title, 12=name change, 23=todo,
// 35=emoji reaction. We peek field13 off the shared NotifyMessageBody, then branch.
const SUBTYPE16_SPECIAL_TITLE = 6;
const SUBTYPE16_GROUP_NAME_CHANGE = 12;
function decodeSubType16(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const field13 = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES))?.field13 ?? 0;
switch (field13) {
case SUBTYPE16_SPECIAL_TITLE: return decodeGroupTitle(ctx);
case SUBTYPE16_GROUP_NAME_CHANGE: return decodeGroupName(ctx);
case GROUP_REACT_DISCRIMINATOR: return decodeGroupMsgEmojiLike(ctx);
default:
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d', field13);
return [];
}
}
// field13 == 6: a member was granted a special title. eventParam carries the
// member uin (f5) + a gray-tip template string (f2); the title text is the last
// `<{"…","text":TITLE,…}>` rich token in that string (on-wire captured shape —
// the kernel resolves the template to a clean string, we parse it here).
function decodeGroupTitle(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES));
const param = notify?.eventParam
? protobuf_decode<GroupSpecialTitleChange>(notify.eventParam)
: undefined;
const userUin = param?.memberUin ?? 0;
const title = extractTitleFromTip(param?.tipText ?? '');
if (!userUin || !title) return [];
const ev: GroupTitleChangeEvent = {
kind: 'group_title_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify?.groupUin ?? 0,
userUin,
title,
};
return [ev];
}
// The tip text is "恭喜<{member}>获得群主授予的<{…"text":TITLE…}>头衔" — the title is
// the `text` of the LAST `<{…}>` rich token (the one just before "头衔"). Tokens
// are flat JSON with no `<`/`>` inside, so a non-greedy scan is safe.
function extractTitleFromTip(text: string): string {
const tokens = text.match(/<\{[^<>]*\}>/g);
if (!tokens || tokens.length === 0) return '';
const last = tokens[tokens.length - 1];
try {
const parsed = JSON.parse(last.slice(1, -1)) as { text?: string };
return parsed.text ?? '';
} catch {
return '';
}
}
// field13 == 12: group renamed. New name is nested in `eventParam` as a
// `GroupNameChange` (field 2); operator is `NotifyMessageBody.operatorUid`.
function decodeGroupName(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES));
const name = notify?.eventParam ? (protobuf_decode<GroupNameChange>(notify.eventParam)?.name ?? '') : '';
if (!name) return [];
const groupId = notify?.groupUin ?? 0;
const ev: GroupNameChangeEvent = {
kind: 'group_name_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
// Operator is a group member → resolves from the roster. Fall back to 0
// (not ctx.fromUin, which on a 0x2DC push is the group id) so an
// unresolved operator never surfaces the group id as user_id.
operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? '', 0),
name,
};
return [ev];
}
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
+17
View File
@@ -67,6 +67,23 @@ export enum Event0x210SubType {
*/
NewFriendNotice = 179,
NewFriendNoticeAlt = 226,
/**
* Multiplexed subType (Lagrange calls it FriendDeleteOrPinChanged=39). One of
* its variants is the profile-like ("名片赞") push: body.msgContent decodes as
* `ProfileLikeTip` and is a like only when inner msgType==0 && subType==203.
* NapCat routes 528/39 → parseLikeEvent (`api/msg.ts:1547`); other 39 variants
* (multi-device sync etc.) fall through.
*/
ProfileLikeNotice = 39,
/**
* C2C input-status notify — the "对方正在输入…" push. subMsgType 0x115 (277).
* RE-confirmed against `wrapper.linux.node`
* `aio_input_state_worker.cc::IsInputStateNotifySysMsg`, which matches exactly
* `(msg_type ^ 0x210) | (sub_msg_type ^ 0x115) == 0`. The payload
* (`InputStatusNotify`) rides in `body.msgContent`. Mirrors NapCat's
* `onInputStatusPush`.
*/
InputStatusNotice = 277,
/**
* Group-app state push (troop shortcut bar / discussion app).
*
+31
View File
@@ -104,7 +104,12 @@ export class IncomingPacketPipeline {
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
} else {
// Snapshot the sender's cached group card BEFORE dispatch — the
// side-effects inside finishDispatch self-heal (overwrite) it, so we
// must read it first to detect a real change and surface group_card.
const cardBefore = this.groupCardBefore(event);
this.finishDispatch(event);
this.emitGroupCardChange(event, cardBefore);
}
}
} catch (e) {
@@ -119,6 +124,32 @@ export class IncomingPacketPipeline {
void this.deps.events.emit(event);
}
/** The sender's cached group card just before this event is dispatched (its
* side-effects will overwrite the cache). Only meaningful for group_message. */
private groupCardBefore(event: QQEventVariant): string | undefined {
if (event.kind !== 'group_message') return undefined;
return this.deps.identity.findGroupMember(event.groupId, event.senderUin)?.card;
}
/** Surface a `group_card_change` when a KNOWN member's card actually changed —
* mirrors NapCat's `parseCardChangedEvent`. Requires a non-empty prior card
* (`cardBefore`) that differs from a non-empty new one, so a cold/unknown
* cache never fabricates a change on first contact. */
private emitGroupCardChange(event: QQEventVariant, cardBefore: string | undefined): void {
if (event.kind !== 'group_message') return;
const cardNew = event.senderCard ?? '';
if (!cardBefore || !cardNew || cardBefore === cardNew) return;
this.finishDispatch({
kind: 'group_card_change',
time: event.time,
selfUin: event.selfUin,
groupId: event.groupId,
userUin: event.senderUin,
cardNew,
cardOld: cardBefore,
});
}
/**
* Common dispatch tail shared by the sync path and the two async enrichment
* paths: run side effects, log the event, then emit it. `alreadyRefreshed` is
+41
View File
@@ -0,0 +1,41 @@
// StatusService.KickNT (forced-offline push) → bot_offline event.
// Command + field layout RE-confirmed against wrapper.linux.node + Lagrange's
// KickNTService/ServiceKickNTResponse (f4 = tips_title, f3 = tips_content).
import { describe, expect, it } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { parseKickNT, KICK_NT_CMD } from '@snowluma/protocol/kick-nt';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { KickNTResponse } from '@snowluma/proto-defs/notify';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { QQEventVariant } from '@snowluma/protocol/events';
type BotOfflineEvent = Extract<QQEventVariant, { kind: 'bot_offline' }>;
describe('parseKickNT (StatusService.KickNT → bot_offline)', () => {
const identity = IdentityService.memory('3433035623');
function pkt(resp: KickNTResponse, uin = '3433035623'): PacketInfo {
return {
pid: 1, uin, serviceCmd: KICK_NT_CMD, seqId: 1, retCode: 0,
fromClient: false, body: protobuf_encode<KickNTResponse>(resp),
};
}
it('emits bot_offline with tag=title (f4) and message=tips (f3)', () => {
const [ev] = parseKickNT(
pkt({ uin: 3433035623, title: '你已离线', tips: '你的账号在其他设备登录' }),
identity,
) as BotOfflineEvent[];
expect(ev.kind).toBe('bot_offline');
expect(ev.selfUin).toBe(3433035623);
expect(ev.tag).toBe('你已离线');
expect(ev.message).toBe('你的账号在其他设备登录');
});
it('falls back to the identity uin when the packet uin is missing', () => {
const [ev] = parseKickNT(pkt({ title: 't', tips: 'm' }, ''), identity) as BotOfflineEvent[];
expect(ev.selfUin).toBe(3433035623);
});
});
@@ -13,6 +13,7 @@ import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import type { PacketInfo } from '@snowluma/common/protocol-types';
function makePipeline(opts: {
@@ -346,3 +347,70 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => {
expect(identity.findGroupMember(9999, 222)).toBeNull();
});
});
describe('IncomingPacketPipeline / group_card_change from message traffic', () => {
const GROUP = 123456789;
function member(card: string): GroupMemberInfo {
return {
uin: 22222, uid: 'u_member', nickname: 'nick', card, role: 'member',
level: 0, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0,
};
}
function setup(cachedCard: string) {
const identity = IdentityService.memory('10001');
identity.rememberGroups([{
groupId: GROUP, groupName: 'g', remark: '', memberCount: 1, memberMax: 500,
members: new Map([[22222, member(cachedCard)]]),
} as QQGroupInfo]);
const events = new BridgeEventBus();
const pipeline = new IncomingPacketPipeline({
identity, events,
refreshMemberCache: vi.fn(async () => false),
resolveStrangerProfile: vi.fn(async () => null),
resolveGroupJoinRequest: vi.fn(async () => null),
});
const captured: QQEventVariant[] = [];
events.onAny((e) => captured.push(e as QQEventVariant));
return { pipeline, captured };
}
function groupMsg(card: string): QQEventVariant {
return {
kind: 'group_message', time: 1700000000, selfUin: 10001, groupId: GROUP,
senderUin: 22222, senderNick: 'nick', senderCard: card, senderRole: 'member',
msgSeq: 1, msgId: 1, elements: [],
} as QQEventVariant;
}
const pkt = (): PacketInfo => ({
pid: 1, uin: '10001', serviceCmd: 'test.cmd', seqId: 1, retCode: 0,
fromClient: false, body: new Uint8Array(),
});
it('emits group_card_change when a known member card changes', () => {
const { pipeline, captured } = setup('OldCard');
pipeline.registerCmd('test.cmd', () => [groupMsg('NewCard')]);
pipeline.process(pkt());
const ev = captured.find((e) => e.kind === 'group_card_change');
expect(ev).toBeTruthy();
expect((ev as Extract<QQEventVariant, { kind: 'group_card_change' }>).cardOld).toBe('OldCard');
expect((ev as Extract<QQEventVariant, { kind: 'group_card_change' }>).cardNew).toBe('NewCard');
expect((ev as Extract<QQEventVariant, { kind: 'group_card_change' }>).userUin).toBe(22222);
});
it('does NOT emit when the card is unchanged', () => {
const { pipeline, captured } = setup('SameCard');
pipeline.registerCmd('test.cmd', () => [groupMsg('SameCard')]);
pipeline.process(pkt());
expect(captured.some((e) => e.kind === 'group_card_change')).toBe(false);
});
it('does NOT fabricate a change on first contact (no cached card)', () => {
const { pipeline, captured } = setup('');
pipeline.registerCmd('test.cmd', () => [groupMsg('SomeCard')]);
pipeline.process(pkt());
expect(captured.some((e) => e.kind === 'group_card_change')).toBe(false);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.11.4",
"version": "1.12.0",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.11.4",
"version": "1.12.0",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.11.4",
"version": "1.12.0",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.11.4",
"version": "1.12.0",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.11.4",
"version": "1.12.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
+2 -1
View File
@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.11.4",
"version": "1.12.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -20,6 +20,7 @@
"@radix-ui/react-slot": "^1.1.3",
"@radix-ui/react-tooltip": "^1.1.9",
"@tanstack/react-router": "^1.169.2",
"@tanstack/react-virtual": "^3.14.5",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"gridstack": "^12.6.0",
@@ -25,12 +25,15 @@ function IconBtn({ onClick, title, children }: { onClick: () => void; title: str
);
}
function StatusPill({ status }: { status: 'open' | 'reconnecting' | 'closed' }) {
const map = {
open: { dot: 'bg-emerald-500', label: '已连接', glow: 'shadow-[0_0_0_3px_rgb(16_185_129/0.15)]' },
reconnecting: { dot: 'bg-amber-500', label: '重连中', glow: 'shadow-[0_0_0_3px_rgb(245_158_11/0.15)]' },
closed: { dot: 'bg-muted-foreground/50', label: '未连接', glow: '' },
}[status];
function StatusPill({ status, paused }: { status: 'open' | 'reconnecting' | 'closed'; paused?: boolean }) {
// A deliberate pause reads as "已暂停", distinct from an unwanted disconnect.
const map = paused
? { dot: 'bg-muted-foreground/50', label: '已暂停', glow: '' }
: {
open: { dot: 'bg-emerald-500', label: '已连接', glow: 'shadow-[0_0_0_3px_rgb(16_185_129/0.15)]' },
reconnecting: { dot: 'bg-amber-500', label: '重连中', glow: 'shadow-[0_0_0_3px_rgb(245_158_11/0.15)]' },
closed: { dot: 'bg-muted-foreground/50', label: '未连接', glow: '' },
}[status];
return (
<div className="inline-flex items-center gap-2 rounded-full border border-border/60 bg-card/70 px-3 py-1.5 text-xs font-medium backdrop-blur-sm">
<span className={cn('h-2 w-2 rounded-full', map.dot, map.glow)} />
@@ -94,14 +97,18 @@ export function LiveActivity() {
const [status, setStatus] = useState<'open' | 'reconnecting' | 'closed'>('closed');
const [kindFilter, setKindFilter] = useState<'all' | 'event' | 'action'>('all');
const [query, setQuery] = useState('');
const pausedRef = useRef(paused);
useEffect(() => { pausedRef.current = paused; }, [paused]);
const idRef = useRef(0);
// Pausing truly drops the EventSource instead of connecting-and-discarding:
// `paused` is an effect dependency, so it closes the stream on pause and
// reopens it on resume. (The always-on-across-tabs behaviour is intentional —
// debug-page keeps this mounted so actions fired from other tabs still land in
// the feed — so only an explicit pause severs the connection.)
useEffect(() => {
if (paused) return;
const off = api.debug.stream(
(m) => {
if (m.kind === 'ready' || pausedRef.current) return;
if (m.kind === 'ready') return;
setRows((prev) => {
// Precompute the search haystack once at enqueue, so filtering never
// re-stringifies every row on each keystroke.
@@ -112,7 +119,7 @@ export function LiveActivity() {
(s) => setStatus(s),
);
return off;
}, [api]);
}, [paused, api]);
const visible = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -149,7 +156,7 @@ export function LiveActivity() {
<RadioTower className="h-[18px] w-[18px] text-primary" />
<h2 className="text-[15px] font-semibold tracking-tight">实时活动</h2>
<span className="text-xs text-muted-foreground tabular-nums">{visible.length}</span>
<StatusPill status={status} />
<StatusPill status={status} paused={paused} />
</div>
<div className="flex items-center gap-2">
<Segmented value={kindFilter} onChange={setKindFilter}
@@ -140,27 +140,37 @@ export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0 }:
{segments.map((s, i) => (
<div
key={s._id}
draggable
// stopPropagation makes the nested-builder boundary explicit: a child
// row's drag never reaches the parent node row.
onDragStart={(e) => { e.stopPropagation(); setDragFrom(i); }}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => { e.stopPropagation(); if (dragFrom !== null) move(dragFrom, i); setDragFrom(null); }}
onDragEnd={() => setDragFrom(null)}
className="flex items-start gap-2 rounded-xl border border-border/50 bg-card/60 p-2"
className="rounded-xl border border-border/50 bg-card/60 p-2"
>
<GripVertical className="mt-1 h-4 w-4 shrink-0 cursor-grab text-muted-foreground/50" />
<div className="min-w-0 flex-1">
<div className="mb-1 flex items-center justify-between">
<span className="text-[11px] font-semibold text-muted-foreground">{LABELS[s.k]}</span>
<div className="flex items-center gap-0.5">
<button type="button" onClick={() => move(i, i - 1)} disabled={i === 0} className="rounded px-1 text-muted-foreground hover:bg-muted disabled:opacity-30" title="上移">↑</button>
<button type="button" onClick={() => move(i, i + 1)} disabled={i === segments.length - 1} className="rounded px-1 text-muted-foreground hover:bg-muted disabled:opacity-30" title="下移">↓</button>
<button type="button" onClick={() => remove(i)} className="rounded p-0.5 text-muted-foreground hover:text-destructive" title="删除"><Trash2 className="h-3.5 w-3.5" /></button>
</div>
{/* Drag is scoped to the grip handle only — making the whole row
draggable hijacked text selection inside the segment inputs (you
couldn't select part of a pasted URL without dragging the card).
The row stays the drop target; its body is fully selectable. */}
<div className="mb-1 flex items-center justify-between gap-2">
<span className="flex min-w-0 items-center gap-1.5">
<span
draggable
// stopPropagation keeps a nested (forward-node) builder's drag
// from reaching the parent row; onDragEnd lives here because the
// grip — not the row — is now the drag source.
onDragStart={(e) => { e.stopPropagation(); setDragFrom(i); }}
onDragEnd={() => setDragFrom(null)}
title="拖动此处排序" aria-label="拖动排序"
className="flex shrink-0 cursor-grab rounded-md p-0.5 text-muted-foreground/50 transition-colors hover:bg-muted hover:text-foreground active:cursor-grabbing"
>
<GripVertical className="h-3.5 w-3.5" />
</span>
<span className="truncate text-[11px] font-semibold text-muted-foreground">{LABELS[s.k]}</span>
</span>
<div className="flex shrink-0 items-center gap-0.5">
<button type="button" onClick={() => move(i, i - 1)} disabled={i === 0} className="rounded px-1 text-muted-foreground hover:bg-muted disabled:opacity-30" title="上移">↑</button>
<button type="button" onClick={() => move(i, i + 1)} disabled={i === segments.length - 1} className="rounded px-1 text-muted-foreground hover:bg-muted disabled:opacity-30" title="下移">↓</button>
<button type="button" onClick={() => remove(i)} className="rounded p-0.5 text-muted-foreground hover:text-destructive" title="删除"><Trash2 className="h-3.5 w-3.5" /></button>
</div>
<SegmentEditor seg={s} onChange={(n) => patch(i, n)} uin={uin} groupId={groupId} depth={depth} />
</div>
<SegmentEditor seg={s} onChange={(n) => patch(i, n)} uin={uin} groupId={groupId} depth={depth} />
</div>
))}
+19 -2
View File
@@ -89,6 +89,10 @@ export function LoginWaves() {
let lines: Pt[][] = [];
let paths: SVGPathElement[] = [];
let raf = 0;
// Honour reduced-motion (the OS setting or the app's own data-reduce-motion
// toggle): draw a single static frame instead of running the rAF loop. #185.
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)');
const reduced = () => prefersReduced.matches || document.documentElement.dataset.reduceMotion === '1';
const setSize = () => {
bounding = host.getBoundingClientRect();
@@ -143,7 +147,7 @@ export function LoginWaves() {
const t = e.touches[0];
if (t) updateMouse(t.clientX, t.clientY);
};
const onResize = () => { setSize(); setLines(); };
const onResize = () => { setSize(); setLines(); if (reduced()) { movePoints(0); drawLines(); } };
const movePoints = (time: number) => {
lines.forEach((points) => {
@@ -213,10 +217,23 @@ export function LoginWaves() {
window.addEventListener('resize', onResize);
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('touchmove', onTouchMove, { passive: true });
raf = requestAnimationFrame(tick);
// Animate only when motion is allowed; otherwise paint one static frame.
// React live to changes of the OS reduced-motion preference.
const applyMotion = () => {
if (reduced()) {
if (raf) { cancelAnimationFrame(raf); raf = 0; }
movePoints(0);
drawLines();
} else if (!raf) {
raf = requestAnimationFrame(tick);
}
};
prefersReduced.addEventListener('change', applyMotion);
applyMotion();
return () => {
cancelAnimationFrame(raf);
prefersReduced.removeEventListener('change', applyMotion);
window.removeEventListener('resize', onResize);
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('touchmove', onTouchMove);
@@ -18,7 +18,12 @@ export function DeliveriesWidget() {
useEffect(() => {
let active = true;
const pull = () =>
let inFlight = false;
const pull = () => {
// Skip while the tab is backgrounded, or if a request is still in flight
// (a slow endpoint must not stack overlapping polls). #185.
if (inFlight || document.hidden) return;
inFlight = true;
api.notifications
.recent(50)
.then((r) => {
@@ -26,12 +31,19 @@ export function DeliveriesWidget() {
})
.catch(() => {
if (active) setRecords((prev) => prev ?? []);
});
})
.finally(() => { inFlight = false; });
};
void pull();
const id = window.setInterval(() => void pull(), POLL_MS);
// The interval keeps firing but no-ops while hidden, so refresh immediately
// when the tab becomes visible again to shed any staleness.
const onVisible = () => { if (!document.hidden) pull(); };
document.addEventListener('visibilitychange', onVisible);
return () => {
active = false;
window.clearInterval(id);
document.removeEventListener('visibilitychange', onVisible);
};
}, [api]);
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { motion, AnimatePresence } from 'motion/react';
import { ArrowDownToLine, Download, Filter, Highlighter, Inbox, Pause, Plus, RefreshCw, Search, SearchX, SlidersHorizontal, Trash2, WrapText, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -91,7 +92,7 @@ function ToolButton({ label, onClick, children, active, danger, disabled }: Tool
export function LogsPage() {
const api = useApi();
const { formatClock, appearance } = useTheme();
const { formatClock } = useTheme();
const { pages, setPages } = useLayout();
const prefs = pages.logs;
@@ -104,7 +105,7 @@ export function LogsPage() {
const [showOptions, setShowOptions] = useState(false);
const [newKeyword, setNewKeyword] = useState('');
const [newColor, setNewColor] = useState(HIGHLIGHT_COLORS[0].id);
const endRef = useRef<HTMLDivElement | null>(null);
const scrollRef = useRef<HTMLDivElement | null>(null);
// maxLines is read through a ref so changing it doesn't re-subscribe the SSE.
const maxLines = prefs.maxLines;
@@ -179,11 +180,6 @@ export function LogsPage() {
};
}, [api]);
useEffect(() => {
if (!prefs.autoScroll) return;
endRef.current?.scrollIntoView({ block: 'end' });
}, [logs, prefs.autoScroll]);
const filtered = useMemo(() => {
const f = filter.trim().toLowerCase();
const capped = logs.slice(-maxLines);
@@ -199,6 +195,40 @@ export function LogsPage() {
});
}, [logs, filter, enabled, maxLines]);
// Virtualize the log rows: only the visible window (+overscan) is mounted, so
// the DOM stays at a few dozen nodes regardless of how many lines the view
// holds. Rows are dynamically measured (measureElement) so wrap mode's
// variable-height lines are handled without a fixed row-height assumption.
const rowVirtualizer = useVirtualizer({
count: filtered.length,
getScrollElement: () => scrollRef.current,
estimateSize: () => 28,
overscan: 12,
// Key the size cache by row id, not index: the list is front-dropped at the
// maxLines cap, so every surviving row's index shifts down each flush. Keying
// by id keeps each measured height with its content (and matches the React
// key), avoiding a one-frame height mis-attribution on off-screen rows.
getItemKey: (index) => filtered[index]?.id ?? index,
});
// Toggling wrap changes every row's height — force a clean re-measure so the
// cached sizes don't leave gaps/overlaps.
useEffect(() => { rowVirtualizer.measure(); }, [prefs.wrap, rowVirtualizer]);
// Follow the tail while auto-scroll is on. Re-run on anything that changes the
// visible set or row heights (new logs, filter/level/maxLines → filtered.length,
// wrap → heights), not just new logs. Freshly-appended rows still carry the
// estimate on this pass, so a second pin on the next frame (after ResizeObserver
// measures them) reaches the true bottom in wrap mode.
useEffect(() => {
if (!prefs.autoScroll || filtered.length === 0) return;
const last = filtered.length - 1;
rowVirtualizer.scrollToIndex(last, { align: 'end' });
const raf = requestAnimationFrame(() => rowVirtualizer.scrollToIndex(last, { align: 'end' }));
return () => cancelAnimationFrame(raf);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [logs, filtered.length, prefs.autoScroll, prefs.wrap]);
// Any hand edit to the bundled prefs drops the active preset to 'custom'.
const toggleLevel = (lv: LogLevel) => {
const next = new Set(enabled);
@@ -497,17 +527,18 @@ export function LogsPage() {
{/* ── Log stream ──────────────────────────────────────────── */}
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
<div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-muted/20">
<ScrollArea className="min-h-0 flex-1" viewportClassName="[&>div]:!block">
{/* Column header lives OUTSIDE the scroll viewport so the virtualizer's
scroll element contains only the rows (no sticky-offset math). */}
{filtered.length > 0 && (
<div className="hidden items-center gap-3 border-b border-border/60 bg-card/60 px-3 py-2 font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 sm:flex">
<span className="w-[104px] shrink-0">时间</span>
<span className="w-[76px] shrink-0">级别</span>
<span className="w-28 shrink-0">模块</span>
<span className="flex-1">消息</span>
</div>
)}
<ScrollArea viewportRef={scrollRef} className="min-h-0 flex-1" viewportClassName="[&>div]:!block">
<div className="font-mono text-xs">
{filtered.length > 0 && (
<div className="sticky top-0 z-10 hidden items-center gap-3 border-b border-border/60 bg-card/75 px-3 py-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 backdrop-blur-md sm:flex">
<span className="w-[104px] shrink-0">时间</span>
<span className="w-[76px] shrink-0">级别</span>
<span className="w-28 shrink-0">模块</span>
<span className="flex-1">消息</span>
</div>
)}
{filtered.length === 0 ? (
<div className="flex min-h-60 flex-col items-center justify-center gap-3 px-4 py-10 text-center font-sans text-muted-foreground">
{logs.length === 0 ? (
@@ -524,17 +555,21 @@ export function LogsPage() {
)}
</div>
) : (
<div className="divide-y divide-border/30">
{filtered.map((log) => {
<div className="relative w-full" style={{ height: rowVirtualizer.getTotalSize() }}>
{rowVirtualizer.getVirtualItems().map((vRow) => {
const log = filtered[vRow.index];
if (!log) return null; // guard a transient count/measurement skew
const hl = matchHighlight(log.message, prefs.highlightRules);
return (
<motion.div
<div
key={log.id}
initial={appearance.disableMotion ? false : { opacity: 0 }}
animate={{ opacity: 1 }}
transition={appearance.disableMotion ? { duration: 0 } : { duration: 0.12 }}
className="flex flex-col gap-0.5 px-3 py-1.5 transition-colors hover:bg-accent/40 sm:flex-row sm:items-start sm:gap-3 sm:py-1"
style={hl ? { boxShadow: `inset 3px 0 0 ${hl}`, backgroundColor: `color-mix(in oklab, ${hl} 8%, transparent)` } : undefined}
data-index={vRow.index}
ref={rowVirtualizer.measureElement}
className="absolute left-0 top-0 flex w-full flex-col gap-0.5 border-b border-border/30 px-3 py-1.5 transition-colors hover:bg-accent/40 sm:flex-row sm:items-start sm:gap-3 sm:py-1"
style={{
transform: `translateY(${vRow.start}px)`,
...(hl ? { boxShadow: `inset 3px 0 0 ${hl}`, backgroundColor: `color-mix(in oklab, ${hl} 8%, transparent)` } : {}),
}}
>
<div className="flex items-center gap-3 sm:contents">
<span className="w-[104px] shrink-0 tabular-nums text-muted-foreground">{formatClock(log.time)}</span>
@@ -553,12 +588,11 @@ export function LogsPage() {
)}
{log.message}
</span>
</motion.div>
</div>
);
})}
</div>
)}
<div ref={endRef} />
</div>
</ScrollArea>
</div>
@@ -263,6 +263,12 @@ export function ProcessesPage() {
processName={probeDialog.name}
open={!!probeDialog}
onOpenChange={(open) => !open && setProbeDialog(null)}
onLoad={() => {
if (probeDialog) {
setConfirm({ kind: 'load', pid: probeDialog.pid, name: probeDialog.name });
setProbeDialog(null);
}
}}
/>
)}
</div>
@@ -25,13 +25,14 @@ interface ProcessProbeDialogProps {
processName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onLoad?: () => void;
}
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
}
export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: ProcessProbeDialogProps) {
export function ProcessProbeDialog({ pid, processName, open, onOpenChange, onLoad }: ProcessProbeDialogProps) {
const api = useApi();
const [loading, setLoading] = useState(false);
const [info, setInfo] = useState<QqPortLoginInfo | null>(null);
@@ -127,6 +128,11 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: Pro
<Button variant="outline" size="sm" onClick={() => onOpenChange(false)}>
关闭
</Button>
{!loading && info?.loggedIn && onLoad && (
<Button size="sm" onClick={onLoad}>
加载
</Button>
)}
{!loading && (
<Button size="sm" onClick={probe}>
<Eye className="size-3.5" /> 重新探测
@@ -4,16 +4,20 @@ import { cn } from '@/lib/utils';
interface ScrollAreaProps extends React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> {
viewportClassName?: string;
/** Ref to the scrollable viewport element — needed to drive a virtualizer
* (TanStack Virtual's getScrollElement) off the actual scroll container. */
viewportRef?: React.Ref<HTMLDivElement>;
}
const ScrollArea = React.forwardRef<React.ElementRef<typeof ScrollAreaPrimitive.Root>, ScrollAreaProps>(
({ className, children, viewportClassName, ...props }, ref) => (
({ className, children, viewportClassName, viewportRef, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn('relative overflow-hidden', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
ref={viewportRef}
className={cn('size-full rounded-[inherit] [&>div]:!block', viewportClassName)}
>
{children}
+67 -3
View File
@@ -42,6 +42,13 @@ class HttpApiClient implements ApiClient {
private currentToken: string | null;
private onUnauthorized?: () => void;
// Shared, ref-counted /api/logs/stream: a single EventSource fans out to every
// subscriber (any number of dashboard alert widgets + the log viewer) instead
// of opening one connection each. See openLogStream.
private logSubscribers = new Set<LogsStreamOptions>();
private logStreamDispose: (() => void) | null = null;
private lastLogStatus: StreamStatus = 'closed';
// namespaced surfaces are bound up-front so callers can destructure
readonly processes: ApiClient['processes'];
readonly config: ApiClient['config'];
@@ -268,8 +275,12 @@ class HttpApiClient implements ApiClient {
// ---------- token management ----------
private setToken(token: string | null): void {
const changed = this.currentToken !== token;
this.currentToken = token;
this.tokenStore.save(token);
// The shared log stream URL carries the token — rebuild it on any change so
// a re-login doesn't leave subscribers on a stale-token connection (#185).
if (changed) this.reopenSharedLogStream();
}
// ---------- auth ----------
@@ -394,10 +405,63 @@ class HttpApiClient implements ApiClient {
}
private openLogStream(options: LogsStreamOptions): () => void {
return this.openSseChannel<LogEntry | { type: string }>('/api/logs/stream', (parsed) => {
this.logSubscribers.add(options);
if (this.logStreamDispose) {
// A late subscriber joins the already-live shared connection — replay the
// current transport status so its badge isn't stuck at the default.
options.onStatus?.(this.lastLogStatus);
} else {
this.openSharedLogStream();
}
return () => {
this.logSubscribers.delete(options);
if (this.logSubscribers.size === 0 && this.logStreamDispose) {
this.logStreamDispose();
this.logStreamDispose = null;
this.lastLogStatus = 'closed';
}
};
}
/** Open the single shared /api/logs/stream connection; every frame and status
* change fans out to all subscribers, each isolated so one throwing handler
* can't drop the frame for the others (and a subscriber unsubscribed mid-frame
* is skipped). A no-token attempt does NOT cache a dead disposer — it reports
* 'closed' and returns so a later subscribe / setToken can open for real,
* avoiding poisoning the shared cache. */
private openSharedLogStream(): void {
if (!this.currentToken) {
this.lastLogStatus = 'closed';
for (const sub of [...this.logSubscribers]) {
if (this.logSubscribers.has(sub)) { try { sub.onStatus?.('closed'); } catch { /* isolate */ } }
}
return;
}
this.lastLogStatus = 'reconnecting'; // connecting until onopen fires
this.logStreamDispose = this.openSseChannel<LogEntry | { type: string }>('/api/logs/stream', (parsed) => {
if ('type' in parsed) return; // control frame, not a log line
options.onLine(parsed);
}, options.onStatus);
for (const sub of [...this.logSubscribers]) {
if (this.logSubscribers.has(sub)) { try { sub.onLine(parsed); } catch { /* isolate a bad subscriber */ } }
}
}, (s) => {
this.lastLogStatus = s;
for (const sub of [...this.logSubscribers]) {
if (this.logSubscribers.has(sub)) { try { sub.onStatus?.(s); } catch { /* isolate */ } }
}
});
}
/** Token changed (login / re-login / logout): the shared stream baked the old
* token into its URL, so tear it down and reopen with the new one if anyone is
* still listening. Without this a re-login would leave the feed retrying a
* stale-token URL forever. */
private reopenSharedLogStream(): void {
if (this.logStreamDispose) {
this.logStreamDispose();
this.logStreamDispose = null;
}
this.lastLogStatus = 'closed';
if (this.logSubscribers.size > 0) this.openSharedLogStream();
}
// Invoke a (stream) action and relay each `data: <json>\n\n` SSE frame. Uses
+59 -2
View File
@@ -379,6 +379,9 @@ importers:
'@tanstack/react-router':
specifier: ^1.169.2
version: 1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
'@tanstack/react-virtual':
specifier: ^3.14.5
version: 3.14.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -1720,6 +1723,12 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@tanstack/react-virtual@3.14.5':
resolution: {integrity: sha512-4EKRXh7zBLkbKbFmG3AUVkircuHd+7OdT1pocJSepxtfBd3qnrJgJ5rtPkRYyo9fmyVb2+pI2xPy5oYvMLQy6A==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@tanstack/router-core@1.169.2':
resolution: {integrity: sha512-5sm0DJF1A7Mz+9gy4Gz/lLovNailK3yot4vYvz9MkBUPw26uLnhQiR8hSCYxucjE0wD6Mdlc5l+Z0/XTlZ7xHw==}
engines: {node: '>=20.19'}
@@ -1727,6 +1736,9 @@ packages:
'@tanstack/store@0.9.3':
resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==}
'@tanstack/virtual-core@3.17.3':
resolution: {integrity: sha512-8Np/TFELpI0ySuJoVmjvOrQYXH/8sTX0Biv9szhFhY39xOdAAY+smrMxjxOum/ux3eM8MUJQsEJ0/R0UpvC8dw==}
'@tybys/wasm-util@0.10.3':
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
@@ -4308,6 +4320,12 @@ snapshots:
react-dom: 19.2.5(react@19.2.5)
use-sync-external-store: 1.6.0(react@19.2.5)
'@tanstack/react-virtual@3.14.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
dependencies:
'@tanstack/virtual-core': 3.17.3
react: 19.2.5
react-dom: 19.2.5(react@19.2.5)
'@tanstack/router-core@1.169.2':
dependencies:
'@tanstack/history': 1.161.6
@@ -4317,6 +4335,8 @@ snapshots:
'@tanstack/store@0.9.3': {}
'@tanstack/virtual-core@3.17.3': {}
'@tybys/wasm-util@0.10.3':
dependencies:
tslib: 2.8.1
@@ -4476,7 +4496,7 @@ snapshots:
magicast: 0.5.3
obug: 2.1.1
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
transitivePeerDependencies:
- supports-color
@@ -4492,7 +4512,7 @@ snapshots:
obug: 2.1.1
std-env: 4.1.0
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
'@vitest/expect@4.1.4':
dependencies:
@@ -4511,6 +4531,14 @@ snapshots:
optionalDependencies:
vite: 8.1.0(@types/node@24.12.2)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
'@vitest/mocker@4.1.4(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
dependencies:
'@vitest/spy': 4.1.4
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
'@vitest/pretty-format@4.1.4':
dependencies:
tinyrainbow: 3.1.0
@@ -5813,6 +5841,35 @@ snapshots:
transitivePeerDependencies:
- msw
vitest@4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)):
dependencies:
'@vitest/expect': 4.1.4
'@vitest/mocker': 4.1.4(vite@8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
'@vitest/pretty-format': 4.1.4
'@vitest/runner': 4.1.4
'@vitest/snapshot': 4.1.4
'@vitest/spy': 4.1.4
'@vitest/utils': 4.1.4
es-module-lexer: 2.0.0
expect-type: 1.3.0
magic-string: 0.30.21
obug: 2.1.1
pathe: 2.0.3
picomatch: 4.0.4
std-env: 4.1.0
tinybench: 2.9.0
tinyexec: 1.1.1
tinyglobby: 0.2.16
tinyrainbow: 3.1.0
vite: 8.1.0(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 25.6.0
'@vitest/coverage-istanbul': 4.1.4(vitest@4.1.4)
'@vitest/coverage-v8': 4.1.4(vitest@4.1.4)
transitivePeerDependencies:
- msw
vp-runtime-helper@1.0.10:
dependencies:
'@types/fs-extra': 11.0.4