fix(core): restore group remarks in queries

Request and retain the group remark information needed by group list and group detail queries while preserving the existing safeguards for large rosters.

Synchronize confirmed group remark changes with the local identity roster and persistent cache. Remote failures leave local state untouched, and missing roster entries remain observable without creating phantom groups.

Add regression coverage for query mapping, request scope, persistence, failed updates, unknown groups, and closed identity stores.

Fixes #304
This commit is contained in:
DrSmoothl committed 2026-08-01 21:11:02 +08:00
1 parent 6372e1479c
commit fb4d7716a1
10 files changed
+173 -10

No files matched your search

+2
View File
@@ -129,6 +129,7 @@ export interface MockBridge {
findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
updateFriendRemark: ReturnType<typeof vi.fn>;
updateGroupRemark: ReturnType<typeof vi.fn>;
forgetGroup: ReturnType<typeof vi.fn>;
};
events: { emit: ReturnType<typeof vi.fn> };
@@ -162,6 +163,7 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
updateGroupRemark: vi.fn(() => true),
forgetGroup: vi.fn(),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
@@ -8,6 +8,7 @@ import type {
OidbFriendCategory,
OidbRobotUinRangeResponse,
OidbSvcTrpcTcp0xFD4_1Response,
OidbSvcTrpcTcp0xFE5_2Response,
OidbSvcTrpcTcp0xFE7_3Response,
} from '@snowluma/proto-defs/oidb';
import type {
@@ -86,6 +87,18 @@ function memberListPacket(body: OidbSvcTrpcTcp0xFE7_3Response): SendPacketResult
};
}
function groupListPacket(body: OidbSvcTrpcTcp0xFE5_2Response): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>({ body }),
),
};
}
function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) {
let index = 0;
const sendRawPacket = vi.fn(async (
@@ -131,6 +144,34 @@ function apiForCategoryChange(roster: OidbSvcTrpcTcp0xFD4_1Response) {
return { api, sendRawPacket };
}
describe('apis/contacts / group roster', () => {
it('maps QQ group remarks into the returned and remembered roster', async () => {
const rememberGroups = vi.fn();
const sendRawPacket = vi.fn(async () => groupListPacket({
groups: [{
groupUin: 123456789,
info: { groupName: 'Project', memberCount: 42, memberMax: 500 },
customInfo: { remark: ' My Project ' },
}],
}));
const api = new ContactsApi({
sendRawPacket,
identity: { rememberGroups },
} as any);
const groups = await api.fetchGroupList();
expect(groups).toEqual([expect.objectContaining({
groupId: 123456789,
groupName: 'Project',
remark: ' My Project ',
memberCount: 42,
memberMax: 500,
})]);
expect(rememberGroups).toHaveBeenCalledWith(groups);
});
});
describe('apis/contacts / categorized friend roster', () => {
it('keeps fetchFriendList flat while traversing cookie pages', async () => {
const cookie = Uint8Array.from([0x01]);
@@ -329,6 +329,7 @@ describe('apis/group-file', () => {
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
updateGroupRemark: vi.fn(() => true),
forgetGroup: vi.fn(),
},
});
@@ -238,6 +238,37 @@ describe('IdentityService', () => {
}
});
it('keeps exact group remark updates after reopening the persistent cache', () => {
const dbPath = tempDbPath('update-group-remark');
const remark = ' project group ';
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([{ ...makeGroup(), remark: 'old-remark' }]);
expect(identity.updateGroupRemark(GROUP_ID, remark)).toBe(true);
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
}
});
it('does not invent a group while applying a remark update', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
expect(identity.updateGroupRemark(987654321, 'unknown')).toBe(false);
expect(identity.groups).toHaveLength(1);
expect(identity.findGroup(GROUP_ID)?.remark).toBe('');
expect(identity.findGroup(987654321)).toBeNull();
identity.close();
});
it.each([
['empty', ''],
['whitespace-only', ' '],
@@ -749,6 +780,7 @@ describe('IdentityService', () => {
['nickname', () => { identity.nickname = 'after-close'; }],
['self profile', () => identity.setSelfProfile(profile)],
['group member update', () => identity.updateGroupMember(GROUP_ID, { ...member, card: 'after-close' })],
['group remark update', () => identity.updateGroupRemark(GROUP_ID, 'after-close')],
['friends', () => identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: '', remark: '' }])],
['groups', () => identity.rememberGroups([])],
['forget group', () => identity.forgetGroup(GROUP_ID)],
+2 -1
View File
@@ -275,7 +275,8 @@ export interface OidbGroupListConfig1 {
export interface OidbGroupListConfig2 {
field1?: pb<1, bool>;
field2?: pb<2, bool>;
field3?: pb<3, bool>;
/** Request the bot-local label returned as group.customInfo.remark. */
remark?: pb<3, bool>;
field4?: pb<4, bool>;
field5?: pb<5, bool>;
field6?: pb<6, bool>;
+30 -1
View File
@@ -322,6 +322,35 @@ export class IdentityService {
this.runWrite('group member update', () => this.transaction(() => this.upsertGroupMember(persisted)));
}
/** Apply a server-confirmed update to the bot's local label for one group. */
updateGroupRemark(groupId: number, remark: string): boolean {
this.beginObservation('group remark update');
if (!Number.isSafeInteger(groupId) || groupId <= 0) {
throw new Error(`group remark update has invalid group id: ${groupId}`);
}
if (typeof remark !== 'string') {
throw new Error('group remark update must be a string');
}
const group = this.groups_.get(groupId);
if (!group) return false;
const observed: QQGroupInfo = { ...group, remark };
const persisted: GroupInput = {
groupId,
groupName: observed.groupName,
remark: observed.remark,
memberCount: observed.memberCount,
memberMax: observed.memberMax,
};
this.groups_.set(groupId, observed);
this.runWrite(
'group remark update',
() => this.transaction(() => this.upsertGroup(persisted)),
);
return true;
}
/** Apply the server-authoritative friend/stranger remark synchronization push. */
updateFriendRemark(uid: string, uin: number, remark: string): boolean {
this.beginObservation('friend remark update');
@@ -932,7 +961,7 @@ export class IdentityService {
).run(
input.groupId,
mergeOptionalText(input.groupName, existing?.group_name ?? ''),
mergeOptionalText(input.remark, existing?.remark ?? ''),
mergeOptionalExactText(input.remark, existing?.remark ?? ''),
normalizeNonNegative(input.memberCount, existing?.member_count ?? 0),
normalizeNonNegative(input.memberMax, existing?.member_max ?? 0),
nowSeconds(),
@@ -5,8 +5,9 @@
// per-group fields to include. Asking for everything blows the
// named-pipe write buffer on accounts with ~200+ groups (see #42),
// so we keep `config1.*` mostly on but turn off the costly
// `field5002`/`field5003` and entire `config2` block that never map
// back to a decoded field anyway.
// `field5002`/`field5003` and the unused `config2` fields. `config2.remark`
// is the bot-local group remark returned as `customInfo.remark`, so it is the
// sole optional field enabled in that block.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFE5_2Response } from '@snowluma/proto-defs/oidb';
@@ -37,7 +38,7 @@ export namespace FetchGroupList {
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
},
config2: {
field1: false, field2: false, field3: false, field4: false,
field1: false, field2: false, remark: true, field4: false,
field5: false, field6: false, field7: false, field8: false,
},
config3: { field5: allTrue, field6: allTrue },
@@ -2,16 +2,20 @@
// the bot sees this — the group's actual name is untouched).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0xf16Req } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
const log = createLogger('Bridge.GroupAdmin');
export namespace SetGroupRemark {
export const command = 0xF16;
export const subCommand = 1;
export interface Params { groupId: number; remark: string; }
export type Deps = OidbSender;
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
export const serialize = (_ctx: Deps, p: Params): Oidb0xf16Req => ({
inner: { groupId: BigInt(p.groupId), remark: p.remark },
@@ -24,6 +28,28 @@ export namespace SetGroupRemark {
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetGroupRemark, params);
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
await invokeOidb(deps, SetGroupRemark, params);
// QQ has already accepted the mutation. Keep the local roster coherent,
// but never turn a local-cache problem into a false remote failure that
// encourages callers to repeat the mutation.
try {
const updated = deps.identity.updateGroupRemark(params.groupId, params.remark);
if (!updated) {
log.warn(
'local group roster did not contain server-confirmed remark target: uin=%s group=%d',
deps.identity.uin,
params.groupId,
);
}
} catch (error: unknown) {
log.error(
'local identity synchronization failed after confirmed group remark update: uin=%s group=%d: %s',
deps.identity.uin,
params.groupId,
error instanceof Error ? error.message : String(error),
);
}
};
}
@@ -28,13 +28,17 @@ describe('FetchGroupList namespace', () => {
expect(env.reserved).toBe(1);
});
it('sends the verbatim config blob (field5002/5003 OFF to avoid EPIPE on big rosters)', async () => {
it('requests group remarks without enabling the other costly optional fields', async () => {
const sender = makeSender();
await FetchGroupList.invoke(sender);
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupListRequest>>(bytes);
expect(env.body?.config?.config1?.groupName).toBe(true);
expect(env.body?.config?.config1?.memberCount).toBe(true);
expect(env.body?.config?.config2?.remark).toBe(true);
for (const field of ['field1', 'field2', 'field4', 'field5', 'field6', 'field7', 'field8'] as const) {
expect(env.body?.config?.config2?.[field] ?? false, field).toBe(false);
}
// proto3 default false — omitted on wire, decoded as null.
expect(env.body?.config?.config1?.field5002 ?? false).toBe(false);
expect(env.body?.config?.config1?.field5003 ?? false).toBe(false);
@@ -8,7 +8,10 @@ import { SetGroupRemark } from '../../../src/oidb-services/group-admin/set-group
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001', updateGroupRemark: vi.fn(() => true) },
};
}
describe('SetGroupRemark namespace', () => {
@@ -25,4 +28,27 @@ describe('SetGroupRemark namespace', () => {
const env = protobuf_decode<OidbBase<Oidb0xf16Req>>(bytes);
expect(env.body?.inner).toMatchObject({ groupId: 12345n, remark: 'my group' });
});
it('updates the local group roster after QQ confirms the remark', async () => {
const deps = makeDeps();
await SetGroupRemark.invoke(deps as any, { groupId: 12345, remark: 'my group' });
expect(deps.identity.updateGroupRemark).toHaveBeenCalledWith(12345, 'my group');
});
it('does not update the local roster when QQ rejects the mutation', async () => {
const deps = makeDeps();
deps.sendRawPacket.mockResolvedValueOnce({
success: false,
gotResponse: true,
errorCode: 120,
errorMessage: 'denied',
responseData: Buffer.alloc(0),
});
await expect(
SetGroupRemark.invoke(deps as any, { groupId: 12345, remark: 'not-applied' }),
).rejects.toThrow();
expect(deps.identity.updateGroupRemark).not.toHaveBeenCalled();
});
});