diff --git a/package.json b/package.json index 74a23d37..f588a4e3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.14.4", + "version": "1.14.5", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index b096ac7b..84bb67ca 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.14.4", + "version": "1.14.5", "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).", diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 49d38d3f..22473fc3 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -81,7 +81,7 @@ export type HookManagerDeps = { * Responsibilities: * - Route user commands (load/unload/refresh) to the matching session. * - Route watcher diff events to the matching session. - * - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager. + * - Forward session events ('login' / 'disconnected' / transport health) to BridgeManager. * - Retry stuck-in-connecting sessions on every watcher tick (so a * failed connect eventually recovers without a manual refresh). * - Retry the bounded early-process auto-load race without retrying diff --git a/packages/bridge/src/hook-packet-client.ts b/packages/bridge/src/hook-packet-client.ts index e8935d2d..3898bc4e 100644 --- a/packages/bridge/src/hook-packet-client.ts +++ b/packages/bridge/src/hook-packet-client.ts @@ -1,8 +1,20 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; -import { QqHookClient, type QqHookSendReply } from './qq-hook-client'; +import { + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + QqHookClient, + type QqHookSendReply, +} from './qq-hook-client'; + +export type OutboundHealthListener = (healthy: boolean) => void; export class HookPacketClient implements PacketSender { - constructor(private readonly client: QqHookClient) { } + private outboundHealthy = true; + + constructor( + private readonly client: QqHookClient, + private readonly onOutboundHealthChanged?: OutboundHealthListener, + ) { } async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise { if (!this.client.isLoggedIn) { @@ -14,6 +26,7 @@ export class HookPacketClient implements PacketSender { wantReply: true, replyTimeoutMs: timeoutMs, }) as QqHookSendReply; + this.setOutboundHealthy(true); return { success: reply.error === 0, gotResponse: true, @@ -22,6 +35,10 @@ export class HookPacketClient implements PacketSender { responseData: reply.body, }; } catch (error) { + if (error instanceof HookPipeRequestError + && error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) { + this.setOutboundHealthy(false); + } return { success: false, gotResponse: false, @@ -31,4 +48,10 @@ export class HookPacketClient implements PacketSender { }; } } + + private setOutboundHealthy(healthy: boolean): void { + if (this.outboundHealthy === healthy) return; + this.outboundHealthy = healthy; + this.onOutboundHealthChanged?.(healthy); + } } diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index eecb61ac..5fb1429f 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -69,7 +69,7 @@ export type HookSessionDeps = { * Emitted events: * 'login' (uin, packetSender) — real-UIN login detected * 'disconnected' (wasLoggedIn) — connection dropped or torn down - * 'receive-health-changed' (healthy) — receive path confirmed stale/recovered + * 'receive-health-changed' (healthy) — combined receive/request path health changed * 'status-changed' (status, error) — status field mutated * 'disposed' () — session stopped tracking this PID */ @@ -107,6 +107,7 @@ export class HookSession extends EventEmitter { private nextLoginHintAt = 0; private nextLoginIdentityObservationAt = 0; private _receiveHealthy = true; + private _outboundHealthy = true; private receiveWatchUin = ''; private receiveWatchArmed = false; private receiveWatchTimer: ReturnType | null = null; @@ -130,7 +131,9 @@ export class HookSession extends EventEmitter { get uin(): string { return this._uin; } get method(): string { return this._method; } get isDisposed(): boolean { return this.disposed; } - get receiveHealthy(): boolean { return this._receiveHealthy; } + get receiveHealthy(): boolean { + return this._receiveHealthy && this._outboundHealthy; + } attachProcessInfo(info: { name?: string; path?: string }): void { if (info.name) this._name = info.name; @@ -499,7 +502,10 @@ export class HookSession extends EventEmitter { if (this.client?.isClosed) this.tearDownClient(); if (!this.client) { this.client = this.makeClient(this.pid); - this.sender = new HookPacketClient(this.client); + this.sender = new HookPacketClient( + this.client, + healthy => this.setOutboundHealthy(healthy), + ); this.bound = false; } if (!this.bound) { @@ -582,6 +588,7 @@ export class HookSession extends EventEmitter { this.bound = false; this.connected = false; this.loggedIn = false; + this._outboundHealthy = true; this.resetLoginHint(); } @@ -595,9 +602,13 @@ export class HookSession extends EventEmitter { this.stopLoginReconcile(); // A PID can switch accounts without an intermediate logout edge. Never // carry the previous account's heartbeat deadline into the new epoch. - if (this.receiveWatchUin !== this._uin) this.resetReceiveWatch(this._uin); + if (this.receiveWatchUin !== this._uin) { + this.resetReceiveWatch(this._uin); + this._outboundHealthy = true; + } } else { this.resetReceiveWatch(); + this._outboundHealthy = true; } // Only the connected/logged-in states are ours to set here; when fully @@ -844,8 +855,29 @@ export class HookSession extends EventEmitter { private setReceiveHealthy(healthy: boolean): void { if (this._receiveHealthy === healthy) return; + const previous = this.receiveHealthy; this._receiveHealthy = healthy; - this.emit('receive-health-changed', healthy); + if (previous !== this.receiveHealthy) { + this.emit('receive-health-changed', this.receiveHealthy); + } + } + + private setOutboundHealthy(healthy: boolean): void { + if (this._outboundHealthy === healthy) return; + const previous = this.receiveHealthy; + this._outboundHealthy = healthy; + if (previous !== this.receiveHealthy) { + this.emit('receive-health-changed', this.receiveHealthy); + } + if (healthy) { + this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin); + } else { + this.log.warn( + 'request path unavailable: PID=%d UIN=%s; reporting good=false', + this.pid, + this._uin, + ); + } } private resetReceiveWatch(uin = ''): void { diff --git a/packages/bridge/src/qq-hook-client.ts b/packages/bridge/src/qq-hook-client.ts index c89b76e4..1573c23c 100644 --- a/packages/bridge/src/qq-hook-client.ts +++ b/packages/bridge/src/qq-hook-client.ts @@ -23,6 +23,7 @@ export const MAX_PIPE_MSG_BYTES = 65536; export const MAX_PIPE_BODY_BYTES = 16 * 1024 * 1024; export const DEFAULT_ACK_TIMEOUT_MS = 5000; export const DEFAULT_REPLY_TIMEOUT_MS = 30000; +export const PIPE_STATUS_CONNECTION_UNAVAILABLE = -39; const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250; const packetLog = createLogger('QQHook.Packet'); const runtimeLog = createLogger('QQHook.Runtime'); @@ -273,8 +274,12 @@ function withTimeout(promise: Promise, timeoutMs: number, label: string): }); } -class HookPipeRequestError extends Error { - constructor(message: string) { +export class HookPipeRequestError extends Error { + constructor( + message: string, + readonly status: number, + readonly requestId: number, + ) { super(message); this.name = 'HookPipeRequestError'; } @@ -1064,7 +1069,11 @@ export class QqHookClient extends EventEmitter { return; } if (frame.op === PipeOp.error) { - const error = new HookPipeRequestError(frame.msg || `pipe error ${frame.status}`); + const error = new HookPipeRequestError( + frame.msg || `pipe error ${frame.status}`, + frame.status, + frame.requestId, + ); const ack = this.pendingAcks.get(frame.requestId); if (ack) { this.pendingAcks.delete(frame.requestId); diff --git a/packages/bridge/tests/hook-packet-client.test.ts b/packages/bridge/tests/hook-packet-client.test.ts new file mode 100644 index 00000000..e6502f9c --- /dev/null +++ b/packages/bridge/tests/hook-packet-client.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from 'vitest'; +import { HookPacketClient } from '../src/hook-packet-client'; +import { + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + type QqHookClient, +} from '../src/qq-hook-client'; + +function fakeClient(send: QqHookClient['send']): QqHookClient { + return { + isLoggedIn: true, + send, + } as unknown as QqHookClient; +} + +describe('HookPacketClient outbound health', () => { + it('reports native connection loss once and recovers after a successful request', async () => { + const healthChanged = vi.fn(); + const send = vi + .fn() + .mockRejectedValueOnce(new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 1, + )) + .mockRejectedValueOnce(new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 2, + )) + .mockResolvedValueOnce({ + requestId: 3, + error: 0, + message: '', + body: Buffer.from('ok'), + }); + const sender = new HookPacketClient(fakeClient(send), healthChanged); + + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) + .resolves.toMatchObject({ success: false, gotResponse: false }); + await sender.sendPacket('Test.Command', Buffer.alloc(0)); + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) + .resolves.toMatchObject({ success: true, gotResponse: true }); + + expect(healthChanged.mock.calls).toEqual([[false], [true]]); + }); + + it('does not classify ordinary request rejection as connection loss', async () => { + const healthChanged = vi.fn(); + const send = vi.fn().mockRejectedValue( + new HookPipeRequestError('This request is not valid.', -38, 1), + ); + const sender = new HookPacketClient(fakeClient(send), healthChanged); + + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) + .resolves.toMatchObject({ success: false, gotResponse: false }); + + expect(healthChanged).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bridge/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index 28dca715..78f0246f 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -2,7 +2,12 @@ import { afterEach, describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; import { HookSession } from '../src/hook-session'; import type { ManualMapHandle } from '../src/injector'; -import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client'; +import { + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + type QqHookClient, + type QqHookPacket, +} from '../src/qq-hook-client'; import type { QqPortLoginInfo } from '../src/qq-port-probe'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketSink } from '@snowluma/common/protocol-types'; @@ -35,6 +40,7 @@ class FakeClient extends EventEmitter { shouldFailConnect = false; nativeReadyOnIdentityHint = false; identityHintFailures = 0; + sendError: Error | null = null; readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = []; readonly loginIdentityHints: string[] = []; private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; @@ -58,6 +64,7 @@ class FakeClient extends EventEmitter { if (this.nativeReadyOnIdentityHint) this.fireLogin(uin); } async send(serviceCmd: string, body: Buffer) { + if (this.sendError) throw this.sendError; this.sentPackets.push({ serviceCmd, body: Buffer.from(body) }); return { requestId: this.sentPackets.length, @@ -1061,6 +1068,39 @@ describe('HookSession — end-to-end receive health (#233)', () => { ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) }); } + it('reports native outbound loss as unhealthy and recovers on the next successful request', async () => { + const { ctx, healthChanges } = await startReceiveSession(); + let sender: PacketSender | undefined; + ctx.session.on('login', (_uin: string, nextSender: PacketSender) => { + sender = nextSender; + }); + + try { + // Re-emit on a new account epoch so the test captures the session sender. + ctx.currentClient().fireLogin('20002'); + ctx.currentClient().sendError = new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 1, + ); + + await sender!.sendPacket('Test.Command', Buffer.alloc(0)); + expect(ctx.session.receiveHealthy).toBe(false); + expect(healthChanges).toEqual([false]); + + // Incoming traffic alone must not conceal a still-broken send path. + firePacket(ctx, HEARTBEAT_CMD, '20002'); + expect(ctx.session.receiveHealthy).toBe(false); + + ctx.currentClient().sendError = null; + await sender!.sendPacket('Test.Command', Buffer.alloc(0)); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([false, true]); + } finally { + ctx.session.dispose(); + } + }); + it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); const { ctx, healthChanges } = await startReceiveSession(); diff --git a/packages/bridge/tests/qq-hook-client.test.ts b/packages/bridge/tests/qq-hook-client.test.ts index f38a6a66..4411f57e 100644 --- a/packages/bridge/tests/qq-hook-client.test.ts +++ b/packages/bridge/tests/qq-hook-client.test.ts @@ -688,10 +688,19 @@ describe('QqHookClient — packet TRACE', () => { message: 'send ack 1 timed out after 25 ms', }); - await expect(client.sendAndWait( + const requestError = await client.sendAndWait( 'Pipe.Error', Buffer.from([0xff]), - )).rejects.toThrow('send ack 2 timed out after 25 ms'); + ).then( + () => null, + (error: unknown) => error, + ); + expect(requestError).toMatchObject({ + name: 'HookPipeRequestError', + message: 'send ack 2 timed out after 25 ms', + status: 12, + requestId: 2, + }); expect(traceMessages(entries)).toEqual(expect.arrayContaining([ expect.stringMatching(/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/), diff --git a/packages/common/package.json b/packages/common/package.json index cc8f1b01..2f4ea97f 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.14.4", + "version": "1.14.5", "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).", diff --git a/packages/core/package.json b/packages/core/package.json index 754707e9..b6e2c4de 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.14.4", + "version": "1.14.5", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 861ce2f8..f8a80572 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -3,7 +3,11 @@ import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/f import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail'; import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list'; import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page'; -import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests'; +import { + FetchGroupRequests, + FetchGroupRequestsByUid, + groupRequestOperationType, +} from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests'; import { FetchRobotUinRanges, type RobotUinRange, @@ -92,6 +96,19 @@ export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boole && ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin); } +function normalizeGroupRequestSequence( + rawSequence: bigint | number | undefined, + groupId: number, +): number { + const sequence = Number(rawSequence ?? 0); + if (!Number.isSafeInteger(sequence) || sequence <= 0) { + throw new Error( + `invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`, + ); + } + return sequence; +} + const MEMBER_LIST_TTL_MS = 60_000; export class ContactsApi { @@ -387,25 +404,107 @@ export class ContactsApi { return info; } - async fetchGroupRequests(filtered = false): Promise { - const resp = await FetchGroupRequests.invoke(this.ctx, { filtered }); + async fetchGroupRequests( + filtered = false, + count = 50, + cursor = 0n, + ): Promise { + const resp = await FetchGroupRequests.invoke(this.ctx, { filtered, count, cursor }); const requests: GroupRequestInfo[] = []; for (const raw of resp.requests ?? []) { + const groupId = raw.group?.groupUin ?? 0; + const targetUin = raw.target?.uin ?? 0; + const invitorUin = raw.invitor?.uin ?? 0; + const operatorUin = raw.operatorUser?.uin ?? 0; + const notifyType = raw.eventType ?? 0; + const operationType = groupRequestOperationType(notifyType); + const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); + if (operationType === null) { + log.warn( + 'unsupported group-request notification type: group=%d sequence=%s type=%d', + groupId, + String(raw.sequence ?? 0n), + notifyType, + ); + } requests.push({ - groupId: raw.group?.groupUin ?? 0, + groupId, groupName: raw.group?.groupName ?? '', - targetUid: raw.target?.uid ?? '', - targetUin: 0, + targetUid: this.ctx.identity.findUidByUin(targetUin, groupId) + ?? this.ctx.identity.findUidByUin(targetUin) + ?? '', + targetUin, targetName: raw.target?.name ?? '', - invitorUid: raw.invitor?.uid ?? '', - invitorUin: 0, + invitorUid: this.ctx.identity.findUidByUin(invitorUin, groupId) + ?? this.ctx.identity.findUidByUin(invitorUin) + ?? '', + invitorUin, invitorName: raw.invitor?.name ?? '', - operatorUid: raw.operatorUser?.uid ?? '', - operatorUin: 0, + operatorUid: this.ctx.identity.findUidByUin(operatorUin, groupId) + ?? this.ctx.identity.findUidByUin(operatorUin) + ?? '', + operatorUin, operatorName: raw.operatorUser?.name ?? '', - sequence: Number(raw.sequence ?? 0), + sequence, state: raw.state ?? 0, - eventType: raw.eventType ?? 0, + notifyType, + eventType: operationType ?? 0, + comment: raw.comment ?? '', + filtered, + }); + } + this.ctx.identity.rememberGroupRequests(requests); + return requests; + } + + /** UID-form request list retained for correlating incoming UID-only pushes. + * Explicit list/actions use fetchGroupRequests(), which matches QQ's native + * numeric-account path and does not need profile lookups. */ + async fetchGroupRequestsByUid( + filtered = false, + count = 50, + cursor = 0n, + ): Promise { + const resp = await FetchGroupRequestsByUid.invoke(this.ctx, { filtered, count, cursor }); + const requests: GroupRequestInfo[] = []; + for (const raw of resp.requests ?? []) { + const groupId = raw.group?.groupUin ?? 0; + const targetUid = raw.target?.uid ?? ''; + const invitorUid = raw.invitor?.uid ?? ''; + const operatorUid = raw.operatorUser?.uid ?? ''; + const notifyType = raw.eventType ?? 0; + const operationType = groupRequestOperationType(notifyType); + const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); + if (operationType === null) { + log.warn( + 'unsupported group-request notification type: group=%d sequence=%s type=%d', + groupId, + String(raw.sequence ?? 0n), + notifyType, + ); + } + requests.push({ + groupId, + groupName: raw.group?.groupName ?? '', + targetUid, + targetUin: this.ctx.identity.findUinByUid(targetUid, groupId) + ?? this.ctx.identity.findUinByUid(targetUid) + ?? 0, + targetName: raw.target?.name ?? '', + invitorUid, + invitorUin: this.ctx.identity.findUinByUid(invitorUid, groupId) + ?? this.ctx.identity.findUinByUid(invitorUid) + ?? 0, + invitorName: raw.invitor?.name ?? '', + operatorUid, + operatorUin: this.ctx.identity.findUinByUid(operatorUid, groupId) + ?? this.ctx.identity.findUinByUid(operatorUid) + ?? 0, + operatorName: raw.operatorUser?.name ?? '', + sequence, + state: raw.state ?? 0, + notifyType, + eventType: operationType ?? 0, comment: raw.comment ?? '', filtered, }); diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index f9422a07..6ab3ba27 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -3,8 +3,8 @@ import type { BridgeContext } from './bridge-context'; export interface BridgeInterface extends BridgeContext { readonly activePid: number | null; - /** False only when every attached QQ process is confirmed stale. - * An unarmed watchdog remains true for compatibility. */ + /** False only when every attached QQ process has a confirmed receive or + * request-path failure. An unarmed watchdog remains true for compatibility. */ readonly receiveHealthy: boolean; /** Latest device snapshot observed on this Bridge lifecycle. `null` means * QQ has not emitted its cache notification since SnowLuma attached. */ diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 26a72ad0..df96d272 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -70,8 +70,8 @@ export class Bridge implements BridgeInterface { }, resolveGroupJoinRequest: async (groupId, uid, subType) => { const [main, filtered] = await Promise.allSettled([ - this.apis.contacts.fetchGroupRequests(false), - this.apis.contacts.fetchGroupRequests(true), + this.apis.contacts.fetchGroupRequestsByUid(false), + this.apis.contacts.fetchGroupRequestsByUid(true), ]); if (main.status === 'rejected') { log.warn('group-request enrichment main inbox failed: group=%d uid=%s err=%s', diff --git a/packages/core/tests/actions/contacts.test.ts b/packages/core/tests/actions/contacts.test.ts index 92a7fec5..c7b3e396 100644 --- a/packages/core/tests/actions/contacts.test.ts +++ b/packages/core/tests/actions/contacts.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { OidbBase, @@ -20,6 +21,36 @@ import type { import { ContactsApi } from '../../src/bridge/apis/contacts'; +interface ObservedGroupRequestUserByUin { + uin?: pb<1, uint_32>; + name?: pb<2, string>; +} + +interface ObservedGroupRequestUserByUid { + uid?: pb<1, string>; + name?: pb<2, string>; +} + +interface ObservedGroupRequestGroup { + groupUin?: pb<1, uint_32>; + groupName?: pb<2, string>; +} + +interface ObservedGroupRequest { + sequence?: pb<1, uint_64>; + eventType?: pb<2, uint_32>; + state?: pb<3, uint_32>; + group?: pb<4, ObservedGroupRequestGroup>; + target?: pb<5, TUser>; + invitor?: pb<6, TUser>; + operatorUser?: pb<7, TUser>; + comment?: pb<10, string>; +} + +interface ObservedGroupRequestResponse { + requests?: pb_repeated<1, ObservedGroupRequest>; +} + function friend( uin: number, categoryId: number, @@ -112,6 +143,34 @@ function groupDetailPacket(body: OidbSvcTrpcTcp0x88D_0Response): SendPacketResul }; } +function groupRequestPacketByUin( + body: ObservedGroupRequestResponse, +): SendPacketResult { + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from( + protobuf_encode>>({ body }), + ), + }; +} + +function groupRequestPacketByUid( + body: ObservedGroupRequestResponse, +): SendPacketResult { + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from( + protobuf_encode>>({ body }), + ), + }; +} + function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) { let index = 0; const sendRawPacket = vi.fn(async ( @@ -212,6 +271,75 @@ describe('apis/contacts / group roster', () => { }); }); +describe('apis/contacts / group requests', () => { + it('maps the native numeric-account response into directly actionable requests', async () => { + const rememberGroupRequests = vi.fn(); + const findUidByUin = vi.fn((uin: number) => uin === 1_234_567_890 ? 'cached_target_uid' : null); + const sendRawPacket = vi.fn(async () => groupRequestPacketByUin({ + requests: [{ + sequence: 1_785_525_232_784_291n, + eventType: 7, + state: 1, + group: { groupUin: 1_095_186_374, groupName: 'group' }, + target: { uin: 1_234_567_890, name: 'requester' }, + invitor: { uin: 2_345_678_901, name: 'inviter' }, + operatorUser: { uin: 3_456_789_012, name: 'operator' }, + comment: 'please', + }], + })); + const api = new ContactsApi({ + sendRawPacket, + identity: { findUidByUin, rememberGroupRequests }, + } as any); + + const requests = await api.fetchGroupRequests(false); + + expect(requests).toEqual([expect.objectContaining({ + groupId: 1_095_186_374, + targetUid: 'cached_target_uid', + targetUin: 1_234_567_890, + invitorUin: 2_345_678_901, + operatorUin: 3_456_789_012, + sequence: 1_785_525_232_784_291, + notifyType: 7, + eventType: 1, + filtered: false, + })]); + expect(rememberGroupRequests).toHaveBeenCalledWith(requests); + }); + + it('retains the UID-form response for correlating real-time request pushes', async () => { + const rememberGroupRequests = vi.fn(); + const findUinByUid = vi.fn((uid: string) => uid === 'target_uid' ? 1_234_567_890 : null); + const sendRawPacket = vi.fn(async () => groupRequestPacketByUid({ + requests: [{ + sequence: 42n, + eventType: 7, + state: 1, + group: { groupUin: 999, groupName: 'group' }, + target: { uid: 'target_uid', name: 'requester' }, + invitor: { uid: 'inviter_uid', name: 'inviter' }, + operatorUser: { uid: 'operator_uid', name: 'operator' }, + }], + })); + const api = new ContactsApi({ + sendRawPacket, + identity: { findUinByUid, rememberGroupRequests }, + } as any); + + const requests = await api.fetchGroupRequestsByUid(true); + + expect(requests).toEqual([expect.objectContaining({ + targetUid: 'target_uid', + targetUin: 1_234_567_890, + invitorUid: 'inviter_uid', + operatorUid: 'operator_uid', + filtered: true, + })]); + expect(rememberGroupRequests).toHaveBeenCalledWith(requests); + }); +}); + describe('apis/contacts / categorized friend roster', () => { it('keeps fetchFriendList flat while traversing cookie pages', async () => { const cookie = Uint8Array.from([0x01]); diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 9a116111..d790c85d 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.14.4", + "version": "1.14.5", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index fe29bb99..ac14206c 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -4781,7 +4781,7 @@ }, "flag": { "type": "string", - "description": "处理用 flag(eventType:groupId:targetUid:filtered)" + "description": "处理请求使用的规范 flag" } }, "required": [ @@ -5815,6 +5815,18 @@ "type": "boolean" }, "default": false + }, + { + "name": "count", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "default": 50, + "desc": "每个收件箱最多读取的记录数" } ], "invariants": [], @@ -5829,6 +5841,13 @@ "only_pending": { "type": "boolean", "default": false + }, + "count": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "description": "每个收件箱最多读取的记录数", + "default": 50 } }, "additionalProperties": true @@ -6970,7 +6989,7 @@ { "name": "get_status", "aliases": [], - "returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。", + "returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。", "returnsSchema": { "type": "object", "properties": { @@ -6980,7 +6999,7 @@ }, "good": { "type": "boolean", - "description": "接收链路健康状态;仅在确认停滞时为 false" + "description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false" } }, "required": [ diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 9083070e..c1bd818a 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -4784,7 +4784,7 @@ export const ACTIONS: CatalogAction[] = [ }, "flag": { "type": "string", - "description": "处理用 flag(eventType:groupId:targetUid:filtered)" + "description": "处理请求使用的规范 flag" } }, "required": [ @@ -5818,6 +5818,18 @@ export const ACTIONS: CatalogAction[] = [ "type": "boolean" }, "default": false + }, + { + "name": "count", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "default": 50, + "desc": "每个收件箱最多读取的记录数" } ], "invariants": [], @@ -5832,6 +5844,13 @@ export const ACTIONS: CatalogAction[] = [ "only_pending": { "type": "boolean", "default": false + }, + "count": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "description": "每个收件箱最多读取的记录数", + "default": 50 } }, "additionalProperties": true @@ -6973,7 +6992,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_status", "aliases": [], - "returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。", + "returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。", "returnsSchema": { "type": "object", "properties": { @@ -6983,7 +7002,7 @@ export const ACTIONS: CatalogAction[] = [ }, "good": { "type": "boolean", - "description": "接收链路健康状态;仅在确认停滞时为 false" + "description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false" } }, "required": [ diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 0542612e..7f302441 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.14.4", + "version": "1.14.5", "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..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/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 06a8f182..823dda68 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,5 +1,6 @@ import { readFile } from 'node:fs/promises'; import { FriendDressError } from '@snowluma/protocol/web/friend-dress'; +import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info'; import type { GroupEssenceContent, GroupEssenceMessage, @@ -1006,7 +1007,7 @@ export const actions = [ actor: { type: 'integer', description: '处理人 QQ 号' }, invitor_uin: { type: 'integer', description: '邀请人 QQ 号' }, invitor_nick: { type: 'string', description: '邀请人昵称' }, - flag: { type: 'string', description: '处理用 flag(eventType:groupId:targetUid:filtered)' }, + flag: { type: 'string', description: '处理请求使用的规范 flag' }, }, required: ['group_id', 'group_name', 'request_id', 'requester_uin', 'requester_nick', 'message', 'checked', 'actor', 'invitor_uin', 'invitor_nick', 'flag'], }, @@ -1025,13 +1026,13 @@ export const actions = [ actor: r.operatorUin, invitor_uin: r.invitorUin, invitor_nick: r.invitorName, - flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`, + flag: formatGroupRequestFlag(r), }))); }, }), // NapCat 对“被忽略通知中属于入群请求的子集”的命名(notify type == 7)。 - // 这里把经过过滤的 0x10c8_2 每一项映射成 NapCat 结构。 + // 这里把经过过滤的申请收件箱项目映射成 NapCat 结构。 // eventType 已经在当前流水线中编码了请求类别。 defineAction({ name: 'get_group_ignore_add_request', @@ -2735,14 +2736,10 @@ export const actions = [ ]; // 已过滤(机器人/被忽略)的入群请求。 -// SnowLuma 已通过 fetchGroupRequests 实现底层 oidb 0x10c8_2 拉取。 +// 与标准群系统消息共用过滤收件箱,只保留方言动作的返回形状。 // 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。 async function fetchFilteredGroupRequests(ctx: ApiActionContext) { - try { - return await ctx.bridge.apis.contacts.fetchGroupRequests(true); - } catch { - return []; - } + return ctx.bridge.apis.contacts.fetchGroupRequests(true); } diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 3df2324f..bef5a996 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -237,12 +237,14 @@ export const actions = [ params: { group_id: f.groupId().optional(), only_pending: f.bool().default(false), + count: f.int({ min: 1, max: 100 }).default(50).describe('每个收件箱最多读取的记录数'), }, run: async (p, ctx) => { if (ctx.handleGetGroupSystemMsg) { return okResponse(await ctx.handleGetGroupSystemMsg({ groupId: p.group_id, onlyPending: p.only_pending, + count: p.count, })); } return okResponse([]); diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index e4724e83..dd2c975b 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -27,12 +27,12 @@ export const actions = [ defineAction({ name: 'get_status', readOnly: true, - returns: '运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。', + returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。', returnsSchema: { type: 'object', properties: { online: { type: 'boolean', description: '是否在线' }, - good: { type: 'boolean', description: '接收链路健康状态;仅在确认停滞时为 false' }, + good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' }, }, required: ['online', 'good'], }, diff --git a/packages/onebot/src/event-converter/element-codecs.ts b/packages/onebot/src/event-converter/element-codecs.ts index 206a373e..97163182 100644 --- a/packages/onebot/src/event-converter/element-codecs.ts +++ b/packages/onebot/src/event-converter/element-codecs.ts @@ -54,7 +54,7 @@ type CodecOutput = T extends 'image' export interface ElementCodec { /** S 收·转:MessageElement → OneBot 段。 */ toSegment?: (element: MessageElementOf, ctx: ToSegmentContext) => Promise; - /** P 发·解:OneBot 段 data → MessageElement(null = 无法构造,parser 会 typed reject)。 */ + /** P 发·解:OneBot 段 data → MessageElement(null = 无法构造;reply 可作为可选修饰段被跳过)。 */ fromSegment?: (data: Record, options?: ParseMessageOptions) => Promise | null>; } @@ -203,8 +203,18 @@ export const ELEMENT_CODECS = { return { type: 'reply', data: { id: String(id) } }; }, async fromSegment(data, options) { - const id = intOr(data.id, 0); - if (id === 0) return null; + let id: number; + try { + id = intOr(data.id, 0); + } catch (error) { + if (!(error instanceof MessageElementValidationError)) throw error; + log.warn('could not quote the target message'); + return null; + } + if (id <= 0) { + log.warn('could not quote the target message'); + return null; + } const meta = options?.resolveReplyMeta?.(id) ?? null; if (options?.resolveReplySequence) { @@ -231,11 +241,8 @@ export const ELEMENT_CODECS = { // message and therefore has no QQ server sequence. Treating the opaque // OneBot id as a direct sequence would publish a malformed reply. if (meta?.sequenceAuthoritative === false) { - throw new MessageElementValidationError( - 'INVALID_FIELD', - `reply target ${id} has no authoritative QQ sequence`, - 'reply', - ); + log.warn('could not quote the target message'); + return null; } // Backward-compatible path: allow direct seq reply IDs. diff --git a/packages/onebot/src/group-request-poller.ts b/packages/onebot/src/group-request-poller.ts new file mode 100644 index 00000000..a8a81f41 --- /dev/null +++ b/packages/onebot/src/group-request-poller.ts @@ -0,0 +1,245 @@ +import { createLogger, type Logger } from '@snowluma/common/logger'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { GroupInviteEvent } from '@snowluma/protocol/events'; +import { + formatGroupRequestFlag, + type GroupRequestInfo, +} from '@snowluma/protocol/qq-info'; + +const DEFAULT_INTERVAL_MS = 15_000; +const REQUEST_SCREEN_COUNT = 50; +const RECENT_EVENT_WINDOW_MS = 30_000; +const MAX_SEEN_FLAGS = 2_048; + +export interface GroupRequestPollerOptions { + intervalMs?: number; + now?: () => number; +} + +/** + * Some group requests (notably invitations initiated through qun.qq.com) are + * visible in QQ's system-notification list without producing the real-time + * push consumed by SnowLuma's packet pipeline. Observe both request inboxes + * and emit only newly seen, actionable records through the same typed event + * bus as push-originated requests. + */ +export class GroupRequestPoller { + private readonly intervalMs: number; + private readonly now: () => number; + private readonly log: Logger; + private readonly seenFlags = new Map(); + private readonly recentFingerprints = new Map(); + private timer: ReturnType | null = null; + private scheduledTask: Promise | null = null; + private scanInFlight: Promise | null = null; + private unsubscribe: (() => void) | null = null; + private running = false; + private lifecycleStarted = false; + + constructor( + private readonly bridge: BridgeInterface, + private readonly selfUin: number, + options: GroupRequestPollerOptions = {}, + ) { + this.intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS; + if (!Number.isSafeInteger(this.intervalMs) || this.intervalMs <= 0) { + throw new Error(`invalid group-request polling interval: ${this.intervalMs}`); + } + this.now = options.now ?? Date.now; + this.log = createLogger('OneBot.GroupRequests').child({ uin: selfUin }); + } + + start(): void { + if (this.running) return; + this.running = true; + this.lifecycleStarted = true; + this.unsubscribe = this.bridge.events.on('group_invite', (event) => { + this.rememberObservedEvent(event); + }); + this.scheduledTask = this.runScheduledPoll(); + } + + stop(): Promise { + if (!this.running) return this.scheduledTask ?? Promise.resolve(); + this.running = false; + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + this.unsubscribe?.(); + this.unsubscribe = null; + return this.scheduledTask ?? Promise.resolve(); + } + + /** + * Public deterministic seam used by diagnostics and tests. Concurrent calls + * share one scan so a slow QQ response cannot create overlapping polling. + */ + pollOnce(): Promise { + if (this.scanInFlight) return this.scanInFlight; + const scan = this.scan(); + this.scanInFlight = scan; + void scan.finally(() => { + if (this.scanInFlight === scan) this.scanInFlight = null; + }).catch(() => undefined); + return scan; + } + + private async scan(): Promise { + const [main, filtered] = await Promise.all([ + this.bridge.apis.contacts.fetchGroupRequests(false, REQUEST_SCREEN_COUNT), + this.bridge.apis.contacts.fetchGroupRequests(true, REQUEST_SCREEN_COUNT), + ]); + if (this.lifecycleStarted && !this.running) return; + const discovered = [...main, ...filtered] + .filter((request) => request.state === 1) + .filter((request) => request.notifyType === 1 || request.notifyType === 7); + + const now = this.now(); + this.sweepRecentFingerprints(now); + for (const request of discovered) { + if (this.lifecycleStarted && !this.running) return; + let event: GroupInviteEvent; + try { + event = this.toEvent(request); + } catch (error) { + this.log.error( + 'group request record rejected: group=%s sequence=%s subtype=%s reason=%s', + String(request.groupId), + String(request.sequence), + request.notifyType === 1 ? 'invite' : 'add', + error instanceof Error ? error.message : String(error), + ); + continue; + } + + const fingerprint = eventFingerprint(event); + if (this.seenFlags.has(event.flag)) continue; + if ((this.recentFingerprints.get(fingerprint) ?? 0) > now - RECENT_EVENT_WINDOW_MS) { + this.rememberFlag(event.flag); + continue; + } + + if (event.fromUin === 0) { + this.log.warn( + 'group request sender could not be identified: group=%d sequence=%d subtype=%s', + event.groupId, + request.sequence, + event.subType, + ); + } + + // Mark before emission: handlers may synchronously trigger another list + // read through a quick operation, which must not re-emit this request. + this.rememberFlag(event.flag); + this.recentFingerprints.set(fingerprint, now); + this.log.info( + 'new group request discovered: group=%d sequence=%d subtype=%s filtered=%s', + event.groupId, + request.sequence, + event.subType, + request.filtered, + ); + await this.bridge.events.emit(event); + } + } + + private toEvent(request: GroupRequestInfo): GroupInviteEvent { + const notifyType = request.notifyType; + const subType = notifyType === 1 ? 'invite' : 'add'; + const fromUin = notifyType === 1 ? request.invitorUin : request.targetUin; + const fromUid = notifyType === 1 ? request.invitorUid : request.targetUid; + const inviteCardSequence = notifyType === 1 + ? this.bridge.apis.contacts.getGroupInviteCardSequence?.(request.groupId) + : undefined; + if (!Number.isSafeInteger(request.sequence) || request.sequence <= 0) { + throw new Error(`invalid group-request sequence: ${request.sequence}`); + } + if (!Number.isSafeInteger(request.groupId) || request.groupId <= 0) { + throw new Error(`invalid group id on group request: ${request.groupId}`); + } + if (!Number.isSafeInteger(request.eventType) || request.eventType <= 0) { + throw new Error( + `group request has no operation type: group=${request.groupId} sequence=${request.sequence} notifyType=${notifyType ?? 0}`, + ); + } + if (!Number.isSafeInteger(fromUin) || fromUin < 0) { + throw new Error(`invalid sender account on group request: ${fromUin}`); + } + if (inviteCardSequence !== undefined + && (!Number.isSafeInteger(inviteCardSequence) || inviteCardSequence <= 0)) { + throw new Error( + `invalid invite-card sequence: group=${request.groupId} sequence=${inviteCardSequence}`, + ); + } + + return { + kind: 'group_invite', + time: Math.floor(this.now() / 1_000), + selfUin: this.selfUin, + groupId: request.groupId, + fromUin, + fromUid, + subType, + message: request.comment, + flag: formatGroupRequestFlag(inviteCardSequence === undefined ? request : { + groupId: request.groupId, + sequence: inviteCardSequence, + eventType: 2, + filtered: false, + }), + }; + } + + private rememberObservedEvent(event: GroupInviteEvent): void { + if (event.flag.startsWith('slreq:1:')) this.rememberFlag(event.flag); + const fingerprint = eventFingerprint(event); + this.recentFingerprints.set(fingerprint, this.now()); + } + + private rememberFlag(flag: string): void { + if (this.seenFlags.has(flag)) return; + this.seenFlags.set(flag, true); + if (this.seenFlags.size <= MAX_SEEN_FLAGS) return; + const oldest = this.seenFlags.keys().next().value; + if (oldest !== undefined) this.seenFlags.delete(oldest); + } + + private sweepRecentFingerprints(now: number): void { + const oldest = now - RECENT_EVENT_WINDOW_MS; + for (const [fingerprint, observedAt] of this.recentFingerprints) { + if (observedAt <= oldest) this.recentFingerprints.delete(fingerprint); + } + } + + private async runScheduledPoll(): Promise { + try { + await this.pollOnce(); + } catch (error) { + this.log.error( + 'group request scan failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } finally { + if (this.running) { + this.timer = setTimeout(() => { + this.timer = null; + this.scheduledTask = this.runScheduledPoll(); + }, this.intervalMs); + this.timer.unref?.(); + } + } + } +} + +function eventFingerprint( + event: Pick, +): string { + const fromUid = event.fromUid?.trim() ?? ''; + const actor = event.fromUin > 0 + ? `uin:${event.fromUin}` + : fromUid + ? `uid:${fromUid}` + : `request:${event.flag}`; + return `${event.groupId}:${event.subType}:${actor}`; +} diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 8b7061b8..d603b3b4 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -23,6 +23,7 @@ import { MessageStore } from './message-store'; import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions'; import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command'; import { loginHistorySyncCoordinator } from './history-sync'; +import { GroupRequestPoller } from './group-request-poller'; import { HttpPostAdapter, HttpServerAdapter, @@ -56,6 +57,7 @@ export class OneBotInstance { private readonly reactionStore: ReactionStore; private readonly networkManager: OneBotNetworkManager; private readonly networkReady: Promise; + private readonly groupRequestPoller: GroupRequestPoller; private lifecycleTail: Promise; private readonly rkeyCache: RKeyCache; private readonly ctx: OneBotInstanceContext; @@ -67,6 +69,7 @@ export class OneBotInstance { private readonly pendingSelfSentEchoes = new Map(); private eventPipeline: EventPipelineHandle | null = null; private eventPipelineDrain: Promise = Promise.resolve(); + private groupRequestPollerDrain: Promise = Promise.resolve(); private disposePromise: Promise | null = null; private disposeRequested = false; private acceptingActions = true; @@ -187,12 +190,19 @@ export class OneBotInstance { this.startHeartbeat(); this.rkeyCache.warmUp(this.bridge, this.uin); this.eventPipeline = registerEventPipeline(ctx); + this.groupRequestPoller = new GroupRequestPoller(this.bridge, ctx.selfId); } waitUntilNetworkReady(): Promise { return this.networkReady; } + /** Begin observing request-list-only group invitations after adapters exist. */ + startGroupRequestPolling(): void { + if (this.disposeRequested) return; + this.groupRequestPoller.start(); + } + /** * Start the optional login-time backfill once roster warmup has completed. * The startup snapshot is intentional: hot config edits take effect on the @@ -260,6 +270,7 @@ export class OneBotInstance { this.apiHandler.quiesce(); this.online = false; this.stopHeartbeat(); + this.groupRequestPollerDrain = this.groupRequestPoller.stop(); this.historySyncAbortController?.abort( new Error(`OneBot instance UIN=${this.uin} is disposing`), ); @@ -278,6 +289,7 @@ export class OneBotInstance { await Promise.all([ Promise.all(this.inFlightActions), this.eventPipelineDrain, + this.groupRequestPollerDrain, this.historySyncTask ?? Promise.resolve(), ]); const shutdown = await this.networkManager.shutdown(); diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index 4754e6e3..7ab544fb 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -355,6 +355,7 @@ export class OneBotManager { this.trackLifecycle(`network startup UIN=${uin}`, instance.waitUntilNetworkReady().then((result) => { if (result.applied) log.info('network startup applied: UIN=%s adapters=%d', uin, result.statuses.length); else log.warn('network startup degraded: UIN=%s failures=%d', uin, result.errors.length); + instance.startGroupRequestPolling(); })); void warmUpBridgeState(uin, bridge).then( (warmup) => { diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 9fa7d8d8..989f6248 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -396,6 +396,11 @@ export async function segmentToElement(type: string, data: Record(); for (const request of requests) { - const uid = request.targetUid; + const actor = groupRequestActor(request); + const uid = actor.uid; if (!uid || resolved.has(uid)) continue; - if (request.targetUin > 0) { - resolved.set(uid, request.targetUin); + if (actor.uin > 0) { + resolved.set(uid, actor.uin); unresolved.delete(uid); continue; } @@ -365,27 +368,66 @@ async function resolveRequesterUins( return resolved; } +function groupRequestActor(request: GroupRequestInfo): { + uid: string; + uin: number; + name: string; +} { + if (request.notifyType === 1) { + return { + uid: request.invitorUid, + uin: request.invitorUin, + name: request.invitorName, + }; + } + return { + uid: request.targetUid, + uin: request.targetUin, + name: request.targetName, + }; +} + export async function getGroupSystemMessages( bridge: BridgeInterface, query: GroupSystemMessageQuery = {}, ): Promise { - const requests = (await bridge.apis.contacts.fetchGroupRequests()).filter((request) => { + const count = query.count ?? 50; + if (!Number.isSafeInteger(count) || count < 1 || count > 100) { + throw new Error(`invalid group-system-message count: ${count}`); + } + const [main, filtered] = await Promise.all([ + bridge.apis.contacts.fetchGroupRequests(false, count), + bridge.apis.contacts.fetchGroupRequests(true, count), + ]); + const unique = new Map(); + for (const request of [...main, ...filtered]) { + if (request.notifyType !== undefined + && request.notifyType !== 1 + && request.notifyType !== 7) continue; + if (request.eventType <= 0) continue; + const flag = formatGroupRequestFlag(request); + if (!unique.has(flag)) unique.set(flag, request); + } + const requests = [...unique.values()].filter((request) => { if (query.groupId !== undefined && request.groupId !== query.groupId) return false; if (query.onlyPending && request.state !== 1) return false; return true; }); const requesterUins = await resolveRequesterUins(bridge, requests); - return requests.map((request) => ({ - group_id: request.groupId, - group_name: request.groupName, - request_id: request.sequence, - requester_uin: requesterUins.get(request.targetUid) ?? request.targetUin, - requester_nick: request.targetName, - message: request.comment, - checked: request.state !== 1, - flag: formatGroupRequestFlag(request), - })); + return requests.map((request) => { + const actor = groupRequestActor(request); + return { + group_id: request.groupId, + group_name: request.groupName, + request_id: request.sequence, + requester_uin: requesterUins.get(actor.uid) ?? actor.uin, + requester_nick: actor.name, + message: request.comment, + checked: request.state !== 1, + flag: formatGroupRequestFlag(request), + }; + }); } export async function getDownloadRKeys(bridge: BridgeInterface): Promise { diff --git a/packages/onebot/src/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts index e0072aac..5449672d 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -50,10 +50,22 @@ export function parseGroupRequestFlag(flag: string): ParsedGroupRequestFlag { return { kind: 'legacy', requestType, groupId, targetUid }; } -async function fetchRequestInboxes(bridge: BridgeInterface): Promise { +interface RequestInboxLookup { + requests: GroupRequestInfo[]; + failures: unknown[]; +} + +async function fetchRequestInboxes( + bridge: BridgeInterface, + identityForm: 'uin' | 'uid', +): Promise { const [main, filtered] = await Promise.allSettled([ - bridge.apis.contacts.fetchGroupRequests(false), - bridge.apis.contacts.fetchGroupRequests(true), + identityForm === 'uin' + ? bridge.apis.contacts.fetchGroupRequests(false, 100) + : bridge.apis.contacts.fetchGroupRequestsByUid(false, 100), + identityForm === 'uin' + ? bridge.apis.contacts.fetchGroupRequests(true, 100) + : bridge.apis.contacts.fetchGroupRequestsByUid(true, 100), ]); if (main.status === 'rejected') { @@ -64,14 +76,27 @@ async function fetchRequestInboxes(bridge: BridgeInterface): Promise result.status === 'rejected') + .map((result) => result.reason); + if (failures.length === 2) { + throw new AggregateError(failures, 'failed to fetch group requests from both inboxes'); } - return [ - ...(main.status === 'fulfilled' ? main.value : []), - ...(filtered.status === 'fulfilled' ? filtered.value : []), - ]; + return { + requests: [ + ...(main.status === 'fulfilled' ? main.value : []), + ...(filtered.status === 'fulfilled' ? filtered.value : []), + ], + failures, + }; +} + +function throwMissingGroupRequest(message: string, failures: readonly unknown[]): never { + if (failures.length > 0) { + throw new AggregateError(failures, `group request lookup incomplete: ${message}`); + } + throw new Error(message); } async function applyGroupRequest( @@ -119,9 +144,14 @@ export async function handleGroupAddRequest( return; } - const matching = (await fetchRequestInboxes(bridge)) - .find((request) => request.sequence === parsed.sequence); - if (!matching) throw new Error(`group request sequence ${parsed.sequence} not found`); + const lookup = await fetchRequestInboxes(bridge, 'uin'); + const matching = lookup.requests.find((request) => request.sequence === parsed.sequence); + if (!matching) { + throwMissingGroupRequest( + `group request sequence ${parsed.sequence} not found`, + lookup.failures, + ); + } await applyGroupRequest(bridge, matching, approve, reason); return; } @@ -141,7 +171,8 @@ export async function handleGroupAddRequest( } } - const matching = (await fetchRequestInboxes(bridge)).find((request) => { + const lookup = await fetchRequestInboxes(bridge, 'uid'); + const matching = lookup.requests.find((request) => { if (request.groupId !== parsed.groupId) return false; return parsed.requestType === 'add' ? request.targetUid === parsed.targetUid @@ -150,6 +181,6 @@ export async function handleGroupAddRequest( // Never fall back to an arbitrary request from the same group: when a UID // does not match, approving another pending request is worse than failing. - if (!matching) throw new Error('matching group request not found'); + if (!matching) throwMissingGroupRequest('matching group request not found', lookup.failures); await applyGroupRequest(bridge, matching, approve, reason); } diff --git a/packages/onebot/tests/action-registry.test.ts b/packages/onebot/tests/action-registry.test.ts index 0e91bc67..3483f6ff 100644 --- a/packages/onebot/tests/action-registry.test.ts +++ b/packages/onebot/tests/action-registry.test.ts @@ -137,16 +137,18 @@ describe('compiled production Action registry', () => { const response = await handler.handle('get_group_system_msg', { group_id: '100000002', only_pending: true, + count: '80', }); expect(response.status).toBe('ok'); expect(handleGetGroupSystemMsg).toHaveBeenCalledWith({ groupId: 100000002, onlyPending: true, + count: 80, }); const doc = ACTION_REGISTRY.resolve('get_group_system_msg'); if (!doc || doc.kind === 'raw') throw new Error('get_group_system_msg action missing'); - expect(doc.action.doc.params.map((param) => param.name)).toEqual(['group_id', 'only_pending']); + expect(doc.action.doc.params.map((param) => param.name)).toEqual(['group_id', 'only_pending', 'count']); }); }); diff --git a/packages/onebot/tests/contact-actions.test.ts b/packages/onebot/tests/contact-actions.test.ts index 1eaf80ac..d9bf71ff 100644 --- a/packages/onebot/tests/contact-actions.test.ts +++ b/packages/onebot/tests/contact-actions.test.ts @@ -123,6 +123,7 @@ function makeGroupRequest(overrides: Partial = {}): GroupReque operatorName: 'operator', sequence: 123456, state: 1, + notifyType: 7, eventType: 22, comment: 'please', filtered: false, @@ -595,6 +596,19 @@ describe('onebot/contact-actions / getStrangerInfo', () => { }); describe('onebot/contact-actions / getGroupSystemMessages', () => { + it('reads both request inboxes with the requested per-inbox count', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered + ? [makeGroupRequest({ sequence: 2, filtered: true, targetUin: 202, targetUid: '' })] + : [makeGroupRequest({ sequence: 1, filtered: false, targetUin: 101, targetUid: '' })]); + const bridge = fakeBridge({ fetchGroupRequests }); + + const result = await getGroupSystemMessages(bridge, { count: 80 }); + + expect(fetchGroupRequests).toHaveBeenNthCalledWith(1, false, 80); + expect(fetchGroupRequests).toHaveBeenNthCalledWith(2, true, 80); + expect(result.map((item) => item.request_id)).toEqual([1, 2]); + }); + it('returns the same canonical flag accepted by set_group_add_request', async () => { const bridge = fakeBridge({ fetchGroupRequests: vi.fn(async () => [ @@ -613,6 +627,28 @@ describe('onebot/contact-actions / getGroupSystemMessages', () => { }); }); + it('reports the inviter as requester for group invitations', async () => { + const bridge = fakeBridge({ + fetchGroupRequests: vi.fn(async (filtered: boolean) => filtered ? [] : [ + makeGroupRequest({ + notifyType: 1, + eventType: 2, + targetUin: 10_001, + targetName: 'bot', + invitorUin: 45_678, + invitorName: 'inviter', + }), + ]), + }); + + const result = await getGroupSystemMessages(bridge); + + expect(result).toEqual([expect.objectContaining({ + requester_uin: 45_678, + requester_nick: 'inviter', + })]); + }); + it('filters by group and pending state before resolving requester identities', async () => { const fetchUserProfileByUid = vi.fn(async (uid: string) => makeProfile(uid === 'u_pending' ? 101 : 202, uid)); diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index e8d40f55..d7b31e07 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -1059,16 +1059,17 @@ describe('extended-actions / get_group_ignored_notifies', () => { actor: 8888, invitor_uin: 7777, invitor_nick: 'inviter', - flag: '7:999:u_t:filtered', + flag: 'slreq:1:42:999:7:1', }]); }); - it('returns [] when the fetch throws', async () => { + it('surfaces filtered-inbox failures instead of returning a false empty result', async () => { const bridge = fakeBridge({ fetchGroupRequests: (async () => { throw new Error('boom'); }) as any, }); const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignored_notifies', {}); - expect(res).toMatchObject({ status: 'ok', data: [] }); + expect(res).toMatchObject({ status: 'failed' }); + expect(res.wording).toContain('boom'); }); }); diff --git a/packages/onebot/tests/group-request-poller.test.ts b/packages/onebot/tests/group-request-poller.test.ts new file mode 100644 index 00000000..fc8c4636 --- /dev/null +++ b/packages/onebot/tests/group-request-poller.test.ts @@ -0,0 +1,279 @@ +import { describe, expect, it, vi } from 'vitest'; +import { BridgeEventBus } from '@snowluma/protocol/event-bus'; +import type { GroupRequestInfo } from '@snowluma/protocol/qq-info'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import { GroupRequestPoller } from '../src/group-request-poller'; + +function request(overrides: Partial = {}): GroupRequestInfo { + return { + groupId: 999, + groupName: 'group', + targetUid: 'target_uid', + targetUin: 123, + targetName: 'requester', + invitorUid: 'inviter_uid', + invitorUin: 456, + invitorName: 'inviter', + operatorUid: '', + operatorUin: 0, + operatorName: '', + sequence: 42, + state: 1, + notifyType: 7, + eventType: 1, + comment: 'please', + filtered: false, + ...overrides, + }; +} + +function setup( + fetchGroupRequests: (filtered: boolean, count: number) => Promise, + getGroupInviteCardSequence?: (groupId: number) => number | undefined, +) { + const events = new BridgeEventBus({ + onError: (_kind, error) => { throw error; }, + }); + const bridge = { + events, + apis: { contacts: { fetchGroupRequests, getGroupInviteCardSequence } }, + } as unknown as BridgeInterface; + const poller = new GroupRequestPoller(bridge, 10_001, { intervalMs: 60_000 }); + return { events, poller }; +} + +describe('GroupRequestPoller', () => { + it('emits a canonical invite request from a pending list-only notification once', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered ? [] : [request({ + notifyType: 1, + eventType: 2, + })]); + const { events, poller } = setup(fetchGroupRequests); + const received: unknown[] = []; + events.on('group_invite', (event) => { received.push(event); }); + + await poller.pollOnce(); + await poller.pollOnce(); + + expect(fetchGroupRequests).toHaveBeenCalledWith(false, 50); + expect(fetchGroupRequests).toHaveBeenCalledWith(true, 50); + expect(received).toEqual([expect.objectContaining({ + kind: 'group_invite', + selfUin: 10_001, + groupId: 999, + fromUin: 456, + fromUid: 'inviter_uid', + subType: 'invite', + message: 'please', + flag: 'slreq:1:42:999:2:0', + })]); + }); + + it('uses the applicant identity and filtered handle for join applications', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered + ? [request({ filtered: true, sequence: 43 })] + : []); + const { events, poller } = setup(fetchGroupRequests); + const received: unknown[] = []; + events.on('group_invite', (event) => { received.push(event); }); + + await poller.pollOnce(); + + expect(received).toEqual([expect.objectContaining({ + fromUin: 123, + fromUid: 'target_uid', + subType: 'add', + flag: 'slreq:1:43:999:1:1', + })]); + }); + + it('emits an actionable invite when the sender account is unavailable and continues the batch', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered ? [] : [ + request({ + notifyType: 1, + eventType: 2, + sequence: 41, + invitorUid: '', + invitorUin: 0, + }), + request({ + groupId: 1_000, + notifyType: 1, + eventType: 2, + sequence: 42, + }), + ]); + const { events, poller } = setup(fetchGroupRequests); + const received: unknown[] = []; + events.on('group_invite', (event) => { received.push(event); }); + + await poller.pollOnce(); + await poller.pollOnce(); + + expect(received).toEqual([ + expect.objectContaining({ + groupId: 999, + fromUin: 0, + fromUid: '', + subType: 'invite', + flag: 'slreq:1:41:999:2:0', + }), + expect.objectContaining({ + groupId: 1_000, + fromUin: 456, + flag: 'slreq:1:42:1000:2:0', + }), + ]); + }); + + it('does not merge separate requests whose sender identities are both unavailable', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered ? [] : [ + request({ + notifyType: 1, + eventType: 2, + sequence: 41, + invitorUid: '', + invitorUin: 0, + }), + request({ + notifyType: 1, + eventType: 2, + sequence: 42, + invitorUid: '', + invitorUin: 0, + }), + ]); + const { events, poller } = setup(fetchGroupRequests); + const received: unknown[] = []; + events.on('group_invite', (event) => { received.push(event); }); + + await poller.pollOnce(); + + expect(received).toEqual([ + expect.objectContaining({ flag: 'slreq:1:41:999:2:0' }), + expect.objectContaining({ flag: 'slreq:1:42:999:2:0' }), + ]); + }); + + it('isolates a malformed list record without suppressing valid siblings', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered ? [] : [ + request({ sequence: 0 }), + request({ groupId: 1_000, sequence: 43 }), + ]); + const { events, poller } = setup(fetchGroupRequests); + const received: unknown[] = []; + events.on('group_invite', (event) => { received.push(event); }); + + await poller.pollOnce(); + + expect(received).toEqual([ + expect.objectContaining({ + groupId: 1_000, + flag: 'slreq:1:43:1000:1:0', + }), + ]); + }); + + it('preserves the private invite-card approval sequence when one is known', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered ? [] : [request({ + notifyType: 1, + eventType: 2, + sequence: 42, + })]); + const { events, poller } = setup(fetchGroupRequests, () => 778_899); + const received: unknown[] = []; + events.on('group_invite', (event) => { received.push(event); }); + + await poller.pollOnce(); + + expect(received).toEqual([expect.objectContaining({ + flag: 'slreq:1:778899:999:2:0', + })]); + }); + + it('does not emit processed or non-request notification types', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => filtered ? [] : [ + request({ sequence: 1, state: 2 }), + request({ sequence: 2, notifyType: 9, eventType: 6 }), + ]); + const { events, poller } = setup(fetchGroupRequests); + const received = vi.fn(); + events.on('group_invite', received); + + await poller.pollOnce(); + + expect(received).not.toHaveBeenCalled(); + }); + + it('fails the scan when either inbox cannot be read', async () => { + const fetchGroupRequests = vi.fn(async (filtered: boolean) => { + if (filtered) throw new Error('filtered inbox unavailable'); + return [request()]; + }); + const { events, poller } = setup(fetchGroupRequests); + const received = vi.fn(); + events.on('group_invite', received); + + await expect(poller.pollOnce()).rejects.toThrow('filtered inbox unavailable'); + expect(received).not.toHaveBeenCalled(); + }); + + it('does not duplicate a request already delivered by the real-time path', async () => { + let releaseMain!: (value: GroupRequestInfo[]) => void; + const main = new Promise((resolve) => { releaseMain = resolve; }); + const fetchGroupRequests = vi.fn((filtered: boolean) => filtered + ? Promise.resolve([]) + : main); + const { events, poller } = setup(fetchGroupRequests); + const received: unknown[] = []; + events.on('group_invite', (event) => { received.push(event); }); + + poller.start(); + await events.emit({ + kind: 'group_invite', + time: 1, + selfUin: 10_001, + groupId: 999, + fromUin: 456, + fromUid: 'inviter_uid', + subType: 'invite', + message: 'please', + flag: 'invite:999:inviter_uid', + }); + releaseMain([request({ notifyType: 1, eventType: 2 })]); + await poller.stop(); + + expect(received).toHaveLength(1); + }); + + it('shares concurrent scans instead of issuing overlapping requests', async () => { + let release!: (value: GroupRequestInfo[]) => void; + const pending = new Promise((resolve) => { release = resolve; }); + const fetchGroupRequests = vi.fn(() => pending); + const { poller } = setup(fetchGroupRequests); + + const first = poller.pollOnce(); + const second = poller.pollOnce(); + expect(second).toBe(first); + expect(fetchGroupRequests).toHaveBeenCalledTimes(2); + + release([]); + await first; + }); + + it('does not emit from an in-flight scheduled scan after shutdown starts', async () => { + let release!: (value: GroupRequestInfo[]) => void; + const pending = new Promise((resolve) => { release = resolve; }); + const fetchGroupRequests = vi.fn(() => pending); + const { events, poller } = setup(fetchGroupRequests); + const received = vi.fn(); + events.on('group_invite', received); + + poller.start(); + const stopped = poller.stop(); + release([request()]); + await stopped; + + expect(received).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/instance-network-dispose.test.ts b/packages/onebot/tests/instance-network-dispose.test.ts index 6bffabd5..44fbd29d 100644 --- a/packages/onebot/tests/instance-network-dispose.test.ts +++ b/packages/onebot/tests/instance-network-dispose.test.ts @@ -18,6 +18,8 @@ function fabricatedInstance(results: NetworkShutdownResult[]) { heartbeatTimer: null, eventPipeline: null, eventPipelineDrain: Promise.resolve(), + groupRequestPoller: { stop: vi.fn(() => Promise.resolve()) }, + groupRequestPollerDrain: Promise.resolve(), disposePromise: null, disposeRequested: false, acceptingActions: true, diff --git a/packages/onebot/tests/manager-lifecycle.test.ts b/packages/onebot/tests/manager-lifecycle.test.ts index 22e3677c..de7150e7 100644 --- a/packages/onebot/tests/manager-lifecycle.test.ts +++ b/packages/onebot/tests/manager-lifecycle.test.ts @@ -23,6 +23,7 @@ function fakeInstance( nickname: `retiring-${uin}`, quiesce, dispose, + startGroupRequestPolling: vi.fn(), getConnectionStatuses: () => statuses, } as unknown as OneBotInstance; } @@ -173,6 +174,9 @@ describe('OneBotManager database preparation', () => { expect(beginMigration).toHaveBeenCalledOnce(); expect(manager.getInstance('10001')).not.toBeNull(); + await vi.waitFor(() => { + expect(instance.startGroupRequestPolling).toHaveBeenCalledOnce(); + }); } finally { await manager.dispose(); process.chdir(originalCwd); diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index 09667f4e..8fa6e781 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -194,16 +194,21 @@ describe('parseMessage', () => { [{ type: 'at', data: { qq: '123abc' } }] as any, false, )).rejects.toMatchObject({ code: 'INVALID_FIELD' }); - await expect(parseMessage( - [{ type: 'reply', data: { id: '456junk' } }] as any, - false, - )).rejects.toMatchObject({ code: 'INVALID_FIELD' }); await expect(parseMessage( [{ type: 'face', data: { id: 1.9 } }] as any, false, )).rejects.toMatchObject({ code: 'INVALID_FIELD' }); }); + it('skips an unusable reply segment while preserving sendable content', async () => { + const result = await parseMessage([ + { type: 'reply', data: { id: 'notice-event-id' } }, + { type: 'text', data: { text: 'still sent' } }, + ] as any, false); + + expect(result).toEqual([{ type: 'text', text: 'still sent' }]); + }); + it('parses image segment', async () => { const result = await parseMessage( [{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any, diff --git a/packages/onebot/tests/request-actions.test.ts b/packages/onebot/tests/request-actions.test.ts index a5c86a6f..b0c5eb20 100644 --- a/packages/onebot/tests/request-actions.test.ts +++ b/packages/onebot/tests/request-actions.test.ts @@ -7,7 +7,7 @@ import type { GroupRequestInfo } from '@snowluma/protocol/qq-info'; const APIS_ROUTING: Record = { fetchFriendList: 'contacts', fetchGroupList: 'contacts', fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts', - fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts', + fetchGroupRequests: 'contacts', fetchGroupRequestsByUid: 'contacts', fetchDownloadRKeys: 'contacts', getGroupInviteCardSequence: 'contacts', findGroupInviteCardGroupBySequence: 'contacts', }; @@ -111,10 +111,11 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { it('matches add requests by groupId and targetUid', async () => { const setAddRequest = vi.fn(async () => {}); + const fetchGroupRequestsByUid = vi.fn(async () => [ + fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }), + ]); const bridge = fakeBridge({ - fetchGroupRequests: vi.fn(async () => [ - fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }), - ]), + fetchGroupRequestsByUid, apis: { groupAdmin: { setAddRequest } } as any, }); @@ -122,12 +123,14 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { expect(setAddRequest).toHaveBeenCalledOnce(); expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false); + expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(false, 100); + expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(true, 100); }); it('matches invite requests by groupId and invitorUid', async () => { const setAddRequest = vi.fn(async () => {}); const bridge = fakeBridge({ - fetchGroupRequests: vi.fn(async () => [ + fetchGroupRequestsByUid: vi.fn(async () => [ fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }), ]), getGroupInviteCardSequence: vi.fn(() => null), @@ -144,7 +147,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { const setAddRequest = vi.fn(async () => {}); const bridge = fakeBridge({ // Main inbox empty; the invite sits only in the spam-filtered inbox. - fetchGroupRequests: vi.fn(async (filtered: boolean) => + fetchGroupRequestsByUid: vi.fn(async (filtered: boolean) => filtered ? [fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 55, eventType: 2, filtered: true })] : []), @@ -161,7 +164,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { it('surfaces "not found" only when neither inbox has the request', async () => { const bridge = fakeBridge({ - fetchGroupRequests: vi.fn(async () => []), + fetchGroupRequestsByUid: vi.fn(async () => []), getGroupInviteCardSequence: vi.fn(() => null), apis: { groupAdmin: { setAddRequest: vi.fn(async () => {}) } } as any, }); @@ -187,7 +190,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { it('does not fall back to another request from the same group', async () => { const setAddRequest = vi.fn(async () => {}); const bridge = fakeBridge({ - fetchGroupRequests: vi.fn(async () => [ + fetchGroupRequestsByUid: vi.fn(async () => [ fakeRequest({ groupId: 999, targetUid: 'u_someone_else' }), ]), apis: { groupAdmin: { setAddRequest } } as any, @@ -214,6 +217,20 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true); }); + it('does not report not-found when an unavailable inbox may contain the request', async () => { + const bridge = fakeBridge({ + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + fetchGroupRequests: vi.fn(async (filtered: boolean) => { + if (filtered) throw new Error('filtered inbox down'); + return []; + }), + apis: { groupAdmin: { setAddRequest: vi.fn(async () => {}) } } as any, + }); + + await expect(handleGroupAddRequest(bridge, '55', true, 'ok')) + .rejects.toThrow(/lookup incomplete/); + }); + it('distinguishes request-queue failure from a genuine missing request', async () => { const bridge = fakeBridge({ findGroupInviteCardGroupBySequence: vi.fn(() => undefined), diff --git a/packages/onebot/tests/send-group-file.test.ts b/packages/onebot/tests/send-group-file.test.ts index 9e161576..4e06d459 100644 --- a/packages/onebot/tests/send-group-file.test.ts +++ b/packages/onebot/tests/send-group-file.test.ts @@ -111,7 +111,7 @@ describe('send_group_msg with {type:"file"} segment', () => { } }); - it('rejects replying to an OIDB-only group file id as a QQ sequence (#254)', async () => { + it('skips an OIDB-only group-file reply and sends the remaining content (#254)', async () => { const messageStore = new MessageStore(':memory:'); try { const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt); @@ -133,21 +133,21 @@ describe('send_group_msg with {type:"file"} segment', () => { await expect(sendGroupMessage(ctx, 12345, [ { type: 'reply', data: { id: file.messageId } }, { type: 'text', data: { text: 'received' } }, - ] as any, false)).rejects.toMatchObject({ - code: 'INVALID_FIELD', - elementType: 'reply', - }); - expect(sendGroup).not.toHaveBeenCalled(); + ] as any, false)).resolves.toMatchObject({ messageId: expect.any(Number) }); + expect(sendGroup).toHaveBeenCalledWith(12345, [ + { type: 'text', text: 'received' }, + ]); } finally { messageStore.close(); } }); - it('rejects a local-only reply id even when its full event was not cached', async () => { + it('skips a local-only reply id even when its full event was not cached', async () => { const messageStore = new MessageStore(':memory:'); try { const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt); const bridge = fakeBridge({ + identity: { nickname: 'Bot' }, apis: { message: { sendGroup } } as any, resolveUserUid: vi.fn(), } as any); @@ -166,8 +166,10 @@ describe('send_group_msg with {type:"file"} segment', () => { await expect(sendGroupMessage(ctx, 12345, [ { type: 'reply', data: { id: 77 } }, { type: 'text', data: { text: 'received' } }, - ] as any, false)).rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'reply' }); - expect(sendGroup).not.toHaveBeenCalled(); + ] as any, false)).resolves.toMatchObject({ messageId: expect.any(Number) }); + expect(sendGroup).toHaveBeenCalledWith(12345, [ + { type: 'text', text: 'received' }, + ]); } finally { messageStore.close(); } diff --git a/packages/onebot/tests/status-health.test.ts b/packages/onebot/tests/status-health.test.ts index c99db9a5..f5692659 100644 --- a/packages/onebot/tests/status-health.test.ts +++ b/packages/onebot/tests/status-health.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { ApiHandler, type ApiActionContext } from '../src/api-handler'; -describe('get_status receive health (#233)', () => { +describe('get_status transport health (#233, #342)', () => { it('keeps online true while reporting a stalled receive path as not good', async () => { const ctx = { isOnline: () => true, diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 66bfbb66..ad406d7f 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.14.4", + "version": "1.14.5", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` 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).", diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts index 56f2ed3f..a0163c4f 100644 --- a/packages/proto-defs/src/oidb-actions/base.ts +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -217,7 +217,7 @@ export interface OidbLike { } export interface OidbGroupRequestList { count?: pb<1, uint_32>; - field2?: pb<2, uint_32>; + field2?: pb<2, uint_64>; } export interface OidbUserInfoKey { key?: pb<1, uint_32>; diff --git a/packages/proto-defs/src/oidb.ts b/packages/proto-defs/src/oidb.ts index fc04d734..f2065315 100644 --- a/packages/proto-defs/src/oidb.ts +++ b/packages/proto-defs/src/oidb.ts @@ -184,7 +184,7 @@ export interface OidbRobotUinRangeResponse { robotConfig?: pb<5, OidbRobotUinRangeConfig>; } -// OIDB.0x10C0 Group Request +// OIDB.0x10C0 Group Request — UID-form response (envelope reserved=0). export interface OidbSvcTrpcTcp0x10C0ResponseUser { uid?: pb<1, string>; name?: pb<2, string>; @@ -215,3 +215,33 @@ export interface OidbSvcTrpcTcp0x10C0Response { field5?: pb<5, uint_64>; field6?: pb<6, uint_32>; } + +// The native UIN-form request (envelope reserved=1) uses the same response +// tags, but user field 1 changes wire type from string to uint32. Keep a +// separate schema: decoding both forms through one interface would silently +// discard every numeric account identifier as a mismatched wire type. +export interface OidbSvcTrpcTcp0x10C0ResponseUserByUin { + uin?: pb<1, uint_32>; + name?: pb<2, string>; +} + +export interface OidbSvcTrpcTcp0x10C0ResponseRequestByUin { + sequence?: pb<1, uint_64>; + eventType?: pb<2, uint_32>; + state?: pb<3, uint_32>; + group?: pb<4, OidbSvcTrpcTcp0x10C0ResponseGroup>; + target?: pb<5, OidbSvcTrpcTcp0x10C0ResponseUserByUin>; + invitor?: pb<6, OidbSvcTrpcTcp0x10C0ResponseUserByUin>; + operatorUser?: pb<7, OidbSvcTrpcTcp0x10C0ResponseUserByUin>; + field9?: pb<9, string>; + comment?: pb<10, string>; +} + +export interface OidbSvcTrpcTcp0x10C0ResponseByUin { + requests?: pb_repeated<1, OidbSvcTrpcTcp0x10C0ResponseRequestByUin>; + field2?: pb<2, uint_64>; + newLatestSeq?: pb<3, uint_64>; + field4?: pb<4, uint_32>; + field5?: pb<5, uint_64>; + field6?: pb<6, uint_32>; +} diff --git a/packages/protocol/package.json b/packages/protocol/package.json index ad4f91e6..8fede30c 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.14.4", + "version": "1.14.5", "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/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts b/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts index 3126f688..8887f84b 100644 --- a/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts +++ b/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts @@ -1,30 +1,86 @@ // 0x10C0 — fetch pending group-add requests. // subCommand 1 = main inbox, 2 = filtered (low-priority) inbox // -// Returns the wire shape verbatim — the facade does the GroupRequestInfo -// mapping because it also needs to thread the `filtered` flag onto -// each entry, which the wire doesn't carry. +// Current QQ uses the UIN-form envelope for its native list path. The server +// changes user field 1 from a UID string to a numeric UIN when that envelope +// bit changes, so the two forms deliberately have separate decoders below. +// The UID form remains necessary for correlating UID-only real-time pushes. import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase, OidbSvcTrpcTcp0x10C0Response } from '@snowluma/proto-defs/oidb'; +import type { + OidbBase, + OidbSvcTrpcTcp0x10C0Response, + OidbSvcTrpcTcp0x10C0ResponseByUin, +} from '@snowluma/proto-defs/oidb'; import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base'; import { invokeOidb, type OidbSender } from '../../oidb-service'; +// Current QQ's EncodeOperateSysNotify maps the high-level list notification +// type to the discriminator sent by 0x10C8. This table was read directly from +// the current Linux client; keeping the distinction prevents list type 7 +// (join request) from being incorrectly sent back as operation type 7. +const GROUP_REQUEST_OPERATION_TYPE = new Map([ + [0, 0], [1, 2], [2, 10], [3, 11], [4, 12], [5, 22], + [6, 35], [7, 1], [8, 3], [9, 6], [10, 7], [11, 13], + [12, 15], [13, 16], [14, 17], [15, 19], [16, 8], [17, 100], +]); + +export function groupRequestOperationType(notifyType: number): number | null { + return GROUP_REQUEST_OPERATION_TYPE.get(notifyType) ?? null; +} + export namespace FetchGroupRequests { export const command = 0x10C0; + export const uinForm = true; export interface Params { /** false → subCmd 1 (main inbox), true → subCmd 2 (filtered). */ filtered: boolean; + /** Maximum records in this screen. QQ's own default is 50. */ + count?: number; + /** Cursor returned by response field 2; zero starts at the newest screen. */ + cursor?: bigint; } export type Deps = OidbSender; export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1; - export const serialize = (_ctx: Deps, _: Params): OidbGroupRequestList => ({ - count: 20, - field2: 0, + export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestList => ({ + count: p.count ?? 50, + field2: p.cursor ?? 0n, + }); + + export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0x10C0ResponseByUin): OidbSvcTrpcTcp0x10C0ResponseByUin => body; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchGroupRequests, params); +} + +/** UID-form compatibility path used only when an incoming push supplies UID + * but no UIN. It intentionally leaves the envelope's reserved field unset. */ +export namespace FetchGroupRequestsByUid { + export const command = 0x10C0; + + export interface Params { + filtered: boolean; + count?: number; + cursor?: bigint; + } + + export type Deps = OidbSender; + + export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestList => ({ + count: p.count ?? 50, + field2: p.cursor ?? 0n, }); export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0x10C0Response): OidbSvcTrpcTcp0x10C0Response => body; @@ -36,5 +92,5 @@ export namespace FetchGroupRequests { protobuf_decode>(bytes); export const invoke = (deps: Deps, params: Params): Promise => - invokeOidb(deps, FetchGroupRequests, params); + invokeOidb(deps, FetchGroupRequestsByUid, params); } diff --git a/packages/protocol/src/qq-info.ts b/packages/protocol/src/qq-info.ts index 579580c9..3e944d0e 100644 --- a/packages/protocol/src/qq-info.ts +++ b/packages/protocol/src/qq-info.ts @@ -75,6 +75,9 @@ export interface GroupRequestInfo { operatorName: string; sequence: number; state: number; + /** High-level notification type returned by the request list. */ + notifyType?: number; + /** 0x10C8 operation discriminator derived from notifyType. */ eventType: number; comment: string; filtered: boolean; diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts index d45232e7..74ca57ea 100644 --- a/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts @@ -1,10 +1,41 @@ import { describe, expect, it, vi } from 'vitest'; -import { protobuf_decode } from '@snowluma/proton'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; -import { FetchGroupRequests } from '../../../src/oidb-services/contacts/fetch-group-requests'; +import { + FetchGroupRequests, + FetchGroupRequestsByUid, + groupRequestOperationType, +} from '../../../src/oidb-services/contacts/fetch-group-requests'; + +interface ObservedGroupRequestUserByUin { + uin?: pb<1, uint_32>; + name?: pb<2, string>; +} + +interface ObservedGroupRequestGroup { + groupUin?: pb<1, uint_32>; + groupName?: pb<2, string>; +} + +interface ObservedGroupRequestByUin { + sequence?: pb<1, uint_64>; + eventType?: pb<2, uint_32>; + state?: pb<3, uint_32>; + group?: pb<4, ObservedGroupRequestGroup>; + target?: pb<5, ObservedGroupRequestUserByUin>; + invitor?: pb<6, ObservedGroupRequestUserByUin>; + operatorUser?: pb<7, ObservedGroupRequestUserByUin>; + comment?: pb<10, string>; +} + +interface ObservedGroupRequestResponseByUin { + requests?: pb_repeated<1, ObservedGroupRequestByUin>; + cursor?: pb<2, uint_64>; +} function makeSender() { const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; @@ -12,8 +43,17 @@ function makeSender() { } describe('FetchGroupRequests namespace', () => { + it('maps native list notification types to 0x10C8 operation types', () => { + expect(groupRequestOperationType(1)).toBe(2); + expect(groupRequestOperationType(7)).toBe(1); + expect(groupRequestOperationType(17)).toBe(100); + expect(groupRequestOperationType(99)).toBeNull(); + }); + it('declares 0x10C0', () => { expect(FetchGroupRequests.command).toBe(0x10C0); + expect(FetchGroupRequests.uinForm).toBe(true); + expect((FetchGroupRequestsByUid as { uinForm?: boolean }).uinForm).toBeUndefined(); }); describe('resolveSubCommand', () => { @@ -26,9 +66,18 @@ describe('FetchGroupRequests namespace', () => { }); describe('serialize', () => { - it('always sends count=20 / field2=0', () => { - expect(FetchGroupRequests.serialize({} as any, { filtered: false })).toEqual({ count: 20, field2: 0 }); - expect(FetchGroupRequests.serialize({} as any, { filtered: true })).toEqual({ count: 20, field2: 0 }); + it('defaults to one native 50-item screen at cursor zero', () => { + expect(FetchGroupRequests.serialize({} as any, { filtered: false })).toEqual({ count: 50, field2: 0n }); + expect(FetchGroupRequestsByUid.serialize({} as any, { filtered: true })).toEqual({ count: 50, field2: 0n }); + }); + + it('preserves a caller-provided count and 64-bit cursor', () => { + const cursor = 1_785_406_628_779_279n; + expect(FetchGroupRequests.serialize({} as any, { + filtered: false, + count: 80, + cursor, + })).toEqual({ count: 80, field2: cursor }); }); }); @@ -45,12 +94,60 @@ describe('FetchGroupRequests namespace', () => { expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x10c0_2'); }); - it('encodes envelope body with count=20', async () => { + it('encodes the native envelope and requested screen', async () => { const sender = makeSender(); - await FetchGroupRequests.invoke(sender, { filtered: false }); + await FetchGroupRequests.invoke(sender, { + filtered: false, + count: 80, + cursor: 1_785_406_628_779_279n, + }); const [, bytes] = sender.sendRawPacket.mock.calls[0]!; const env = protobuf_decode>(bytes); - expect(env.body?.count).toBe(20); + expect(env.reserved).toBe(1); + expect(env.body).toEqual({ count: 80, field2: 1_785_406_628_779_279n }); + }); + + it('decodes numeric account identifiers from the native response', async () => { + const responseData = Buffer.from(protobuf_encode>({ + body: { + requests: [{ + sequence: 1_785_525_232_784_291n, + eventType: 7, + state: 1, + group: { groupUin: 1_095_186_374, groupName: 'group' }, + target: { uin: 1_234_567_890, name: 'requester' }, + invitor: { uin: 2_345_678_901, name: 'inviter' }, + operatorUser: { uin: 3_456_789_012, name: 'operator' }, + comment: 'please', + }], + cursor: 1_785_406_628_779_279n, + }, + })); + const result: SendPacketResult = { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData, + }; + const sender = { sendRawPacket: vi.fn(async () => result) }; + + const response = await FetchGroupRequests.invoke(sender, { filtered: false }); + + expect(response.requests?.[0]).toMatchObject({ + target: { uin: 1_234_567_890, name: 'requester' }, + invitor: { uin: 2_345_678_901, name: 'inviter' }, + operatorUser: { uin: 3_456_789_012, name: 'operator' }, + }); + expect(response.field2).toBe(1_785_406_628_779_279n); + }); + + it('keeps the UID response path on the non-native envelope', async () => { + const sender = makeSender(); + await FetchGroupRequestsByUid.invoke(sender, { filtered: false }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.reserved ?? 0).toBe(0); }); }); }); diff --git a/packages/proton/package.json b/packages/proton/package.json index a253940f..ebaf455f 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.14.4", + "version": "1.14.5", "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.", diff --git a/packages/runtime/native/snowluma-linux-arm64.node b/packages/runtime/native/snowluma-linux-arm64.node index 77d26392..7ca4befc 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.node and b/packages/runtime/native/snowluma-linux-arm64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.so b/packages/runtime/native/snowluma-linux-arm64.so index e20f470f..c98b676e 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.so and b/packages/runtime/native/snowluma-linux-arm64.so differ diff --git a/packages/runtime/native/snowluma-linux-x64.node b/packages/runtime/native/snowluma-linux-x64.node index 893eecc7..79ef6489 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.node and b/packages/runtime/native/snowluma-linux-x64.node differ diff --git a/packages/runtime/native/snowluma-linux-x64.so b/packages/runtime/native/snowluma-linux-x64.so index cf752168..50f30678 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.so and b/packages/runtime/native/snowluma-linux-x64.so differ diff --git a/packages/runtime/native/snowluma-win32-x64.dll b/packages/runtime/native/snowluma-win32-x64.dll index 9cd0646b..47a47954 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.dll and b/packages/runtime/native/snowluma-win32-x64.dll differ diff --git a/packages/runtime/native/snowluma-win32-x64.node b/packages/runtime/native/snowluma-win32-x64.node index 60fe6ca9..f5fd351d 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.node and b/packages/runtime/native/snowluma-win32-x64.node differ diff --git a/packages/runtime/package.json b/packages/runtime/package.json index f4ba7659..4ada513a 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.14.4", + "version": "1.14.5", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 8e4a7cfb..291f3031 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.4", + "version": "1.14.5", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/sdk/src/client/api-client.ts b/packages/sdk/src/client/api-client.ts index 05ded173..7ad2d3c4 100644 --- a/packages/sdk/src/client/api-client.ts +++ b/packages/sdk/src/client/api-client.ts @@ -132,8 +132,16 @@ export abstract class SnowLumaApiClient { return this.call('get_group_honor_info', params, options); } - getGroupSystemMessages(options?: RequestOptions) { - return this.call('get_group_system_msg', {}, options); + getGroupSystemMessages(options?: RequestOptions & { + groupId?: number; + onlyPending?: boolean; + count?: number; + }) { + return this.call('get_group_system_msg', { + group_id: options?.groupId, + only_pending: options?.onlyPending, + count: options?.count, + }, options); } setGroupKick(groupId: number, userId: number, options?: RequestOptions & { rejectAddRequest?: boolean }) { diff --git a/packages/sdk/src/types/actions.ts b/packages/sdk/src/types/actions.ts index ea06a6ae..d9d786d8 100644 --- a/packages/sdk/src/types/actions.ts +++ b/packages/sdk/src/types/actions.ts @@ -18,6 +18,7 @@ import type { GetGroupFilesParams, GetGroupFileUrlParams, GetGroupHonorInfoParams, + GetGroupSystemMsgParams, GetGroupInfoParams, GetGroupListParams, GetGroupMemberInfoParams, @@ -131,7 +132,7 @@ export interface SnowLumaActionMap { get_group_member_list: { params: GetGroupMemberListParams; data: JsonObject[] }; get_group_member_info: { params: GetGroupMemberInfoParams; data: JsonObject }; get_group_honor_info: { params: GetGroupHonorInfoParams; data: JsonValue }; - get_group_system_msg: { params: JsonObject; data: JsonObject[] }; + get_group_system_msg: { params: GetGroupSystemMsgParams; data: JsonObject[] }; set_group_kick: { params: SetGroupKickParams; data: EmptyData }; set_group_kick_members: { params: SetGroupKickMembersParams; data: EmptyData }; set_group_ban: { params: SetGroupBanParams; data: EmptyData }; diff --git a/packages/sdk/src/types/params.ts b/packages/sdk/src/types/params.ts index 693ea1a2..9ac0f156 100644 --- a/packages/sdk/src/types/params.ts +++ b/packages/sdk/src/types/params.ts @@ -57,6 +57,12 @@ export interface GetGroupHonorInfoParams extends GroupIdParams { type?: 'talkative' | 'performer' | 'legend' | 'strong_newbie' | 'emotion' | 'all' | string; } +export interface GetGroupSystemMsgParams extends JsonObject { + group_id?: number; + only_pending?: boolean; + count?: number; +} + export interface DeleteFriendParams extends UserIdParams { block?: boolean; } diff --git a/packages/ui/package.json b/packages/ui/package.json index 0dd93754..3b35250b 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.4", + "version": "1.14.5", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 3cd3f03f..ccfd5454 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.14.4", + "version": "1.14.5", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index c8a01b6c..1db336a9 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.14.4", + "version": "1.14.5", "type": "module", "scripts": { "dev": "vite",