fix(friend): verify and synchronize remark updates

Validate the service result before reporting friend remark changes as successful. Rejected, incomplete, or contradictory confirmations now reach callers instead of being reported as completed.

Keep confirmed remarks synchronized in the identity cache and consume cross-client remark updates without exposing a new OneBot event. Local cache failures remain observable without turning an already completed remote change into a retryable failure.

Preserve friend remarks exactly across restarts and add request, response, persistence, receive-pipeline, and action-level regression coverage.

Fixes #303.
This commit is contained in:
DrSmoothl committed 2026-07-31 23:21:05 +08:00
1 parent b8ccbdbf18
commit 659e0bd3d0
17 files changed
+511 -18

No files matched your search

+2
View File
@@ -128,6 +128,7 @@ export interface MockBridge {
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
updateFriendRemark: ReturnType<typeof vi.fn>;
forgetGroup: ReturnType<typeof vi.fn>;
};
events: { emit: ReturnType<typeof vi.fn> };
@@ -160,6 +161,7 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
forgetGroup: vi.fn(),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
+20 -2
View File
@@ -1,10 +1,11 @@
import { describe, it, expect, vi } from 'vitest';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { protobuf_decode } from '@snowluma/proton';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemarkResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
// Post-namespace migration: FriendApi is a thin facade over the
@@ -65,10 +66,27 @@ describe('apis/friend', () => {
});
it('setRemark uses the current set command for a non-empty remark', async () => {
const bridge = mockBridge();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<OidbSetFriendRemarkResponse>>({
body: {
result: {
target: { targetUid: 'resolved-uid', targetUin: 10001n },
remark: 'best-friend',
},
},
})),
})),
});
await new FriendApi(bridge as any).setRemark(10001, 'best-friend');
expect(bridge.sendRawPacket.mock.calls[0]![0])
.toBe('OidbSvcTrpcTcp.0x912e_0');
expect(bridge.identity.updateFriendRemark)
.toHaveBeenCalledWith('resolved-uid', 10001, 'best-friend');
});
it('setRemark uses the dedicated clear command for an empty remark', async () => {
@@ -328,6 +328,7 @@ describe('apis/group-file', () => {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
forgetGroup: vi.fn(),
},
});
@@ -214,6 +214,71 @@ describe('IdentityService', () => {
}
});
it('keeps friend remark updates after reopening the persistent cache', () => {
const dbPath = tempDbPath('update-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'friend',
remark: 'old-remark',
}]);
expect(identity.updateFriendRemark('u_friend', 22222, 'new-remark')).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
}
});
it.each([
['empty', ''],
['whitespace-only', ' '],
['surrounding-whitespace', ' padded remark '],
])('preserves %s friend remarks exactly after reopening', (_label, remark) => {
const dbPath = tempDbPath('exact-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'friend',
remark: 'old-remark',
}]);
expect(identity.updateFriendRemark('u_friend', 22222, remark)).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
}
});
it('rejects conflicting friend identities before mutating the roster', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberFriends([
{ uin: 22222, uid: 'u_first', nickname: 'first', remark: 'first-remark' },
{ uin: 33333, uid: 'u_second', nickname: 'second', remark: 'second-remark' },
]);
expect(() => identity.updateFriendRemark('u_first', 33333, 'wrong'))
.toThrow(/identity mismatch/);
expect(identity.findFriend(22222)?.remark).toBe('first-remark');
expect(identity.findFriend(33333)?.remark).toBe('second-remark');
});
it('keeps a failed observation in memory, reports degraded, and retries to healthy', async () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-recovery');
+68 -2
View File
@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
// Proton's call-site analyzer keys off the literal type identifier
// printed in `protobuf_encode<X>` — it walks imports by *original*
@@ -15,7 +17,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import type {
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin,
InputStatusNotify, NotifyMessageBody, GroupNameChange, GroupSpecialTitleChange,
OnlineDeviceNotify, ProfileLikeTip,
OnlineDeviceNotify, ProfileLikeTip, FriendRemarkChangedNotify,
} from '@snowluma/proto-defs/notify';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type {
@@ -440,6 +442,70 @@ describe('parseMsgPush Event0x210 subType=179/226 (NewFriend → friend_add)', (
});
});
describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)', () => {
function makeFriendRemarkPacket(
uid: string,
uin: number,
remark: string,
): PacketInfo {
const content = protobuf_encode<FriendRemarkChangedNotify>({
change: {
target: { uid, uin: BigInt(uin) },
remark,
},
updateTime: 1710000000,
nickname: 'Alice',
changeType: 1,
});
return makeEvent0x210PacketAny(364, content);
}
it('decodes a pure internal synchronization event', () => {
const identity = makeIdentity();
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'Alice',
remark: 'old-remark',
}]);
expect(parseMsgPush(
makeFriendRemarkPacket('u_friend', 22222, 'new-remark'),
identity,
)).toEqual([{
kind: 'friend_remark_changed',
time: 1710000000,
selfUin: Number(SELF_UIN),
userUid: 'u_friend',
userUin: 22222,
remark: 'new-remark',
}]);
expect(identity.findFriend(22222)?.remark).toBe('old-remark');
});
it('applies the synchronization at the packet-pipeline boundary', async () => {
const identity = makeIdentity();
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'Alice',
remark: 'old-remark',
}]);
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
resolveStrangerProfile: vi.fn(async () => null),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
await pipeline.process(makeFriendRemarkPacket('u_friend', 22222, 'new-remark'));
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
});
});
describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输入)', () => {
// RE'd from wrapper.linux.node aio_input_state_worker.cc: 0x210/0x115 sys_msg,
// body = InputStatusNotify {fromUid, toUid, notifyItem{eventType@f4}}.