feat(onebot): report web-originated group requests

Report pending group invitations through the standard OneBot request event even when their origin does not provide a live notification.

Prevent duplicate delivery when the same invitation is observed more than once, stop outstanding work with the account lifecycle, and preserve previously supported invitation behavior.

Expand group-system message queries and surface incomplete lookups instead of reporting misleading empty or not-found results.
This commit is contained in:
DrSmoothl committed 2026-08-10 00:26:16 +08:00
1 parent fe44a2f5bc
commit 1996192a5e
14 files changed
+606 -49

No files matched your search

+6 -9
View File
@@ -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);
}
@@ -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([]);
+218
View File
@@ -0,0 +1,218 @@
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<string, true>();
private readonly recentFingerprints = new Map<string, number>();
private timer: ReturnType<typeof setTimeout> | null = null;
private scheduledTask: Promise<void> | null = null;
private scanInFlight: Promise<void> | 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<void> {
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<void> {
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<void> {
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)
.map((request) => ({ request, event: this.toEvent(request) }));
const now = this.now();
this.sweepRecentFingerprints(now);
for (const { request, event } of discovered) {
if (this.lifecycleStarted && !this.running) return;
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;
}
// 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(
`group request has no sender account: group=${request.groupId} sequence=${request.sequence} subtype=${subType}`,
);
}
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<void> {
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<GroupInviteEvent, 'groupId' | 'subType' | 'fromUin' | 'fromUid'>): string {
const actor = event.fromUin > 0 ? `uin:${event.fromUin}` : `uid:${event.fromUid ?? ''}`;
return `${event.groupId}:${event.subType}:${actor}`;
}
+12
View File
@@ -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<NetworkReconcileResult>;
private readonly groupRequestPoller: GroupRequestPoller;
private lifecycleTail: Promise<void>;
private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext;
@@ -67,6 +69,7 @@ export class OneBotInstance {
private readonly pendingSelfSentEchoes = new Map<string, { event: JsonObject; expiresAt: number }>();
private eventPipeline: EventPipelineHandle | null = null;
private eventPipelineDrain: Promise<void> = Promise.resolve();
private groupRequestPollerDrain: Promise<void> = Promise.resolve();
private disposePromise: Promise<NetworkShutdownResult> | 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<NetworkReconcileResult> {
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();
+1
View File
@@ -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) => {
+56 -14
View File
@@ -17,6 +17,8 @@ const log = createLogger('OneBot.Contacts');
export interface GroupSystemMessageQuery {
groupId?: number;
onlyPending?: boolean;
/** Maximum records read from each QQ request inbox. */
count?: number;
}
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
@@ -330,10 +332,11 @@ async function resolveRequesterUins(
const unresolved = new Set<string>();
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<JsonObject[]> {
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<string, GroupRequestInfo>();
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<JsonObject[]> {
+45 -14
View File
@@ -50,10 +50,22 @@ export function parseGroupRequestFlag(flag: string): ParsedGroupRequestFlag {
return { kind: 'legacy', requestType, groupId, targetUid };
}
async function fetchRequestInboxes(bridge: BridgeInterface): Promise<GroupRequestInfo[]> {
interface RequestInboxLookup {
requests: GroupRequestInfo[];
failures: unknown[];
}
async function fetchRequestInboxes(
bridge: BridgeInterface,
identityForm: 'uin' | 'uid',
): Promise<RequestInboxLookup> {
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<GroupReques
log.warn('failed to fetch filtered group-request inbox: %s',
filtered.reason instanceof Error ? filtered.reason.message : String(filtered.reason));
}
if (main.status === 'rejected' && filtered.status === 'rejected') {
throw new Error('failed to fetch group requests from both inboxes');
const failures = [main, filtered]
.filter((result): result is PromiseRejectedResult => 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);
}
@@ -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']);
});
});
@@ -123,6 +123,7 @@ function makeGroupRequest(overrides: Partial<GroupRequestInfo> = {}): 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));
@@ -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');
});
});
@@ -0,0 +1,192 @@
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> = {}): 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<GroupRequestInfo[]>,
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('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<GroupRequestInfo[]>((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<GroupRequestInfo[]>((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<GroupRequestInfo[]>((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();
});
});
@@ -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,
@@ -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);
+25 -8
View File
@@ -7,7 +7,7 @@ import type { GroupRequestInfo } from '@snowluma/protocol/qq-info';
const APIS_ROUTING: Record<string, string> = {
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),