From d05c516ed6ece1a07d7e328dffcea08a29a1f6a5 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 28 Aug 2026 14:44:07 +0800 Subject: [PATCH 01/11] fix(tools): retry a dropped release push and resume from the version commit A failed git push after the version commit used to abort the pipeline. Re-running the same release command now retries the push instead of stopping as out of sync. --- tools/release.mjs | 130 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 100 insertions(+), 30 deletions(-) diff --git a/tools/release.mjs b/tools/release.mjs index 3c713575..e0c83904 100644 --- a/tools/release.mjs +++ b/tools/release.mjs @@ -6,19 +6,27 @@ // pnpm release --dry-run # print plan, change nothing // // What it does, in order: -// 1. Sanity-check: on `dev`, clean tree, in sync with origin/dev. +// 1. Sanity-check: on `dev`, clean tree. Must not be behind origin/dev. +// Ahead-by-one is allowed when HEAD is already this version's +// `chore(release):` commit (resume after a dropped push). // 2. `pnpm bump ` (writes every package.json). // 3. Commit `chore(release): vX.Y.Z` — that prefix triggers the // Promote workflow, which opens (or updates) the dev→main PR and -// auto-merges if the GitHub setting allows. -// 4. Push to origin/dev. +// auto-merges if the GitHub setting allows. Skipped when HEAD is +// already that commit. +// 4. Push to origin/dev (retries transient HTTPS / TLS failures). // 5. (Unless `--no-wait`) poll the Promote PR via `gh` until it // merges, then fetch and fast-forward `main` to `origin/main`, // create `vX.Y.Z` tag, push it — that triggers `release.yml`. +// Fetch / tag push also retry. // 6. Switch back to `dev` so the next `git log` view is back where // you were. +// +// Re-run the same `pnpm release ` after a dropped push; do +// not amend the release commit. import { execSync, spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -66,6 +74,47 @@ function sh(cmd, { capture = false, allowFail = false } = {}) { return ''; } +function sleepSync(ms) { + execSync(`sleep ${Math.max(1, Math.ceil(ms / 1000))}`); +} + +/** Retry git fetch / push. TLS drops after a successful commit used to abort + * the whole pipeline with no way to resume except by hand. */ +function shRetry(cmd, { attempts = 5 } = {}) { + if (dryRun) { + console.log(`[dry-run] $ ${cmd}`); + return ''; + } + let delayMs = 2000; + for (let i = 1; i <= attempts; i++) { + if (i > 1) info(`retry ${i}/${attempts}: ${cmd}`); + const result = spawnSync(cmd, { cwd: repoRoot, shell: true, stdio: 'inherit' }); + if (result.status === 0) return ''; + if (i === attempts) { + const hint = cmd.includes('git push origin dev') + ? `\nRelease commit is already local. Fix the network and re-run: pnpm release ${version}` + : ''; + throw new Error(`Command failed after ${attempts} attempts: ${cmd}${hint}`); + } + warn(`failed (exit ${result.status}), retrying in ${delayMs / 1000}s`); + sleepSync(delayMs); + delayMs *= 2; + } + return ''; +} + +function headSubject() { + return shCapture('git log -1 --format=%s'); +} + +function packageVersion() { + return JSON.parse(readFileSync(path.join(repoRoot, 'package.json'), 'utf-8')).version; +} + +function headIsThisRelease() { + return headSubject() === releaseCommit && packageVersion() === version; +} + function shCapture(cmd) { return execSync(cmd, { cwd: repoRoot, encoding: 'utf-8' }).trim(); } @@ -82,7 +131,9 @@ function info(msg) { console.log(`\x1b[36mi\x1b[0m ${msg}`); } function warn(msg) { console.log(`\x1b[33m!\x1b[0m ${msg}`); } function printManualFinish() { - info('Once the Promote PR merges, finish manually with:'); + info('Once the Promote PR merges, finish with:'); + info(` pnpm release ${version}`); + info('or by hand:'); info(' git fetch origin refs/heads/main:refs/remotes/origin/main'); info(' git switch main'); info(' git merge --ff-only origin/main'); @@ -92,7 +143,7 @@ function printManualFinish() { function syncMain() { // Use a fully qualified refspec and an explicit fast-forward so release // behavior cannot be changed by the caller's pull/rebase configuration. - sh('git fetch origin refs/heads/main:refs/remotes/origin/main --quiet'); + shRetry('git fetch origin refs/heads/main:refs/remotes/origin/main --quiet'); sh('git switch main'); sh('git merge --ff-only origin/main'); @@ -128,43 +179,53 @@ function preflight() { preflightFail(`Working tree is not clean. Commit or stash first.\n${dirty}`); } - // Make sure we're up to date with origin/dev so the bump commit doesn't - // collide with someone else's push. - shCapture('git fetch origin dev --quiet'); + // Make sure we're not behind origin/dev so the bump commit doesn't + // collide with someone else's push. Ahead-by-one is a resume: the + // previous run committed the bump then dropped the push. + shRetry('git fetch origin refs/heads/dev:refs/remotes/origin/dev --quiet'); const local = shCapture('git rev-parse dev'); const remote = shCapture('git rev-parse origin/dev'); if (local !== remote) { const ahead = shCapture('git rev-list --count origin/dev..dev'); const behind = shCapture('git rev-list --count dev..origin/dev'); - preflightFail(`dev is not in sync with origin/dev (ahead=${ahead}, behind=${behind}). Pull / push first.`); + if (behind !== '0') { + preflightFail(`dev is behind origin/dev (behind=${behind}). Pull first.`); + } + if (ahead === '1' && headIsThisRelease()) { + warn(`dev is ahead of origin/dev by 1; HEAD is ${releaseCommit}, will resume from push`); + } else { + preflightFail(`dev is not in sync with origin/dev (ahead=${ahead}, behind=${behind}). Pull / push first.`); + } } - if (!dryRun) ok(`on dev, clean, in sync with origin/dev`); + if (!dryRun) ok(`on dev, clean, ready to release ${tag}`); } // ───────────── step 2-4: bump + commit + push dev ───────────── function bumpAndPushDev() { - sh(`node tools/bump-version.mjs ${version}`); - ok(`bumped all package.json files to ${version}`); + if (!dryRun && headIsThisRelease()) { + warn(`HEAD is already ${releaseCommit}; skipping bump and commit`); + } else { + sh(`node tools/bump-version.mjs ${version}`); + ok(`bumped all package.json files to ${version}`); - if (dryRun) { - info(`would commit "${releaseCommit}" and push origin dev`); - return; + if (dryRun) { + info(`would commit "${releaseCommit}" and push origin dev`); + return; + } + + const changed = shCapture('git status --porcelain'); + if (!changed) { + warn(`no version changes — package.json already at ${version}, skipping commit`); + } else { + sh('git add package.json packages/*/package.json'); + sh(`git commit -m "${releaseCommit}"`); + ok(`committed ${releaseCommit}`); + } } - const changed = shCapture('git status --porcelain'); - if (!changed) { - // Already at this version. Probably re-running. Still try to push tag. - warn(`no version changes — package.json already at ${version}, skipping commit`); - return; - } - - sh('git add package.json packages/*/package.json'); - sh(`git commit -m "${releaseCommit}"`); - ok(`committed ${releaseCommit}`); - - sh('git push origin dev'); + shRetry('git push origin dev'); ok(`pushed to origin/dev — Promote workflow should kick off shortly`); } @@ -236,9 +297,18 @@ async function waitAndTag() { warn('Tagging anyway, but the release artifact name may not match.'); } - sh(`git tag ${tag}`); - sh(`git push origin ${tag}`); - ok(`tagged and pushed ${tag} — release workflow will pick it up`); + if (dryRun) { + info(`would tag ${tag} and push origin ${tag}`); + } else { + const exists = spawnSync('git', ['rev-parse', '-q', '--verify', `refs/tags/${tag}`], { + cwd: repoRoot, + stdio: 'ignore', + }).status === 0; + if (exists) warn(`tag ${tag} already exists locally`); + else sh(`git tag ${tag}`); + shRetry(`git push origin ${tag}`); + ok(`tagged and pushed ${tag} — release workflow will pick it up`); + } // Hop back to dev so the user lands where they started. sh('git checkout dev'); From 9e279108850c39abcc447b21ed66ea4f1114098f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 29 Aug 2026 19:11:10 +0800 Subject: [PATCH 02/11] fix(onebot): accept an empty group_id on private send_msg Some clients fill unused group_id with an empty string when sending a private message through send_msg. Treat that empty string as absent so the send is a normal private chat. Fixes #426 --- packages/onebot/src/actions/message.ts | 16 +++++++- packages/onebot/tests/actions-message.test.ts | 38 +++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index e92c34c8..bdd2952e 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -1,9 +1,21 @@ import { createLogger } from '@snowluma/common/logger'; import type { JsonObject, JsonValue } from '../types'; import type { ApiActionContext } from '../api-handler'; -import { defineAction, groupAction, f } from '../action-kit'; +import { defineAction, groupAction, f, type Field } from '../action-kit'; import { RETCODE, failedResponse, okResponse } from '../types'; +/** send_msg only (#426). Some clients send `group_id: ""` on private chats. + * Treat that exact empty string as absent. Do not change `f.groupId()`. */ +function sendMsgOptionalGroupId(): Field { + const inner = f.groupId().optional(); + return Object.assign(Object.create(inner) as Field, { + coerce(raw: Parameters['coerce']>[0], field: string) { + if (raw === '') return { ok: true as const, value: undefined }; + return inner.coerce(raw, field); + }, + }); +} + const log = createLogger('OneBot'); /** @@ -47,7 +59,7 @@ export const actions = [ params: { message: f.message(), message_type: f.string().optional(), - group_id: f.groupId().optional(), + group_id: sendMsgOptionalGroupId(), user_id: f.userId().optional(), auto_escape: f.bool().default(false), }, diff --git a/packages/onebot/tests/actions-message.test.ts b/packages/onebot/tests/actions-message.test.ts index 35d55765..adfd8a06 100644 --- a/packages/onebot/tests/actions-message.test.ts +++ b/packages/onebot/tests/actions-message.test.ts @@ -84,6 +84,24 @@ describe('send_msg parse', () => { reason: 'must be >= 1', }); }); + + it('treats an empty group_id string as absent', () => { + expect(sendMsg.parse({ + message_type: 'private', + user_id: 1316864423, + group_id: '', + message: 'hi', + })).toEqual({ + ok: true, + value: { + message: 'hi', + message_type: 'private', + group_id: undefined, + user_id: 1316864423, + auto_escape: false, + }, + }); + }); }); describe('send_msg run', () => { @@ -120,6 +138,26 @@ describe('send_msg run', () => { expect(sendPrivateMessage).not.toHaveBeenCalled(); }); + it('sends a private message when group_id is an empty string', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9006 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'private', + user_id: 1316864423, + group_id: '', + message: [{ type: 'image', data: { file: 'base64://x' } }], + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9006 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[ + 1316864423, + [{ type: 'image', data: { file: 'base64://x' } }], + false, + undefined, + ]]); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + it('sends a private message when only user_id is present', async () => { const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); const sendPrivateMessage = vi.fn(async () => ({ messageId: 9003 })); From 9cdbcb029933872c61da8fc363f52b1692451828 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 29 Aug 2026 23:34:43 +0800 Subject: [PATCH 03/11] fix(identity): keep live group membership in sync with join and leave A join now counts the member as in the group right away. A leave drops them from the live roster without forgetting who they are. Other sightings still do not mean the person is in the group. --- packages/core/tests/identity-service.test.ts | 68 +++++++++++++++++++ packages/protocol/src/identity-service.ts | 39 ++++++++++- packages/protocol/src/packet-pipeline.ts | 4 ++ .../packet-pipeline-roster-refresh.test.ts | 23 +++++++ 4 files changed, 132 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/identity-service.test.ts b/packages/core/tests/identity-service.test.ts index 0faf49cc..7df8061a 100644 --- a/packages/core/tests/identity-service.test.ts +++ b/packages/core/tests/identity-service.test.ts @@ -809,6 +809,7 @@ describe('IdentityService', () => { ['group requests', () => identity.rememberGroupRequests([request])], ['request identity', () => identity.rememberRequestIdentity({ uid: 'u_request', uin: 88888 })], ['group member identity', () => identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_new', uin: 99999 })], + ['group member joined', () => identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_new', uin: 99999 })], ['group member inactive', () => identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin })], ]; @@ -823,6 +824,73 @@ describe('IdentityService', () => { expect(identity.findUinByUid('u_request')).toBeNull(); }); + it('does not treat identity-only sightings as live group members', () => { + const identity = IdentityService.memory(SELF_UIN); + identity.rememberGroups([makeGroup()]); + identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_seen', uin: 88888 }); + + expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull(); + expect(identity.findUinByUid('u_seen')).toBe(88888); + identity.close(); + }); + + it('records a thin live member on join without inventing roster details', () => { + const identity = IdentityService.memory(SELF_UIN); + identity.rememberGroups([makeGroup()]); + const existing = makeMember(33333, 'u_existing', 'card'); + identity.rememberGroupMembers(GROUP_ID, [existing]); + + identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 }); + identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 }); + identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_ignored', uin: 0 }); + + const joined = identity.findGroupMember(GROUP_ID, 44444); + expect(joined).toMatchObject({ + uin: 44444, + uid: 'u_join', + nickname: '', + card: '', + role: 'member', + }); + expect(joined?.isRobot).toBeUndefined(); + expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card'); + identity.close(); + }); + + it('drops a leaver from the live roster and keeps their identity mapping', () => { + const identity = IdentityService.memory(SELF_UIN); + identity.rememberGroups([makeGroup()]); + const member = makeMember(33333, 'u_member', 'card'); + identity.rememberGroupMembers(GROUP_ID, [member]); + + identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin }); + + expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull(); + expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid); + identity.close(); + }); + + it('keeps a leaver out of the live roster after reopen', () => { + const dbPath = tempDbPath('leave-live-roster'); + const member = makeMember(33333, 'u_member', 'card'); + + { + const identity = new IdentityService(SELF_UIN, dbPath); + identity.rememberGroups([makeGroup()]); + identity.rememberGroupMembers(GROUP_ID, [member]); + identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin }); + expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull(); + identity.close(); + } + + { + const identity = new IdentityService(SELF_UIN, dbPath); + expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull(); + expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid); + identity.close(); + } + }); + it('marks missing members inactive only after a successful full refresh', () => { const dbPath = tempDbPath('inactive-refresh'); const first = makeMember(33333, 'u_first'); diff --git a/packages/protocol/src/identity-service.ts b/packages/protocol/src/identity-service.ts index a34302dd..06c38f98 100644 --- a/packages/protocol/src/identity-service.ts +++ b/packages/protocol/src/identity-service.ts @@ -682,12 +682,47 @@ export class IdentityService { }))); } + /** Live 花名册: the joiner is in this group now. Does not invent card/role/isRobot. + * No-op when the UIN is missing, the group is unknown, or the member is already present. */ + rememberGroupMemberJoined( + groupId: number, + identity: { uid?: string; uin?: number }, + ): void { + this.beginObservation('group member joined'); + const uin = normalizeUin(identity.uin); + if (uin === null) return; + const g = this.groups_.get(groupId); + if (!g || g.members.has(uin)) return; + const uid = normalizeUid(identity.uid) ?? ''; + this.rememberUidUin(uid, uin); + g.members.set(uin, { + uin, + uid, + nickname: '', + card: '', + role: 'member', + level: 0, + title: '', + joinTime: 0, + lastSentTime: 0, + shutUpTime: 0, + }); + } + markGroupMemberInactive(groupId: number, identity: { uid?: string; uin?: number }): void { this.beginObservation('group member inactive'); const observed = { ...identity }; + const uid = normalizeUid(observed.uid); + const uin = normalizeUin(observed.uin); + const g = this.groups_.get(groupId); + if (g) { + if (uin !== null) g.members.delete(uin); + else if (uid) { + const member = this.findGroupMemberByUid(groupId, uid); + if (member) g.members.delete(member.uin); + } + } this.runWrite('group member inactive', () => { - const uid = normalizeUid(observed.uid); - const uin = normalizeUin(observed.uin); if (!uid && uin === null) return; const rows = this.findMemberRows(groupId, uid, uin); const updatedAt = nowSeconds(); diff --git a/packages/protocol/src/packet-pipeline.ts b/packages/protocol/src/packet-pipeline.ts index 4f708898..62cbee2c 100644 --- a/packages/protocol/src/packet-pipeline.ts +++ b/packages/protocol/src/packet-pipeline.ts @@ -678,6 +678,10 @@ export class IncomingPacketPipeline { uid: event.operatorUid, uin: event.operatorUin, }); + this.deps.identity.rememberGroupMemberJoined(event.groupId, { + uid: event.userUid, + uin: event.userUin, + }); break; case 'group_member_leave': this.deps.identity.markGroupMemberInactive(event.groupId, { diff --git a/packages/protocol/tests/packet-pipeline-roster-refresh.test.ts b/packages/protocol/tests/packet-pipeline-roster-refresh.test.ts index d5191964..8bd10930 100644 --- a/packages/protocol/tests/packet-pipeline-roster-refresh.test.ts +++ b/packages/protocol/tests/packet-pipeline-roster-refresh.test.ts @@ -138,6 +138,29 @@ describe('IncomingPacketPipeline roster refresh', () => { expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID); }); + it('known-group join records the joiner immediately and does not invent the operator', async () => { + const { pipeline, identity, fetchGroupList, fetchGroupMemberList } = makePipeline({ plantGroup: true }); + pipeline.registerCmd('test.roster', () => [join({ userUin: 33333, userUid: 'u_new', operatorUin: 44444, operatorUid: 'u_op' })]); + await pipeline.process(pkt()); + + expect(identity.findGroupMember(GROUP_ID, 33333)?.uid).toBe('u_new'); + expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined(); + expect(identity.findGroupMember(GROUP_ID, 44444)).toBeNull(); + expect(identity.findUinByUid('u_op')).toBe(44444); + expect(fetchGroupList).not.toHaveBeenCalled(); + expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID); + }); + + it('known-group leave drops the member immediately and keeps their identity mapping', async () => { + const { pipeline, identity } = makePipeline({ plantGroup: true }); + identity.rememberGroupMembers(GROUP_ID, [makeMember(22222, 'u_member')]); + pipeline.registerCmd('test.roster', () => [leave()]); + await pipeline.process(pkt()); + + expect(identity.findGroupMember(GROUP_ID, 22222)).toBeNull(); + expect(identity.findUidByUin(22222, GROUP_ID)).toBe('u_member'); + }); + it('known-group join / leave / admin fetch only the member list', async () => { for (const event of [join(), leave(), admin()]) { const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline({ plantGroup: true }); From 117335166f7eace244faf238d2c8e0258e18d2a6 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 29 Aug 2026 23:58:56 +0800 Subject: [PATCH 04/11] refactor(protocol): keep custom-face list encoding with delete Profile still turns ids into image URLs and slices the count. Asking for ids no longer round-trips through those URLs. --- packages/core/src/bridge/apis/profile.ts | 35 ++----- packages/core/tests/actions/profile.test.ts | 88 +++++++++++++++++ packages/onebot/src/actions/extended.ts | 9 +- .../onebot/tests/extended-actions.test.ts | 40 ++++++++ .../custom-face/fetch-custom-face-list.ts | 44 +++++++++ .../src/oidb-services/custom-face/shared.ts | 5 +- .../fetch-custom-face-list.test.ts | 96 +++++++++++++++++++ 7 files changed, 280 insertions(+), 37 deletions(-) create mode 100644 packages/protocol/src/oidb-services/custom-face/fetch-custom-face-list.ts create mode 100644 packages/protocol/tests/oidb-services/custom-face/fetch-custom-face-list.test.ts diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts index 19738bcb..bd09c8f5 100644 --- a/packages/core/src/bridge/apis/profile.ts +++ b/packages/core/src/bridge/apis/profile.ts @@ -1,6 +1,4 @@ import type { - FaceroamOpReq, - FaceroamOpResp, GroupAvatarExtra, SetStatusReq, SetStatusResp, @@ -8,6 +6,7 @@ import type { import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face'; import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face'; import { FetchCustomFaceDetail } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-detail'; +import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-list'; import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face'; import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face'; import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face'; @@ -167,28 +166,13 @@ export class ProfileApi { })); } - private async fetchCustomFaceIds(count: number): Promise { + async fetchCustomFaceIds(count = 10): Promise { if (!Number.isInteger(count) || count < 0) { throw new Error('custom face count must be a non-negative integer'); } if (count === 0) return []; - const req = { - inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' }, - uin: BigInt(this.ctx.identity.uin), - field3: 1, - field6: 1, - }; - const request = protobuf_encode(req); - const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'fetch custom face failed'); - } - const resp = protobuf_decode(result.responseData); - if (!resp || (resp.retCode ?? 0) !== 0) { - throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`); - } - const faceIds = resp.item?.faceIds || []; + const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin }); return faceIds.slice(0, count); } @@ -196,7 +180,7 @@ export class ProfileApi { return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`; } - /** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */ + /** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */ deleteCustomFace(emojiId: string): Promise { return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId }); } @@ -211,9 +195,8 @@ export class ProfileApi { } /** - * 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的 - * URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串 - * 则清空备注。 + * 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id + * 中段解析,无需调用方单独提供。desc 为空串则清空备注。 */ modifyCustomFace(emojiId: string, desc: string): Promise { return ModifyCustomFace.invoke(this.ctx, { @@ -231,11 +214,7 @@ export class ProfileApi { */ async moveCustomFaceToFront(emojiId: string): Promise { // 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序) - const urls = await this.fetchCustomFace(1000); - const ids = urls.map((url) => { - const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url); - return m ? m[1] : ''; - }).filter(Boolean); + const ids = await this.fetchCustomFaceIds(1000); const idx = ids.indexOf(emojiId); if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`); // 新顺序:目标挪到第一,其余按原顺序 diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index 96fa4aed..6ce24282 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -300,6 +300,94 @@ describe('apis/profile', () => { expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); }); + it('fetchCustomFaceIds slices the Faceroam list and skips the packet for count=0', async () => { + const bridge = mockBridge(); + const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0'; + const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0'; + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + retCode: 0, + item: { faceIds: [emojiA, emojiB] }, + })), + } as any); + + const api = new ProfileApi(bridge as any); + await expect(api.fetchCustomFaceIds(1)).resolves.toEqual([emojiA]); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('Faceroam.OpReq'); + + await expect(api.fetchCustomFaceIds(0)).resolves.toEqual([]); + expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); + }); + + it('fetchCustomFace maps ids to image urls', async () => { + const bridge = mockBridge(); + const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0'; + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + retCode: 0, + item: { faceIds: [emojiA] }, + })), + } as any); + + await expect(new ProfileApi(bridge as any).fetchCustomFace(1)).resolves.toEqual([ + `https://p.qpic.cn/qq_expression/10001/${emojiA}/0`, + ]); + }); + + it('rejects a negative custom-face count before sending', async () => { + const bridge = mockBridge(); + await expect(new ProfileApi(bridge as any).fetchCustomFaceIds(-1)).rejects.toThrow( + /non-negative integer/, + ); + expect(bridge.sendRawPacket).not.toHaveBeenCalled(); + }); + + it('moveCustomFaceToFront reorders from the id list without parsing urls', async () => { + const bridge = mockBridge(); + const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0'; + const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0'; + bridge.sendRawPacket + .mockResolvedValueOnce({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + retCode: 0, + item: { faceIds: [emojiA, emojiB] }, + })), + } as any) + .mockResolvedValue({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ + body: { retCode: 0 }, + })), + } as any); + + await new ProfileApi(bridge as any).moveCustomFaceToFront(emojiB); + + expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([ + 'Faceroam.OpReq', + 'OidbSvcTrpcTcp.0x902f_1', + 'OidbSvcTrpcTcp.0x902e_1', + ]); + const moveBody = protobuf_decode>( + bridge.sendRawPacket.mock.calls[2]![1], + ); + expect(moveBody.body?.emojis?.map((emoji) => emoji.emojiId)).toEqual([emojiB, emojiA]); + }); + it('fetchCustomFaceDetails supplements the Faceroam ids with server descriptions (#333)', async () => { const bridge = mockBridge(); const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0'; diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 28e6cf64..73d07af8 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1266,15 +1266,10 @@ export const actions = [ return_type: f.string().default('url'), }, run: async (p, ctx) => { - const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count); if (p.return_type === 'id') { - const emojiIds = urls.map((url) => { - const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url); - return m ? m[1] : ''; - }).filter(Boolean); - return okResponse(emojiIds); + return okResponse(await ctx.bridge.apis.profile.fetchCustomFaceIds(p.count)); } - return okResponse(urls); + return okResponse(await ctx.bridge.apis.profile.fetchCustomFace(p.count)); }, }), diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index ee3b7369..dc25118b 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -61,6 +61,7 @@ const APIS_ROUTING: Record = { setAvatar: ['profile', 'setAvatar'], setGroupAvatar: ['profile', 'setGroupAvatar'], fetchCustomFace: ['profile', 'fetchCustomFace'], + fetchCustomFaceIds: ['profile', 'fetchCustomFaceIds'], fetchCustomFaceDetails: ['profile', 'fetchCustomFaceDetails'], getProfileLike: ['profile', 'getLike'], getUnidirectionalFriendList: ['profile', 'getUnidirectionalFriendList'], @@ -1486,6 +1487,45 @@ describe('extended-actions / set_group_portrait', () => { }); }); +describe('extended-actions / fetch_custom_face', () => { + it('return_type=id uses the id list directly', async () => { + const fetchCustomFaceIds = vi.fn(async () => [ + '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0', + '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0', + ]); + const fetchCustomFace = vi.fn(); + const bridge = fakeBridge({ fetchCustomFaceIds, fetchCustomFace }); + + const response = await makeHandler(fakeCtx(bridge)).handle('fetch_custom_face', { + count: '2', + return_type: 'id', + }); + + expect(fetchCustomFaceIds).toHaveBeenCalledWith(2); + expect(fetchCustomFace).not.toHaveBeenCalled(); + expect(response).toMatchObject({ + status: 'ok', + data: [ + '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0', + '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0', + ], + }); + }); + + it('default return_type uses image urls', async () => { + const url = 'https://p.qpic.cn/qq_expression/10001/id/0'; + const fetchCustomFace = vi.fn(async () => [url]); + const fetchCustomFaceIds = vi.fn(); + const bridge = fakeBridge({ fetchCustomFace, fetchCustomFaceIds }); + + const response = await makeHandler(fakeCtx(bridge)).handle('fetch_custom_face', { count: '1' }); + + expect(fetchCustomFace).toHaveBeenCalledWith(1); + expect(fetchCustomFaceIds).not.toHaveBeenCalled(); + expect(response).toMatchObject({ status: 'ok', data: [url] }); + }); +}); + describe('extended-actions / fetch_custom_face_detail', () => { it('returns real packet-backed fields with SnowLuma and NapCat resource aliases', async () => { const fetchCustomFaceDetails = vi.fn(async () => [{ diff --git a/packages/protocol/src/oidb-services/custom-face/fetch-custom-face-list.ts b/packages/protocol/src/oidb-services/custom-face/fetch-custom-face-list.ts new file mode 100644 index 00000000..1d995e2f --- /dev/null +++ b/packages/protocol/src/oidb-services/custom-face/fetch-custom-face-list.ts @@ -0,0 +1,44 @@ +// Faceroam.OpReq opType=1 — 拉取当前账号的收藏表情 id 列表。 +// +// 和 delete 同一个 trpc service,区别在 field3=1、inner 带 qqVersion、 +// 并置 field6=1。响应 item.faceIds 是完整列表;截条数由调用方做。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { FaceroamOpReq, FaceroamOpResp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { OidbSender } from '../../oidb-service'; +import { FACEROAM_SERVICE, makeInner } from './shared'; + +export namespace FetchCustomFaceList { + export interface Params { + /** 当前账号 UIN,写入 field2。 */ + uin: string; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FaceroamOpReq => ({ + inner: makeInner(true), + uin: BigInt(p.uin), + field3: 1, + field6: 1, + }); + + export const encode = (req: FaceroamOpReq): Uint8Array => + protobuf_encode(req); + + export const decode = (bytes: Uint8Array): FaceroamOpResp => + protobuf_decode(bytes); + + export async function invoke(deps: Deps, params: Params): Promise { + const body = encode(serialize(deps, params)); + const result = await deps.sendRawPacket(FACEROAM_SERVICE, body); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'fetch custom face failed'); + } + const resp = decode(result.responseData); + if (!resp || (resp.retCode ?? 0) !== 0) { + throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`); + } + return resp.item?.faceIds || []; + } +} diff --git a/packages/protocol/src/oidb-services/custom-face/shared.ts b/packages/protocol/src/oidb-services/custom-face/shared.ts index 7f38d684..c719ec6a 100644 --- a/packages/protocol/src/oidb-services/custom-face/shared.ts +++ b/packages/protocol/src/oidb-services/custom-face/shared.ts @@ -15,7 +15,8 @@ export const FACEROAM_SERVICE = 'Faceroam.OpReq'; // 真出问题再从 identity 里取。 /** osVersion 字符串,Faceroam inner 与 0x902e 业务体 f2 共用。 */ export const CLIENT_VERSION = '10.0.26200'; -const CLIENT_BUILD = '9.9.26-44343'; +/** qqVersion on the Faceroam list inner. Keep the value list already sends. Delete omits this field. */ +const LIST_QQ_VERSION = '9.9.28-46928'; /** * 构造请求 inner(field1 客户端环境)。fetch 带 qqVersion,delete 不带—— @@ -23,6 +24,6 @@ const CLIENT_BUILD = '9.9.26-44343'; */ export function makeInner(withQqVersion: boolean): FaceroamOpReqInner { const inner: FaceroamOpReqInner = { field1: 1, osVersion: CLIENT_VERSION }; - if (withQqVersion) inner.qqVersion = CLIENT_BUILD; + if (withQqVersion) inner.qqVersion = LIST_QQ_VERSION; return inner; } diff --git a/packages/protocol/tests/oidb-services/custom-face/fetch-custom-face-list.test.ts b/packages/protocol/tests/oidb-services/custom-face/fetch-custom-face-list.test.ts new file mode 100644 index 00000000..453ae189 --- /dev/null +++ b/packages/protocol/tests/oidb-services/custom-face/fetch-custom-face-list.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import type { FaceroamOpReq, FaceroamOpResp } from '@snowluma/proto-defs/oidb-actions/base'; + +import { FetchCustomFaceList } from '../../../src/oidb-services/custom-face/fetch-custom-face-list'; + +const SAMPLE_UIN = '10001'; +const EMOJI_A = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0'; +const EMOJI_B = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0'; + +function encodeLegacyList(uin: string): Uint8Array { + return protobuf_encode({ + inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' }, + uin: BigInt(uin), + field3: 1, + field6: 1, + }); +} + +function makeSender(opts: { + faces?: FaceroamOpResp; + success?: boolean; + gotResponse?: boolean; + errorMessage?: string; + responseData?: Uint8Array | null; +} = {}) { + const result: SendPacketResult = { + success: opts.success ?? true, + gotResponse: opts.gotResponse ?? true, + errorCode: 0, + errorMessage: opts.errorMessage ?? '', + responseData: opts.responseData !== undefined + ? opts.responseData + : Buffer.from(protobuf_encode( + opts.faces ?? { retCode: 0, item: { faceIds: [EMOJI_A, EMOJI_B] } }, + )), + }; + return { sendRawPacket: vi.fn(async () => result) }; +} + +describe('FetchCustomFaceList namespace', () => { + describe('serialize + encode', () => { + it('keeps the list request bytes the ProfileApi fetch already sent', () => { + const req = FetchCustomFaceList.serialize({} as any, { uin: SAMPLE_UIN }); + const hex = Buffer.from(FetchCustomFaceList.encode(req)).toString('hex'); + expect(hex).toBe(Buffer.from(encodeLegacyList(SAMPLE_UIN)).toString('hex')); + }); + + it('sends qqVersion on inner and sets field3=1 / field6=1', () => { + const req = FetchCustomFaceList.serialize({} as any, { uin: SAMPLE_UIN }); + expect(req.inner?.qqVersion).toBe('9.9.28-46928'); + expect(req.inner?.osVersion).toBe('10.0.26200'); + expect(req.field3).toBe(1); + expect(req.field6).toBe(1); + expect(req.body).toBeUndefined(); + }); + }); + + describe('invoke', () => { + it('routes through "Faceroam.OpReq" and returns the id list', async () => { + const sender = makeSender(); + await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).resolves.toEqual([ + EMOJI_A, + EMOJI_B, + ]); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('Faceroam.OpReq'); + const [, body] = sender.sendRawPacket.mock.calls[0]!; + expect(Buffer.from(body as Uint8Array).toString('hex')).toBe( + Buffer.from(encodeLegacyList(SAMPLE_UIN)).toString('hex'), + ); + }); + + it('returns an empty list when the item is missing', async () => { + const sender = makeSender({ faces: { retCode: 0 } }); + await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).resolves.toEqual([]); + }); + + it('throws when the sender reports no response', async () => { + const sender = makeSender({ + success: false, + gotResponse: false, + errorMessage: 'timeout', + responseData: null, + }); + await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).rejects.toThrow(/timeout/); + }); + + it('throws when the Faceroam retCode is non-zero', async () => { + const sender = makeSender({ faces: { retCode: 1, message: 'denied' } }); + await expect(FetchCustomFaceList.invoke(sender, { uin: SAMPLE_UIN })).rejects.toThrow( + /fetch custom face error: denied/, + ); + }); + }); +}); From f6adadcd12b96a6453437e5a4731fcb435c927d8 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 30 Aug 2026 00:56:01 +0800 Subject: [PATCH 05/11] refactor(onebot): declare every action param the handler reads Action handlers now only see fields from the param table. Extra client keys are still ignored. Garbage values on declared numbers fail instead of becoming zero. --- packages/mcp/src/generated/catalog.json | 389 ++++++++++++++++-- packages/mcp/src/generated/catalog.ts | 389 ++++++++++++++++-- packages/onebot/src/action-kit.ts | 14 +- packages/onebot/src/actions/extended.ts | 192 ++++++--- packages/onebot/src/actions/group-info.ts | 8 +- packages/onebot/src/actions/request.ts | 10 +- .../onebot/src/actions/stream-download.ts | 8 +- packages/onebot/src/api-handler.ts | 38 -- packages/onebot/tests/action-kit.test.ts | 21 +- packages/onebot/tests/actions-request.test.ts | 64 +-- .../onebot/tests/api-handler-trace.test.ts | 2 +- .../onebot/tests/extended-actions.test.ts | 44 ++ .../tests/helpers/compiled-action-handler.ts | 2 +- packages/onebot/tests/streaming.test.ts | 6 +- 14 files changed, 952 insertions(+), 235 deletions(-) diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index ff71543c..a6edca5d 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -726,6 +726,24 @@ "type": "integer", "minimum": 1 } + }, + { + "name": "button_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "callback_data", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" } ], "invariants": [], @@ -745,12 +763,21 @@ "msg_seq": { "type": "integer", "minimum": 1 + }, + "button_id": { + "type": "string", + "minLength": 1 + }, + "callback_data": { + "type": "string", + "default": "" } }, "required": [ "group_id", "bot_appid", - "msg_seq" + "msg_seq", + "button_id" ], "additionalProperties": true }, @@ -1577,6 +1604,12 @@ "type": "string" }, "default": "" + }, + { + "name": "headers", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -1594,7 +1627,8 @@ "name": { "type": "string", "default": "" - } + }, + "headers": {} }, "additionalProperties": true }, @@ -2268,13 +2302,15 @@ "params": [ { "name": "message_id", - "type": "string", - "required": false, + "type": "messageId", + "required": true, + "role": "message_id", "schema": { - "type": "string" - }, - "default": "", - "role": "message_id" + "type": "integer", + "not": { + "const": 0 + } + } } ], "invariants": [], @@ -2282,11 +2318,16 @@ "type": "object", "properties": { "message_id": { - "type": "string", - "default": "", + "type": "integer", + "not": { + "const": 0 + }, "x-role": "message_id" } }, + "required": [ + "message_id" + ], "additionalProperties": true }, "category": "扩展" @@ -3661,6 +3702,14 @@ "schema": { "type": "string" } + }, + { + "name": "message_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + } } ], "invariants": [], @@ -3669,6 +3718,9 @@ "properties": { "id": { "type": "string" + }, + "message_id": { + "type": "string" } }, "additionalProperties": true @@ -4766,9 +4818,11 @@ }, { "name": "type", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } } ], "invariants": [], @@ -4781,7 +4835,9 @@ "description": "群号", "x-role": "group_id" }, - "type": {} + "type": { + "type": "string" + } }, "required": [ "group_id" @@ -6138,11 +6194,90 @@ "aliases": [], "summary": "获取小程序卡片 ark", "readOnly": true, - "params": [], + "params": [ + { + "name": "type", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "title", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "desc", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "picUrl", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "pic_url", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "jumpUrl", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "jump_url", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], "invariants": [], "inputSchema": { "type": "object", - "properties": {}, + "properties": { + "type": { + "type": "string" + }, + "title": { + "type": "string" + }, + "desc": { + "type": "string" + }, + "picUrl": { + "type": "string" + }, + "pic_url": { + "type": "string" + }, + "jumpUrl": { + "type": "string" + }, + "jump_url": { + "type": "string" + } + }, "additionalProperties": true }, "category": "扩展" @@ -8748,6 +8883,62 @@ "schema": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } + }, + { + "name": "message_type", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "group_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "user_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "source", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "summary", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "prompt", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "news", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -8759,7 +8950,28 @@ }, "message": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." - } + }, + "message_type": { + "type": "string" + }, + "group_id": { + "type": "integer", + "minimum": 0 + }, + "user_id": { + "type": "integer", + "minimum": 0 + }, + "source": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "news": {} }, "additionalProperties": true }, @@ -8917,6 +9129,36 @@ "schema": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } + }, + { + "name": "source", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "summary", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "prompt", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "news", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -8934,7 +9176,17 @@ }, "message": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." - } + }, + "source": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "news": {} }, "required": [ "group_id" @@ -9280,6 +9532,36 @@ "schema": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } + }, + { + "name": "source", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "summary", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "prompt", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "news", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -9296,7 +9578,17 @@ }, "message": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." - } + }, + "source": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "news": {} }, "required": [ "user_id" @@ -9983,15 +10275,19 @@ }, { "name": "sub_type", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } }, { "name": "type", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } }, { "name": "approve", @@ -10020,8 +10316,12 @@ "type": "string", "minLength": 1 }, - "sub_type": {}, - "type": {}, + "sub_type": { + "type": "string" + }, + "type": { + "type": "string" + }, "approve": { "type": "boolean", "default": true @@ -11692,23 +11992,31 @@ "params": [ { "name": "longNick", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } }, { "name": "long_nick", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } } ], "invariants": [], "inputSchema": { "type": "object", "properties": { - "longNick": {}, - "long_nick": {} + "longNick": { + "type": "string" + }, + "long_nick": { + "type": "string" + } }, "additionalProperties": true }, @@ -11933,17 +12241,30 @@ "params": [ { "name": "words", - "type": "raw", - "required": false, - "schema": {} + "type": "string[]", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } } ], "invariants": [], "inputSchema": { "type": "object", "properties": { - "words": {} + "words": { + "type": "array", + "items": { + "type": "string" + } + } }, + "required": [ + "words" + ], "additionalProperties": true }, "category": "扩展" diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index ae11f581..d02a729c 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -729,6 +729,24 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "minimum": 1 } + }, + { + "name": "button_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "callback_data", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" } ], "invariants": [], @@ -748,12 +766,21 @@ export const ACTIONS: CatalogAction[] = [ "msg_seq": { "type": "integer", "minimum": 1 + }, + "button_id": { + "type": "string", + "minLength": 1 + }, + "callback_data": { + "type": "string", + "default": "" } }, "required": [ "group_id", "bot_appid", - "msg_seq" + "msg_seq", + "button_id" ], "additionalProperties": true }, @@ -1580,6 +1607,12 @@ export const ACTIONS: CatalogAction[] = [ "type": "string" }, "default": "" + }, + { + "name": "headers", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -1597,7 +1630,8 @@ export const ACTIONS: CatalogAction[] = [ "name": { "type": "string", "default": "" - } + }, + "headers": {} }, "additionalProperties": true }, @@ -2271,13 +2305,15 @@ export const ACTIONS: CatalogAction[] = [ "params": [ { "name": "message_id", - "type": "string", - "required": false, + "type": "messageId", + "required": true, + "role": "message_id", "schema": { - "type": "string" - }, - "default": "", - "role": "message_id" + "type": "integer", + "not": { + "const": 0 + } + } } ], "invariants": [], @@ -2285,11 +2321,16 @@ export const ACTIONS: CatalogAction[] = [ "type": "object", "properties": { "message_id": { - "type": "string", - "default": "", + "type": "integer", + "not": { + "const": 0 + }, "x-role": "message_id" } }, + "required": [ + "message_id" + ], "additionalProperties": true }, "category": "扩展" @@ -3664,6 +3705,14 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" } + }, + { + "name": "message_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + } } ], "invariants": [], @@ -3672,6 +3721,9 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "id": { "type": "string" + }, + "message_id": { + "type": "string" } }, "additionalProperties": true @@ -4769,9 +4821,11 @@ export const ACTIONS: CatalogAction[] = [ }, { "name": "type", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } } ], "invariants": [], @@ -4784,7 +4838,9 @@ export const ACTIONS: CatalogAction[] = [ "description": "群号", "x-role": "group_id" }, - "type": {} + "type": { + "type": "string" + } }, "required": [ "group_id" @@ -6141,11 +6197,90 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "获取小程序卡片 ark", "readOnly": true, - "params": [], + "params": [ + { + "name": "type", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "title", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "desc", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "picUrl", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "pic_url", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "jumpUrl", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "jump_url", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], "invariants": [], "inputSchema": { "type": "object", - "properties": {}, + "properties": { + "type": { + "type": "string" + }, + "title": { + "type": "string" + }, + "desc": { + "type": "string" + }, + "picUrl": { + "type": "string" + }, + "pic_url": { + "type": "string" + }, + "jumpUrl": { + "type": "string" + }, + "jump_url": { + "type": "string" + } + }, "additionalProperties": true }, "category": "扩展" @@ -8751,6 +8886,62 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } + }, + { + "name": "message_type", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "group_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "user_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "source", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "summary", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "prompt", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "news", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -8762,7 +8953,28 @@ export const ACTIONS: CatalogAction[] = [ }, "message": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." - } + }, + "message_type": { + "type": "string" + }, + "group_id": { + "type": "integer", + "minimum": 0 + }, + "user_id": { + "type": "integer", + "minimum": 0 + }, + "source": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "news": {} }, "additionalProperties": true }, @@ -8920,6 +9132,36 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } + }, + { + "name": "source", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "summary", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "prompt", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "news", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -8937,7 +9179,17 @@ export const ACTIONS: CatalogAction[] = [ }, "message": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." - } + }, + "source": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "news": {} }, "required": [ "group_id" @@ -9283,6 +9535,36 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } + }, + { + "name": "source", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "summary", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "prompt", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "news", + "type": "raw", + "required": false, + "schema": {} } ], "invariants": [], @@ -9299,7 +9581,17 @@ export const ACTIONS: CatalogAction[] = [ }, "message": { "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." - } + }, + "source": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "news": {} }, "required": [ "user_id" @@ -9986,15 +10278,19 @@ export const ACTIONS: CatalogAction[] = [ }, { "name": "sub_type", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } }, { "name": "type", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } }, { "name": "approve", @@ -10023,8 +10319,12 @@ export const ACTIONS: CatalogAction[] = [ "type": "string", "minLength": 1 }, - "sub_type": {}, - "type": {}, + "sub_type": { + "type": "string" + }, + "type": { + "type": "string" + }, "approve": { "type": "boolean", "default": true @@ -11695,23 +11995,31 @@ export const ACTIONS: CatalogAction[] = [ "params": [ { "name": "longNick", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } }, { "name": "long_nick", - "type": "raw", + "type": "string", "required": false, - "schema": {} + "schema": { + "type": "string" + } } ], "invariants": [], "inputSchema": { "type": "object", "properties": { - "longNick": {}, - "long_nick": {} + "longNick": { + "type": "string" + }, + "long_nick": { + "type": "string" + } }, "additionalProperties": true }, @@ -11936,17 +12244,30 @@ export const ACTIONS: CatalogAction[] = [ "params": [ { "name": "words", - "type": "raw", - "required": false, - "schema": {} + "type": "string[]", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } } ], "invariants": [], "inputSchema": { "type": "object", "properties": { - "words": {} + "words": { + "type": "array", + "items": { + "type": "string" + } + } }, + "required": [ + "words" + ], "additionalProperties": true }, "category": "扩展" diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index 5d1dea7c..1b28e6fb 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -483,11 +483,7 @@ interface ActionDef { readOnly?: boolean; params: S; rules?: (r: RuleBuilders>) => readonly CrossFieldRule[]; - /** `raw` is the original untouched params — an escape hatch for the - * irregular tail (alias-key fallbacks, arbitrary nested objects). Declared - * fields in `p` remain the validated path; reach for `raw` only for keys - * the spec can't express. */ - run: (p: InferParams, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; + run: (p: InferParams, ctx: ApiActionContext) => Promise | ApiResponse; } const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason); @@ -517,7 +513,7 @@ export function defineAction(def: ActionDef): ActionSpec { const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => { const r = parse(params); if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r)); - return def.run(r.value, ctx, params); + return def.run(r.value, ctx); }; return { @@ -571,7 +567,7 @@ interface StreamActionDef { readOnly?: boolean; params: S; rules?: (r: RuleBuilders>) => readonly CrossFieldRule[]; - run: (p: InferParams, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise | ApiResponse; + run: (p: InferParams, ctx: ApiActionContext, sink: StreamSink) => Promise | ApiResponse; } export interface StreamActionSpec extends RegisteredActionSpec { @@ -599,7 +595,7 @@ export function defineStreamAction(def: StreamActionDef): Str const toHandler = (ctx: ApiActionContext): Handler => async (params, sink) => { const r = base.parse(params); if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r)); - return def.run(r.value, ctx, params, sink ?? NOOP_SINK); + return def.run(r.value, ctx, sink ?? NOOP_SINK); }; return { @@ -628,7 +624,7 @@ interface PresetDef { readOnly?: boolean; params?: S; rules?: (r: RuleBuilders & Extra>) => readonly CrossFieldRule[]; - run: (p: InferParams & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; + run: (p: InferParams & Extra, ctx: ApiActionContext) => Promise | ApiResponse; } /** Pre-seeds `group_id` (uint, required). */ diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 73d07af8..e3875b4b 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -6,7 +6,6 @@ import type { GroupEssenceMessage, } from '@snowluma/protocol/web/group-essence'; import type { ApiActionContext } from '../api-handler'; -import { asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { hasAuthoritativeSequence, @@ -14,9 +13,10 @@ import { failedResponse, okResponse, type JsonObject, + type JsonValue, type MessageMeta, } from '../types'; -import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; +import { defineAction, groupAction, groupUserAction, f, type Field } from '../action-kit'; import { groupInfoReturnsSchema } from './group-info'; import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; @@ -262,19 +262,57 @@ async function saveDownloadBuffer(buf: Buffer, preferredName: string): Promise): ForwardPreviewMeta | undefined { - const source = asString(params.source) || undefined; - const summary = asString(params.summary) || undefined; - const prompt = asString(params.prompt) || undefined; +function optionalExactString(): Field { + const inner = f.string().optional(); + return Object.assign(Object.create(inner) as Field, { + coerce(raw: unknown, field: string) { + if (typeof raw === 'number' || typeof raw === 'boolean' || raw === null + || (typeof raw === 'object' && raw !== null)) { + return { ok: false as const, field, reason: 'expected a string' }; + } + return inner.coerce(raw as Parameters['coerce']>[0], field); + }, + }); +} + +function integerFromDecimalString(value: string): number { + if (value.trim() === '') return 0; + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : 0; +} + +function primitiveText(value: unknown): string { + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'boolean') return String(value); + return ''; +} + +const forwardPreviewParams = { + source: f.string().optional(), + summary: f.string().optional(), + prompt: f.string().optional(), + news: f.raw(), +}; + +// NapCat-compatible forward preview. All four fields are optional — if none +// are provided, the message module infers defaults from the node list. +function readForwardPreviewMeta(p: { + source?: string; + summary?: string; + prompt?: string; + news?: JsonValue; +}): ForwardPreviewMeta | undefined { + const source = p.source || undefined; + const summary = p.summary || undefined; + const prompt = p.prompt || undefined; let news: Array<{ text: string }> | undefined; - if (Array.isArray(params.news)) { + if (Array.isArray(p.news)) { const collected: Array<{ text: string }> = []; - for (const item of params.news) { + for (const item of p.news) { if (typeof item === 'string') { collected.push({ text: item }); } else if (item && typeof item === 'object' && !Array.isArray(item)) { - const text = asString((item as Record).text); + const text = primitiveText((item as Record).text); if (text) collected.push({ text }); } } @@ -801,13 +839,10 @@ export const actions = [ required: ['text'], }, params: { - message_id: f.string().default('').role('message_id'), + message_id: f.messageId(), }, - // `raw` so message_id works whether the client sends a number or a string. - run: async (_p, ctx, raw) => { - const messageId = asNumber(raw.message_id); - if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - return okResponse(await ctx.fetchPttText(messageId)); + run: async (p, ctx) => { + return okResponse(await ctx.fetchPttText(p.message_id)); }, }), @@ -2268,8 +2303,7 @@ export const actions = [ }, }), - // ===== 原 legacy registerAction,现并入 kit(ctx 调用与逻辑逐字保留; - // 别名键 / 原始参数透传 / 任意对象经 run 第三参 raw 或 f.raw() 表达)===== + // ===== 原 legacy registerAction,现并入 kit ===== defineAction({ name: ['get_rkey', 'nc_get_rkey'], @@ -2407,16 +2441,22 @@ export const actions = [ name: 'send_forward_msg', summary: '发送合并转发(按 message_type/群号自动路由)', returns: '{ message_id, res_id, forward_id }', - // group_id/user_id 是“路由提示”而非身份字段:原实现用 asNumber + `>0` 判断, - // 占位的 0 表示“该分支不适用”、不应报错。故从 raw 读取(保持旧语义), - // 只声明 messages/message。 - params: { messages: f.message().optional(), message: f.message().optional() }, - run: async (p, ctx, raw) => { - const messageType = asString(raw.message_type); - const groupId = asNumber(raw.group_id); - const userId = asNumber(raw.user_id); + // group_id/user_id are routing hints, not identity: 0 means "this branch + // does not apply" and must not error. int({min:0}) optional, not groupId. + params: { + messages: f.message().optional(), + message: f.message().optional(), + message_type: f.string().optional(), + group_id: f.int({ min: 0 }).optional(), + user_id: f.int({ min: 0 }).optional(), + ...forwardPreviewParams, + }, + run: async (p, ctx) => { + const messageType = p.message_type ?? ''; + const groupId = p.group_id ?? 0; + const userId = p.user_id ?? 0; const messages = p.messages ?? p.message; - const meta = readForwardPreviewMeta(raw); + const meta = readForwardPreviewMeta(p); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) { if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); @@ -2437,11 +2477,15 @@ export const actions = [ name: 'send_group_forward_msg', summary: '发送群合并转发', returns: '{ message_id, res_id, forward_id }', - params: { messages: f.message().optional(), message: f.message().optional() }, - run: async (p, ctx, raw) => { + params: { + messages: f.message().optional(), + message: f.message().optional(), + ...forwardPreviewParams, + }, + run: async (p, ctx) => { const messages = p.messages ?? p.message; if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(raw)); + const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(p)); return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); }, }), @@ -2450,11 +2494,16 @@ export const actions = [ name: 'send_private_forward_msg', summary: '发送私聊合并转发', returns: '{ message_id, res_id, forward_id }', - params: { user_id: f.userId(), messages: f.message().optional(), message: f.message().optional() }, - run: async (p, ctx, raw) => { + params: { + user_id: f.userId(), + messages: f.message().optional(), + message: f.message().optional(), + ...forwardPreviewParams, + }, + run: async (p, ctx) => { const messages = p.messages ?? p.message; if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(raw)); + const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(p)); return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); }, }), @@ -2471,12 +2520,11 @@ export const actions = [ }, required: ['messages'], }, - params: { id: f.string().optional() }, - run: async (p, ctx, raw) => { + params: { id: f.string().optional(), message_id: f.string().optional() }, + run: async (p, ctx) => { let id = p.id || ''; - if (!id) { - const rawMessageId = raw.message_id; - const numericMessageId = asNumber(rawMessageId); + if (!id && p.message_id !== undefined) { + const numericMessageId = integerFromDecimalString(p.message_id); if (numericMessageId > 0) { const event = ctx.getMessage(numericMessageId); const segments = Array.isArray(event?.message) ? event.message : []; @@ -2487,11 +2535,11 @@ export const actions = [ const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) ? so.data as Record : null; - const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id); + const candidate = primitiveText(data?.id) || primitiveText(data?.res_id) || primitiveText(data?.forward_id); if (candidate) { id = candidate; break; } } } - if (!id) id = asString(rawMessageId); + if (!id) id = p.message_id; } if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required'); const messages = await ctx.getForwardMsg(id); @@ -2503,8 +2551,13 @@ export const actions = [ name: 'download_file', summary: '下载文件(url 或 base64)到 data/downloads', returns: '{ file }', - params: { url: f.string().default(''), base64: f.string().default(''), name: f.string().default('') }, - run: async (p, _ctx, raw) => { + params: { + url: f.string().default(''), + base64: f.string().default(''), + name: f.string().default(''), + headers: f.raw(), + }, + run: async (p) => { const url = p.url; const base64 = p.base64; const name = p.name; @@ -2516,7 +2569,7 @@ export const actions = [ buf = Buffer.from(base64, 'base64'); if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); } else { - buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS); + buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS); } try { const safe = await saveDownloadBuffer(buf, name); @@ -2539,12 +2592,9 @@ export const actions = [ }, required: ['words'], }, - params: { words: f.raw() }, + params: { words: f.array(f.string()) }, run: async (p, ctx) => { - const rawWords = p.words; - if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array'); - const words = rawWords.map((w) => String(w)); - const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); + const translated = await ctx.bridge.apis.misc.translateEn2Zh(p.words); return okResponse({ words: translated }); }, }), @@ -2552,7 +2602,7 @@ export const actions = [ defineAction({ name: 'set_self_longnick', summary: '设置个性签名(longNick/long_nick,严格 string)', - params: { longNick: f.raw(), long_nick: f.raw() }, + params: { longNick: optionalExactString(), long_nick: optionalExactString() }, run: async (p, ctx) => { const longNick = p.longNick !== undefined ? p.longNick : p.long_nick; if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); @@ -2565,14 +2615,22 @@ export const actions = [ name: 'get_mini_app_ark', summary: '获取小程序卡片 ark', readOnly: true, - params: {}, - run: async (_p, ctx, raw) => { - const type = raw.type || 'bili'; - const title = raw.title || ''; - const desc = raw.desc || ''; - const picUrl = raw.picUrl || raw.pic_url || ''; - const jumpUrl = raw.jumpUrl || raw.jump_url || ''; - const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl)); + params: { + type: f.string().optional(), + title: f.string().optional(), + desc: f.string().optional(), + picUrl: f.string().optional(), + pic_url: f.string().optional(), + jumpUrl: f.string().optional(), + jump_url: f.string().optional(), + }, + run: async (p, ctx) => { + const type = p.type || 'bili'; + const title = p.title || ''; + const desc = p.desc || ''; + const picUrl = p.picUrl || p.pic_url || ''; + const jumpUrl = p.jumpUrl || p.jump_url || ''; + const data = await ctx.bridge.apis.misc.getMiniAppArk(type, title, desc, picUrl, jumpUrl); return okResponse(data); }, }), @@ -2580,12 +2638,20 @@ export const actions = [ groupAction({ name: 'click_inline_keyboard_button', summary: '点击内联键盘按钮', - params: { bot_appid: f.uint(), msg_seq: f.uint() }, - run: async (p, ctx, raw) => { - const buttonId = raw.button_id; - const callbackData = raw.callback_data || ''; - if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters'); - const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq); + params: { + bot_appid: f.uint(), + msg_seq: f.uint(), + button_id: f.string({ allowEmpty: false }), + callback_data: f.string().default(''), + }, + run: async (p, ctx) => { + const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton( + p.group_id, + p.bot_appid, + p.button_id, + p.callback_data, + p.msg_seq, + ); return okResponse(data); }, }), diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 5a0ee2de..beb889bf 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -1,5 +1,4 @@ import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; -import { asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; import { WebHonorType } from '@snowluma/protocol/web/group-honor'; @@ -190,17 +189,14 @@ export const actions = [ }, }), - // `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string - // / empty-string all collapse to 'all'), which a typed string field can't - // replicate exactly — so it stays a raw param coerced in run(). groupAction({ name: 'get_group_honor_info', summary: '获取群荣誉信息', readOnly: true, - params: { type: f.raw() }, + params: { type: f.string().optional() }, run: async (p, ctx) => { const groupId = p.group_id; - const typeStr = asString(p.type) || 'all'; + const typeStr = p.type || 'all'; const typeValues = Object.values(WebHonorType) as string[]; if (!typeValues.includes(typeStr)) { diff --git a/packages/onebot/src/actions/request.ts b/packages/onebot/src/actions/request.ts index 6a6e4576..77fe412c 100644 --- a/packages/onebot/src/actions/request.ts +++ b/packages/onebot/src/actions/request.ts @@ -1,5 +1,4 @@ import { defineAction, f } from '../action-kit'; -import { asString } from '../api-handler'; import { okResponse } from '../types'; export const actions = [ @@ -22,15 +21,14 @@ export const actions = [ params: { // Opaque handle from the original request event; callers must echo it. flag: f.string({ allowEmpty: false }), - // sub_type/type pass through with a nested fallback (sub_type → type → 'add'); - // kept raw so the original asString resolution is preserved verbatim. - sub_type: f.raw(), - type: f.raw(), + // sub_type → type → 'add'. Empty string is kept, not treated as missing. + sub_type: f.string().optional(), + type: f.string().optional(), approve: f.bool().default(true), reason: f.string().default(''), }, run: async (p, ctx) => { - const subType = asString(p.sub_type, asString(p.type, 'add')); + const subType = p.sub_type !== undefined ? p.sub_type : (p.type !== undefined ? p.type : 'add'); await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason); return okResponse(); }, diff --git a/packages/onebot/src/actions/stream-download.ts b/packages/onebot/src/actions/stream-download.ts index 02216779..dbfbef52 100644 --- a/packages/onebot/src/actions/stream-download.ts +++ b/packages/onebot/src/actions/stream-download.ts @@ -361,7 +361,7 @@ const downloadFileStream = defineStreamAction({ summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)', returns: '流式帧:file_info → file_chunk* → file_complete', params: downloadParams, - run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'), + run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'), }); const downloadFileImageStream = defineStreamAction({ @@ -369,7 +369,7 @@ const downloadFileImageStream = defineStreamAction({ summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)', returns: '流式帧:file_info → file_chunk* → file_complete', params: downloadParams, - run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'), + run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'), }); const downloadFileRecordStream = defineStreamAction({ @@ -377,7 +377,7 @@ const downloadFileRecordStream = defineStreamAction({ summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)', returns: '流式帧:file_info → file_chunk* → file_complete', params: downloadParams, - run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'), + run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'), }); const testDownloadStream = defineStreamAction({ @@ -385,7 +385,7 @@ const testDownloadStream = defineStreamAction({ summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)', returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)', params: { error: f.bool().default(false).describe('是否触发测试错误') }, - run: async (p, _ctx, _raw, sink) => { + run: async (p, _ctx, sink) => { for (let i = 0; i < 10; i++) { await sink.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: 'data_chunk' }); } diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 0cca6316..35bfe929 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -415,26 +415,6 @@ export function asString(value: unknown, fallback = ''): string { return fallback; } -export function asNumber(value: unknown): number { - if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); - if (typeof value === 'string' && value.trim()) { - const n = Number(value); - if (Number.isFinite(n)) return Math.trunc(n); - } - return 0; -} - -export function asBoolean(value: unknown, fallback: boolean): boolean { - if (typeof value === 'boolean') return value; - if (typeof value === 'number') return value !== 0; - if (typeof value === 'string') { - const text = value.trim().toLowerCase(); - if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true; - if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false; - } - return fallback; -} - export function toJsonValue(value: unknown): JsonValue { if (value === null) return null; if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value; @@ -448,21 +428,3 @@ export function toJsonValue(value: unknown): JsonValue { } return String(value); } - -export function asMessage(value: unknown): import('./types').JsonValue | undefined { - if (value === undefined) return undefined; - if (typeof value === 'string') { - const trimmed = value.trim(); - if (trimmed.startsWith('[') && trimmed.endsWith(']')) { - try { - const parsed = JSON.parse(trimmed); - if (Array.isArray(parsed)) { - return toJsonValue(parsed); - } - } catch { - // Fallback to literal text if it just looks like an array but is invalid JSON - } - } - } - return toJsonValue(value); -} diff --git a/packages/onebot/tests/action-kit.test.ts b/packages/onebot/tests/action-kit.test.ts index f36e68ce..6ffdc485 100644 --- a/packages/onebot/tests/action-kit.test.ts +++ b/packages/onebot/tests/action-kit.test.ts @@ -152,16 +152,27 @@ describe('toHandler — BAD_REQUEST shaping + ctx threading', () => { }); }); -describe('run raw escape hatch — original params as 3rd arg', () => { - it('exposes untouched params for undeclared keys (alias fallbacks etc.)', async () => { +describe('run only sees declared fields', () => { + it('lets a declared alias through and ignores undeclared keys', async () => { const spec = defineAction({ name: 't', - params: { user_id: f.uint() }, - run: (_p, _ctx, raw) => okResponse({ extra: (raw.long_nick ?? raw.longNick ?? null) as never }), + params: { user_id: f.uint(), longNick: f.string().optional() }, + run: (p) => okResponse({ extra: (p.longNick ?? null) as never }), }); - const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi' }); + const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi', undeclared: 1 }); expect(res).toMatchObject({ status: 'ok', data: { extra: 'hi' } }); }); + + it('rejects garbage on a declared int instead of treating it as 0', async () => { + const spec = defineAction({ + name: 't', + params: { group_id: f.int({ min: 0 }).optional() }, + run: (p) => okResponse({ group_id: p.group_id ?? 0 }), + }); + const res = await spec.toHandler(ctx)({ group_id: 'nope' }); + expect(res.retcode).toBe(RETCODE.BAD_REQUEST); + expect(res.wording).toContain('group_id'); + }); }); describe('toJsonSchema / inputSchema (for the MCP)', () => { diff --git a/packages/onebot/tests/actions-request.test.ts b/packages/onebot/tests/actions-request.test.ts index d91b0533..357a268c 100644 --- a/packages/onebot/tests/actions-request.test.ts +++ b/packages/onebot/tests/actions-request.test.ts @@ -241,7 +241,7 @@ describe('set_friend_add_request describe', () => { }); describe('set_group_add_request parse', () => { - it('requires flag and defaults approve, reason, and the raw type fields', () => { + it('requires flag and defaults approve, reason, and the type fields', () => { expect(setGroupAddRequest.parse({ flag: 'slreq:1:123456:999:22:1' })).toEqual({ ok: true, value: { @@ -254,22 +254,22 @@ describe('set_group_add_request parse', () => { }); }); - it('keeps raw sub_type and type values without coercing them', () => { + it('rejects non-string sub_type and type values', () => { expect(setGroupAddRequest.parse({ flag: 'flag-group-9', sub_type: { kind: 'invite' }, - type: [1, 2], - approve: 0, - reason: 404, })).toEqual({ - ok: true, - value: { - flag: 'flag-group-9', - sub_type: { kind: 'invite' }, - type: [1, 2], - approve: false, - reason: '404', - }, + ok: false, + field: 'sub_type', + reason: 'expected a string', + }); + expect(setGroupAddRequest.parse({ + flag: 'flag-group-9', + type: [1, 2], + })).toEqual({ + ok: false, + field: 'type', + reason: 'expected a string', }); }); @@ -418,23 +418,25 @@ describe('set_group_add_request toHandler', () => { }); it.each([ - [{ sub_type: { kind: 'invite' }, type: 'invite' }, 'invite'], - [{ sub_type: ['invite'], type: 'add' }, 'add'], - [{ sub_type: null, type: 'invite' }, 'invite'], - [{ sub_type: null, type: null }, 'add'], - [{ type: { kind: 'add' } }, 'add'], - [{ type: null }, 'add'], - ])('falls through a non-primitive locator %j to %s', async (params, subType) => { + [{ sub_type: { kind: 'invite' } }, 'sub_type'], + [{ sub_type: ['invite'] }, 'sub_type'], + [{ sub_type: null }, 'sub_type'], + [{ type: { kind: 'add' } }, 'type'], + [{ type: null }, 'type'], + ])('rejects a non-string locator %j', async (params, field) => { const { ctx, handleGroupRequest } = groupCtx(); await expect(setGroupAddRequest.toHandler(ctx)({ flag: 'flag-group-9', ...params, - })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: `${field}: expected a string`, + }); - expect(handleGroupRequest.mock.calls).toEqual([ - ['flag-group-9', subType, true, ''], - ]); + expect(handleGroupRequest).not.toHaveBeenCalled(); }); it('stringifies a numeric flag and reason', async () => { @@ -484,7 +486,7 @@ describe('set_group_add_request toHandler', () => { }); describe('set_group_add_request describe', () => { - it('documents the group-request params including raw type fields', () => { + it('documents the group-request params including type fields', () => { const doc = setGroupAddRequest.describe(); expect(doc.name).toBe('set_group_add_request'); @@ -504,17 +506,17 @@ describe('set_group_add_request describe', () => { }, { name: 'sub_type', - type: 'raw', + type: 'string', required: false, default: undefined, - schema: {}, + schema: { type: 'string' }, }, { name: 'type', - type: 'raw', + type: 'string', required: false, default: undefined, - schema: {}, + schema: { type: 'string' }, }, { name: 'approve', @@ -535,8 +537,8 @@ describe('set_group_add_request describe', () => { type: 'object', properties: { flag: { type: 'string', minLength: 1 }, - sub_type: {}, - type: {}, + sub_type: { type: 'string' }, + type: { type: 'string' }, approve: { type: 'boolean', default: true }, reason: { type: 'string', default: '' }, }, diff --git a/packages/onebot/tests/api-handler-trace.test.ts b/packages/onebot/tests/api-handler-trace.test.ts index ba28b133..00fe8b69 100644 --- a/packages/onebot/tests/api-handler-trace.test.ts +++ b/packages/onebot/tests/api-handler-trace.test.ts @@ -149,7 +149,7 @@ describe('ApiHandler TRACE lifecycle', () => { const stream = defineStreamAction({ name: 'trace_stream', params: {}, - run: async (_params, _ctx, _raw, sink) => { + run: async (_params, _ctx, sink) => { await sink.send({ type: StreamStatus.Stream, chunk: 'complete-frame' }); return { status: 'ok', diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index dc25118b..6bcf25da 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -149,6 +149,50 @@ function fakeEssenceMessage( }; } +describe('extended-actions / send_forward_msg', () => { + it('treats group_id 0 as unused', async () => { + const sendForwardMsg = vi.fn(async () => ({ forwardId: 'fwd' })); + const ctx = fakeCtx(fakeBridge(), { sendForwardMsg }); + const response = await makeHandler(ctx).handle('send_forward_msg', { + messages: 'hi', + group_id: 0, + }); + expect(response).toMatchObject({ status: 'ok', retcode: 0 }); + expect(sendForwardMsg).toHaveBeenCalledOnce(); + }); + + it('rejects a non-numeric group_id instead of treating it as 0', async () => { + const sendForwardMsg = vi.fn(); + const ctx = fakeCtx(fakeBridge(), { sendForwardMsg }); + const response = await makeHandler(ctx).handle('send_forward_msg', { + messages: 'hi', + group_id: 'nope', + }); + expect(response).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(sendForwardMsg).not.toHaveBeenCalled(); + }); +}); + +describe('extended-actions / get_forward_msg', () => { + it('uses a string message_id as the forward id', async () => { + const getForwardMsg = vi.fn(async () => []); + const ctx = fakeCtx(fakeBridge(), { getForwardMsg }); + const response = await makeHandler(ctx).handle('get_forward_msg', { message_id: 'resid-1' }); + expect(getForwardMsg).toHaveBeenCalledWith('resid-1'); + expect(response).toMatchObject({ status: 'ok' }); + }); +}); + +describe('extended-actions / fetch_ptt_text', () => { + it('accepts a numeric message_id', async () => { + const fetchPttText = vi.fn(async () => 'hello'); + const ctx = fakeCtx(fakeBridge(), { fetchPttText }); + const response = await makeHandler(ctx).handle('fetch_ptt_text', { message_id: 12 }); + expect(fetchPttText).toHaveBeenCalledWith(12); + expect(response).toMatchObject({ status: 'ok', data: 'hello' }); + }); +}); + describe('extended-actions / set_self_longnick', () => { it('accepts an empty longNick to clear the signature', async () => { const setSelfLongNick = vi.fn(async () => undefined); diff --git a/packages/onebot/tests/helpers/compiled-action-handler.ts b/packages/onebot/tests/helpers/compiled-action-handler.ts index 352df836..88aa5cad 100644 --- a/packages/onebot/tests/helpers/compiled-action-handler.ts +++ b/packages/onebot/tests/helpers/compiled-action-handler.ts @@ -14,7 +14,7 @@ export function testAction(name: string, run: TestActionRun): RegisteredActionSp return defineAction({ name, params: {}, - run: (_params, context, raw) => run(raw, context), + run: (params, context) => run(params, context), }); } diff --git a/packages/onebot/tests/streaming.test.ts b/packages/onebot/tests/streaming.test.ts index 11d141a4..56611230 100644 --- a/packages/onebot/tests/streaming.test.ts +++ b/packages/onebot/tests/streaming.test.ts @@ -22,7 +22,7 @@ describe('Stream API plumbing', () => { const action = defineStreamAction({ name: 'demo_stream', params: { n: f.uint() }, - run: async (p, _ctx, _raw, sink) => { + run: async (p, _ctx, sink) => { for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i }); return okResponse({ type: 'response', total: p.n }); }, @@ -85,7 +85,7 @@ describe('Stream API plumbing', () => { const action = defineStreamAction({ name: 'demo_partial', params: {}, - run: async (_p, _ctx, _raw, sink) => { + run: async (_p, _ctx, sink) => { await sink.send({ type: 'stream', index: 0 }); throw new Error('mid'); }, @@ -116,7 +116,7 @@ describe('Stream API plumbing', () => { const action = defineStreamAction({ name: 'demo_abort', params: {}, - run: async (_p, _ctx, _raw, sink) => { + run: async (_p, _ctx, sink) => { for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; } return okResponse({ type: 'response' }); }, From a0f152229d4e129d784421c77ce9dd410014d385 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 30 Aug 2026 13:45:22 +0800 Subject: [PATCH 06/11] refactor(protocol): decide message bubbles after decode Live push and history now share one keep-or-drop decision. Control signals and empty bodies stay hidden; undecodable content is kept and logged on both paths. --- .../protocol/src/msg-push/blank-filter.ts | 107 +++++++++++++++--- .../src/msg-push/fetch-c2c-history.ts | 4 +- .../src/msg-push/fetch-group-history.ts | 6 +- packages/protocol/src/msg-push/index.ts | 98 ++++++---------- .../tests/msg-push/blank-filter.test.ts | 37 ++++++ .../tests/msg-push/fetch-c2c-history.test.ts | 44 ++++++- .../msg-push/fetch-group-history.test.ts | 46 +++++++- 7 files changed, 252 insertions(+), 90 deletions(-) create mode 100644 packages/protocol/tests/msg-push/blank-filter.test.ts diff --git a/packages/protocol/src/msg-push/blank-filter.ts b/packages/protocol/src/msg-push/blank-filter.ts index 069c22d0..f58e1beb 100644 --- a/packages/protocol/src/msg-push/blank-filter.ts +++ b/packages/protocol/src/msg-push/blank-filter.ts @@ -1,6 +1,11 @@ +import { hexPreview } from '@snowluma/common/hex'; +import { createLogger } from '@snowluma/common/logger'; +import type { Elem } from '@snowluma/proto-defs/element'; import type { MsgPushHead, PushMsgBody } from './context'; import { hasDecodableContent } from './rich-body-decoder'; +const log = createLogger('MsgPush'); + // C2C-family message types (private 166, temp 141, and 167) whose pushes QQ NT // classifies by `c2c_cmd`. RE: `long_cnn_msg_mgr.cc::OnRecvSysMsg` gates on // exactly this set (svr_msg_type-141 bitmask 0x6000001 → {141,166,167}). @@ -13,13 +18,15 @@ const C2C_CONTROL_TYPES = new Set([141, 166, 167]); // phantom (#102) is one of them. const C2C_CONTROL_CMDS = new Set([1, 73, 75, 129, 131, 133, 135, 192]); +export type MessageSurvival = 'drop-control' | 'drop-blank' | 'keep-undecoded' | 'keep'; + /** * Whether a push is a C2C control/system signal that QQ NT never renders as a * chat message (it dispatches it through `OnRecvSysMsg` instead). Matched by * `(msgType, c2cCmd)` exactly as the official client's header codec does, so it * catches these even on the rare occasion they carry junk content that would - * otherwise decode to a stray element. The precise complement to - * {@link isBlankMessage}, which only catches the content-less case. + * otherwise decode to a stray element. History may skip these before decode; + * the post-decode filter still returns `drop-control` for the same decision. */ export function isC2cControlPush(head: Pick): boolean { return C2C_CONTROL_TYPES.has(head.msgType) && C2C_CONTROL_CMDS.has(head.c2cCmd); @@ -27,21 +34,7 @@ export function isC2cControlPush(head: Pick): /** * A message-kind event is "blank" — the "[空消息]" phantom from #102 — when it - * decoded to zero elements AND its body carried nothing decodable. These are - * QQ's content-less C2C control/system pushes (msgType 166/141/167 carrying a - * `c2c_cmd`, routed by the official client through `OnRecvSysMsg` rather than - * shown as a bubble). - * - * QQ NT drops such records before the UI ever sees them, in BOTH the live push - * path and the history (roam) fetch path — RE of `wrapper.linux.node`: - * - live/roam C2C: `c2c_roam_msg_mgr.cc::FilterBlankMsgAndRetryFetch` - * - group roam: `group_roam_msg_worker.cc::FilterBlankSeqsMsg` - * So we mirror it everywhere a message event is produced — live (`parseMsgPush`) - * and history (`fetchC2cMessageRange` / `fetchGroupMessageRange`). - * - * NOTE: a body that DID carry content but still decoded to zero elements is a - * missing decoder, not a blank message — this returns false for that case so - * the caller can keep (and warn about) it rather than silently dropping content. + * decoded to zero elements AND its body carried nothing decodable. */ export function isBlankMessage( elements: readonly unknown[], @@ -49,3 +42,83 @@ export function isBlankMessage( ): boolean { return elements.length === 0 && !hasDecodableContent(body); } + +/** + * Decoder-after bubble decision for friend / group / temp messages. + * Control drops even when a body decoded to elements. Blank drops only when + * there is nothing to decode. A body that had content but decoded to zero + * elements is keep-undecoded, not blank. + */ +export function classifyMessageSurvival( + head: Pick, + elements: readonly unknown[], + body: PushMsgBody | undefined, +): MessageSurvival { + if (isC2cControlPush(head)) return 'drop-control'; + if (elements.length !== 0) return 'keep'; + if (hasDecodableContent(body)) return 'keep-undecoded'; + return 'drop-blank'; +} + +/** Summarise a body that decoded to zero elements despite carrying content. */ +export function describeUndecodedBody(body: PushMsgBody | undefined): string { + const elems = (body?.richText?.elems ?? []) as Elem[]; + const parts = elems.map((e) => { + if (e.commonElem) { + const ce = e.commonElem; + const pb = ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : ''; + return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`; + } + const keys = Object.keys(e).filter((k) => (e as Record)[k] != null); + return keys.join('+') || '(empty)'; + }); + const extras: string[] = []; + if (body?.richText?.ptt) extras.push('ptt'); + if (body?.richText?.notOnlineFile) extras.push('notOnlineFile'); + if (body?.msgContent && body.msgContent.length > 0) { + extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`); + } + return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`; +} + +/** Keep when the message should appear as a bubble. Warns on keep-undecoded. */ +export function keepDecodedMessage( + head: Pick, + elements: readonly unknown[], + body: PushMsgBody | undefined, + kind: string, + fromUin: number, +): boolean { + const survival = classifyMessageSurvival(head, elements, body); + if (survival === 'drop-control' || survival === 'drop-blank') return false; + if (survival === 'keep-undecoded') { + warnUndecodedMessage({ + kind, + sequence: head.sequence, + fromUin, + msgType: head.msgType, + subType: head.subType, + body, + }); + } + return true; +} + +export function warnUndecodedMessage(info: { + kind: string; + sequence: number; + fromUin: number; + msgType: number; + subType: number; + body: PushMsgBody | undefined; +}): void { + log.warn( + 'message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s', + info.kind, + info.sequence, + info.fromUin, + info.msgType, + info.subType, + describeUndecodedBody(info.body), + ); +} diff --git a/packages/protocol/src/msg-push/fetch-c2c-history.ts b/packages/protocol/src/msg-push/fetch-c2c-history.ts index 67998aa8..7a45724f 100644 --- a/packages/protocol/src/msg-push/fetch-c2c-history.ts +++ b/packages/protocol/src/msg-push/fetch-c2c-history.ts @@ -10,7 +10,7 @@ import type { import type { PushMsgBody } from '@snowluma/proto-defs/message'; import type { QQEventVariant } from '../events'; import type { IdentityService } from '../identity-service'; -import { isBlankMessage, isC2cControlPush } from './blank-filter'; +import { isC2cControlPush, keepDecodedMessage } from './blank-filter'; import { buildContextFromMessage } from './context'; import { decodeFriendMessage } from './decoders/friend-message'; import { requirePacketResponse } from './packet-response'; @@ -46,7 +46,7 @@ function decodeC2cMessages( if (isC2cControlPush(ctx.head)) continue; for (const ev of decodeFriendMessage(ctx)) { if (ev.kind !== 'friend_message') continue; - if (isBlankMessage(ev.elements, ctx.body)) continue; + if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue; if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) { throw new Error( `${source} message is missing the canonical NT sequence ` diff --git a/packages/protocol/src/msg-push/fetch-group-history.ts b/packages/protocol/src/msg-push/fetch-group-history.ts index cc8eb37d..bd9ad673 100644 --- a/packages/protocol/src/msg-push/fetch-group-history.ts +++ b/packages/protocol/src/msg-push/fetch-group-history.ts @@ -4,7 +4,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg'; import type { QQEventVariant } from '../events'; import type { IdentityService } from '../identity-service'; -import { isBlankMessage } from './blank-filter'; +import { keepDecodedMessage } from './blank-filter'; import { buildContextFromMessage } from './context'; import { decodeGroupMessage } from './decoders/group-message'; import { requirePacketResponse } from './packet-response'; @@ -93,9 +93,7 @@ export async function fetchGroupMessageRange( + `(expected=${groupUin} range=${startSeq}-${endSeq})`, ); } - // Drop content-less control pushes (the "[空消息]" phantom, #102) just as - // QQ NT does on its group roam/history fetch — keep history parity with live. - if (isBlankMessage(ev.elements, ctx.body)) continue; + if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue; out.push(ev); } } diff --git a/packages/protocol/src/msg-push/index.ts b/packages/protocol/src/msg-push/index.ts index b1e41b6c..70538a08 100644 --- a/packages/protocol/src/msg-push/index.ts +++ b/packages/protocol/src/msg-push/index.ts @@ -1,12 +1,9 @@ -import { hexPreview } from '@snowluma/common/hex'; import { createLogger } from '@snowluma/common/logger'; import type { PacketInfo } from '@snowluma/common/protocol-types'; -import type { Elem } from '@snowluma/proto-defs/element'; import type { QQEventVariant } from '../events'; import type { IdentityService } from '../identity-service'; -import { isC2cControlPush } from './blank-filter'; -import { hasDecodableContent } from './rich-body-decoder'; -import { buildContext, type PushMsgBody } from './context'; +import { classifyMessageSurvival, warnUndecodedMessage } from './blank-filter'; +import { buildContext } from './context'; import { decodeEvent0x210 } from './decoders/event-0x210'; import { decodeEvent0x2DC } from './decoders/event-0x2dc'; import { decodeFriendMessage } from './decoders/friend-message'; @@ -65,36 +62,11 @@ registry.register([ const log = createLogger('MsgPush'); -// Kinds that carry decoded `elements`; an empty list surfaces to clients as the -// confusing "[空消息]". -const MESSAGE_KINDS = new Set([ - 'friend_message', 'group_message', 'temp_message', -]); - -/** - * Summarise a body that decoded to zero elements despite carrying content — - * each element's field names, every `commonElem`'s serviceType/businessType + - * payload hex, and any `msgContent` — so a missing decoder can be identified - * from one log line rather than swallowed silently. - */ -function describeUndecodedBody(body: PushMsgBody | undefined): string { - const elems = (body?.richText?.elems ?? []) as Elem[]; - const parts = elems.map((e) => { - if (e.commonElem) { - const ce = e.commonElem; - const pb = ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : ''; - return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`; - } - const keys = Object.keys(e).filter((k) => (e as Record)[k] != null); - return keys.join('+') || '(empty)'; - }); - const extras: string[] = []; - if (body?.richText?.ptt) extras.push('ptt'); - if (body?.richText?.notOnlineFile) extras.push('notOnlineFile'); - if (body?.msgContent && body.msgContent.length > 0) { - extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`); +function messageElements(ev: QQEventVariant): readonly unknown[] | undefined { + if (ev.kind === 'friend_message' || ev.kind === 'group_message' || ev.kind === 'temp_message') { + return ev.elements; } - return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`; + return undefined; } function warnMissingC2cSequence(ev: QQEventVariant, fromUin: number): void { @@ -188,11 +160,10 @@ function parseMsgPushInternal( ? registry.decodeOrThrow(ctx) : registry.decode(ctx); const out = events.filter((ev) => { - if (!MESSAGE_KINDS.has(ev.kind)) return true; - // C2C control/system signal (#102): QQ NT routes these via OnRecvSysMsg and - // never shows them as a bubble. Drop by (msgType, c2cCmd) regardless of body - // — the precise discriminator, the group-invite "[空消息]" phantom being one. - if (isC2cControlPush(ctx.head)) { + const elements = messageElements(ev); + if (elements === undefined) return true; + const survival = classifyMessageSurvival(ctx.head, elements, ctx.body); + if (survival === 'drop-control') { log.trace(() => [ 'packet_branch serviceCmd=%j seqId=%d branch=c2c_control_push msgType=%d subType=%d c2cCmd=%d messageSeq=%d', pkt.serviceCmd, @@ -202,38 +173,35 @@ function parseMsgPushInternal( ctx.head.c2cCmd, ctx.head.sequence, ]); - const elemCount = (ev as { elements?: unknown[] }).elements?.length ?? 0; - if (elemCount > 0) { + if (elements.length > 0) { log.debug('dropped c2c control push that carried %d element(s) (kind=%s seq=%d from=%d msgType=%d cmd=%d)', - elemCount, ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.c2cCmd); + elements.length, ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.c2cCmd); } return false; } - if ((ev as { elements?: unknown[] }).elements?.length !== 0) { - warnMissingC2cSequence(ev, ctx.fromUin); - return true; + if (survival === 'drop-blank') { + log.trace(() => [ + 'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d', + pkt.serviceCmd, + pkt.seqId, + ctx.head.msgType, + ctx.head.subType, + ctx.head.sequence, + ]); + return false; } - // Empty-element message that's NOT a known control cmd. Drop it when the body - // is genuinely empty (a content-less push we don't yet classify by c2cCmd). - // If instead the body *had* content we just couldn't decode, keep the - // (still-empty) event but warn so the missing decoder gets noticed rather - // than silently swallowed. - if (hasDecodableContent(ctx.body)) { - log.warn('message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s', - ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.subType, - describeUndecodedBody(ctx.body)); - warnMissingC2cSequence(ev, ctx.fromUin); - return true; + if (survival === 'keep-undecoded') { + warnUndecodedMessage({ + kind: ev.kind, + sequence: ctx.head.sequence, + fromUin: ctx.fromUin, + msgType: ctx.head.msgType, + subType: ctx.head.subType, + body: ctx.body, + }); } - log.trace(() => [ - 'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d', - pkt.serviceCmd, - pkt.seqId, - ctx.head.msgType, - ctx.head.subType, - ctx.head.sequence, - ]); - return false; + warnMissingC2cSequence(ev, ctx.fromUin); + return true; }); return out; diff --git a/packages/protocol/tests/msg-push/blank-filter.test.ts b/packages/protocol/tests/msg-push/blank-filter.test.ts new file mode 100644 index 00000000..ec700fc9 --- /dev/null +++ b/packages/protocol/tests/msg-push/blank-filter.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { + classifyMessageSurvival, + isBlankMessage, + isC2cControlPush, +} from '../../src/msg-push/blank-filter'; + +const privateHead = { msgType: 166, c2cCmd: 0 }; +const controlHead = { msgType: 166, c2cCmd: 75 }; +const groupHead = { msgType: 82, c2cCmd: 0 }; + +describe('classifyMessageSurvival', () => { + it('drops C2C control even when elements decoded', () => { + expect(isC2cControlPush(controlHead)).toBe(true); + expect(classifyMessageSurvival(controlHead, [{ type: 'text' }], { + richText: { elems: [{ text: { str: 'noise' } }] }, + })).toBe('drop-control'); + }); + + it('drops a genuinely empty non-control body', () => { + expect(isBlankMessage([], { richText: { elems: [] } })).toBe(true); + expect(classifyMessageSurvival(privateHead, [], { richText: { elems: [] } })).toBe('drop-blank'); + expect(classifyMessageSurvival(groupHead, [], { richText: { elems: [] } })).toBe('drop-blank'); + }); + + it('keeps an empty decode when the body still carried content', () => { + const body = { richText: { elems: [{ commonElem: { serviceType: 999, businessType: 0 } }] } }; + expect(isBlankMessage([], body)).toBe(false); + expect(classifyMessageSurvival(privateHead, [], body)).toBe('keep-undecoded'); + }); + + it('keeps a message that decoded to elements', () => { + expect(classifyMessageSurvival(privateHead, [{ type: 'text' }], { + richText: { elems: [{ text: { str: 'hi' } }] }, + })).toBe('keep'); + }); +}); diff --git a/packages/protocol/tests/msg-push/fetch-c2c-history.test.ts b/packages/protocol/tests/msg-push/fetch-c2c-history.test.ts index 2f558fce..7d82f7ed 100644 --- a/packages/protocol/tests/msg-push/fetch-c2c-history.test.ts +++ b/packages/protocol/tests/msg-push/fetch-c2c-history.test.ts @@ -3,7 +3,13 @@ // re-uses the regular friend decoder). import { deflateSync } from 'node:zlib'; -import { describe, expect, it } from 'vitest'; +import { + getLogLevel, + setLogLevel, + subscribeLogs, + type LogEntry, +} from '@snowluma/common/logger'; +import { afterEach, describe, expect, it } from 'vitest'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { @@ -24,6 +30,11 @@ import { } from '../../src/msg-push'; const identity = { findFriend: () => undefined } as unknown as IdentityService; +const previousLogLevel = getLogLevel(); + +afterEach(() => { + setLogLevel(previousLogLevel); +}); function okResult(data: Uint8Array): SendPacketResult { return { success: true, gotResponse: true, responseData: data } as SendPacketResult; @@ -124,6 +135,37 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => { expect(out[0]).toMatchObject({ senderUin: 222, elements: [{ type: 'text', text: 'hi' }] }); }); + it('keeps and warns on a body that had content but decoded to no elements', async () => { + const resp = protobuf_encode({ + friendUid: 'u_friend', + messages: [{ + responseHead: { fromUin: 222, forward: { friendName: 'Bob' } }, + contentHead: { msgType: 166, sequence: 9120, ntMsgSeq: 120, timestamp: 1700000120, msgId: 7120 }, + body: { richText: { elems: [{ commonElem: { serviceType: 999, businessType: 0 } }] } }, + }], + }); + const warnings: string[] = []; + setLogLevel('warn'); + const unsubscribe = subscribeLogs((entry: LogEntry) => { + if (entry.level === 'warn') warnings.push(entry.message); + }); + try { + const out = await fetchC2cMessageRange( + { sendRawPacket: async () => okResult(resp) }, + identity, + 10001, + 'u_friend', + 100, + 120, + ); + expect(out).toHaveLength(1); + expect(out[0]).toMatchObject({ kind: 'friend_message', ntMsgSeq: 120, elements: [] }); + expect(warnings.some((message) => message.includes('missing decoder'))).toBe(true); + } finally { + unsubscribe(); + } + }); + it('rejects a visible message without the canonical NT sequence', async () => { const resp = protobuf_encode({ friendUid: 'u_friend', diff --git a/packages/protocol/tests/msg-push/fetch-group-history.test.ts b/packages/protocol/tests/msg-push/fetch-group-history.test.ts index c70a53b8..6d2d9c50 100644 --- a/packages/protocol/tests/msg-push/fetch-group-history.test.ts +++ b/packages/protocol/tests/msg-push/fetch-group-history.test.ts @@ -2,7 +2,13 @@ // field tags) and the fetched-history decode path (each returned PushMsgBody // re-uses the regular group decoder). -import { describe, expect, it } from 'vitest'; +import { + getLogLevel, + setLogLevel, + subscribeLogs, + type LogEntry, +} from '@snowluma/common/logger'; +import { afterEach, describe, expect, it } from 'vitest'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg'; @@ -10,6 +16,11 @@ import type { IdentityService } from '../../src/identity-service'; import { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from '../../src/msg-push'; const identity = { findGroupMember: () => undefined, findGroup: () => null } as unknown as IdentityService; +const previousLogLevel = getLogLevel(); + +afterEach(() => { + setLogLevel(previousLogLevel); +}); function okResult(data: Uint8Array): SendPacketResult { return { success: true, gotResponse: true, responseData: data } as SendPacketResult; @@ -119,6 +130,39 @@ describe('fetchGroupMessageRange / SsoGetGroupMsg', () => { expect(out[0]).toMatchObject({ senderUin: 222, elements: [{ type: 'text', text: 'hi' }] }); }); + it('keeps and warns on a body that had content but decoded to no elements', async () => { + const resp = protobuf_encode({ + body: { + groupUin: 9999, + messages: [{ + responseHead: { fromUin: 222, grp: { groupUin: 9999, memberName: 'Bob' } }, + contentHead: { msgType: 82, sequence: 120, timestamp: 1700000120, msgId: 5120 }, + body: { richText: { elems: [{ commonElem: { serviceType: 999, businessType: 0 } }] } }, + }], + }, + }); + const warnings: string[] = []; + setLogLevel('warn'); + const unsubscribe = subscribeLogs((entry: LogEntry) => { + if (entry.level === 'warn') warnings.push(entry.message); + }); + try { + const out = await fetchGroupMessageRange( + { sendRawPacket: async () => okResult(resp) }, + identity, + 10001, + 9999, + 100, + 120, + ); + expect(out).toHaveLength(1); + expect(out[0]).toMatchObject({ kind: 'group_message', msgSeq: 120, elements: [] }); + expect(warnings.some((message) => message.includes('missing decoder'))).toBe(true); + } finally { + unsubscribe(); + } + }); + it('drops QQ null roam records even when they carry a deleted placeholder (#254)', async () => { const resp = protobuf_encode({ body: { From 6cf461ef8fefa84f0ffa727326b629e4b9c2fb0e Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 30 Aug 2026 16:08:35 +0800 Subject: [PATCH 07/11] refactor(onebot): subscribe every event kind in the pipeline Conversion still decides whether an event becomes OneBot JSON. The pipeline now lists every kind as handle or drop, so a new converted kind cannot be forgotten. --- packages/onebot/src/event-converter/index.ts | 4 +- packages/onebot/src/event-pipeline.ts | 258 ++++++++++++------- packages/onebot/tests/event-pipeline.test.ts | 24 ++ 3 files changed, 186 insertions(+), 100 deletions(-) diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index d15b9ec3..60efddbf 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -71,9 +71,9 @@ type ConverterFor = * new `QQEventVariant` kind that forgets a converter is a compile error here — * not a silent `null` at runtime. */ -type ConverterRegistry = { [K in QQEventVariant['kind']]: ConverterFor | null }; +export type ConverterRegistry = { [K in QQEventVariant['kind']]: ConverterFor | null }; -const CONVERTERS: ConverterRegistry = { +export const CONVERTERS: ConverterRegistry = { // Messages. friend_message: convertFriendMessage, group_message: convertGroupMessage, diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 1dd18296..dcf4a36d 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -1,7 +1,7 @@ import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger'; import { renderParamsVerbose } from '@snowluma/common/log-summary'; import type { QQEventVariant } from '@snowluma/protocol/events'; -import { convertEvent } from './event-converter'; +import { CONVERTERS, convertEvent } from './event-converter'; import type { OneBotInstanceContext } from './instance-context'; import { GROUP_MESSAGE_EVENT, @@ -75,84 +75,14 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipeline }); }; - disposers.push( - ctx.bridge.events.on('group_message', (event) => track(event, async (state) => { - cacheGroupMessageMeta(ctx, event); - await convertAndDispatch(ctx, log, event, state); - })), - ); - disposers.push( - ctx.bridge.events.on('friend_message', (event) => track(event, async (state) => { - cachePrivateMessageMeta( - ctx, - event.peerUin ?? event.senderUin, - event.msgSeq, - event.ntMsgSeq ?? 0, - event.clientSeq ?? event.msgSeq, - event.time, - event.msgId, - event.sequenceAuthoritative !== false, - event.senderUin === ctx.selfId ? 'outgoing' : 'incoming', - ); - await convertAndDispatch(ctx, log, event, state); - })), - ); - disposers.push( - ctx.bridge.events.on('temp_message', (event) => track(event, async (state) => { - cachePrivateMessageMeta( - ctx, - event.senderUin, - event.msgSeq, - event.ntMsgSeq ?? 0, - event.clientSeq ?? 0, - event.time, - 0, - event.sequenceAuthoritative !== false, - undefined, - ); - // Record this group temp session so a later reply is limited to sessions - // the peer opened. - ctx.tempSessions.record(event.senderUin, event.groupId); - await convertAndDispatch(ctx, log, event, state); - })), - ); - for (const kind of NOTICE_KINDS) { + for (const kind of Object.keys(EVENT_PIPELINE) as EventKind[]) { + const entry = EVENT_PIPELINE[kind]; + if ('drop' in entry) continue; + const handle = entry.handle as PipelineHandler; disposers.push( - ctx.bridge.events.on(kind, (event) => track(event, async (state) => { - if (event.kind === 'group_msg_emoji_like') { - cacheReaction(ctx, event); - } - let messageIdOverride: number | undefined; - if (event.kind === 'friend_recall') { - const clientSequence = event.clientSeq ?? event.msgSeq; - const recalled = ctx.messageStore.recordPrivateRecall( - event.userUin, - clientSequence, - event.recalledBySelf === true, - event.time, - ); - if (recalled !== null) { - messageIdOverride = recalled; - } else { - log.debug( - 'friend recall cache miss peer=%d clientSeq=%d', - event.userUin, - clientSequence, - ); - } - } - await convertAndDispatch(ctx, log, event, state, messageIdOverride); - })), + ctx.bridge.events.on(kind, (event) => track(event, (state) => handle(ctx, log, event, state))), ); } - // Internal-only: voice-to-text result push. Not converted to a OneBot event — - // it just unblocks the fetch_ptt_text call waiting on this msgId. - disposers.push( - ctx.bridge.events.on('ptt_trans_result', (event) => track(event, (state) => { - deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text); - traceEventTerminal(log, event.kind, state, 'internal', 'waiter_notified'); - })), - ); const stop = (): void => { if (!accepting) return; @@ -182,28 +112,20 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipeline }; } -const NOTICE_KINDS = [ - 'group_member_join', - 'group_member_leave', - 'group_mute', - 'group_admin', - 'friend_recall', - 'group_recall', - 'friend_request', - 'group_invite', - 'friend_poke', - 'group_poke', - 'group_essence', - 'group_file_upload', - 'friend_add', - 'friend_input_status', - 'friend_profile_like', - 'bot_offline', - 'group_name_change', - 'group_title_change', - 'group_card_change', - 'group_msg_emoji_like', -] as const satisfies readonly QQEventVariant['kind'][]; +type EventKind = QQEventVariant['kind']; + +type PipelineHandler = ( + ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +) => void | Promise; + +type PipelineDisposition = + | { readonly handle: PipelineHandler } + | { readonly drop: true }; + +type PipelineRegistry = { [K in EventKind]: PipelineDisposition }; interface EventTraceState { startedAt: number; @@ -404,3 +326,143 @@ function cacheReaction( ); } } + +function handleGroupMessage( + ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +): Promise { + cacheGroupMessageMeta(ctx, event); + return convertAndDispatch(ctx, log, event, state); +} + +function handleFriendMessage( + ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +): Promise { + cachePrivateMessageMeta( + ctx, + event.peerUin ?? event.senderUin, + event.msgSeq, + event.ntMsgSeq ?? 0, + event.clientSeq ?? event.msgSeq, + event.time, + event.msgId, + event.sequenceAuthoritative !== false, + event.senderUin === ctx.selfId ? 'outgoing' : 'incoming', + ); + return convertAndDispatch(ctx, log, event, state); +} + +function handleTempMessage( + ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +): Promise { + cachePrivateMessageMeta( + ctx, + event.senderUin, + event.msgSeq, + event.ntMsgSeq ?? 0, + event.clientSeq ?? 0, + event.time, + 0, + event.sequenceAuthoritative !== false, + undefined, + ); + ctx.tempSessions.record(event.senderUin, event.groupId); + return convertAndDispatch(ctx, log, event, state); +} + +function handleFriendRecall( + ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +): Promise { + const clientSequence = event.clientSeq ?? event.msgSeq; + const recalled = ctx.messageStore.recordPrivateRecall( + event.userUin, + clientSequence, + event.recalledBySelf === true, + event.time, + ); + let messageIdOverride: number | undefined; + if (recalled !== null) { + messageIdOverride = recalled; + } else { + log.debug( + 'friend recall cache miss peer=%d clientSeq=%d', + event.userUin, + clientSequence, + ); + } + return convertAndDispatch(ctx, log, event, state, messageIdOverride); +} + +function handleGroupMsgEmojiLike( + ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +): Promise { + cacheReaction(ctx, event); + return convertAndDispatch(ctx, log, event, state); +} + +function handlePttTransResult( + _ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +): void { + deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text); + traceEventTerminal(log, event.kind, state, 'internal', 'waiter_notified'); +} + +const convertOnly: PipelineHandler = convertAndDispatch; + +const EVENT_PIPELINE = { + friend_message: { handle: handleFriendMessage }, + group_message: { handle: handleGroupMessage }, + temp_message: { handle: handleTempMessage }, + group_member_join: { handle: convertOnly }, + group_member_leave: { handle: convertOnly }, + group_mute: { handle: convertOnly }, + group_admin: { handle: convertOnly }, + friend_recall: { handle: handleFriendRecall }, + group_recall: { handle: convertOnly }, + friend_request: { handle: convertOnly }, + group_invite: { handle: convertOnly }, + friend_poke: { handle: convertOnly }, + group_poke: { handle: convertOnly }, + group_essence: { handle: convertOnly }, + group_file_upload: { handle: convertOnly }, + friend_add: { handle: convertOnly }, + friend_input_status: { handle: convertOnly }, + friend_profile_like: { handle: convertOnly }, + bot_offline: { handle: convertOnly }, + group_name_change: { handle: convertOnly }, + group_title_change: { handle: convertOnly }, + group_card_change: { handle: convertOnly }, + group_msg_emoji_like: { handle: handleGroupMsgEmojiLike }, + ptt_trans_result: { handle: handlePttTransResult }, + online_devices_changed: { drop: true }, + friend_remark_changed: { drop: true }, +} as const satisfies PipelineRegistry; + +type ConvertedKind = { + [K in EventKind]: (typeof CONVERTERS)[K] extends null ? never : K +}[EventKind]; + +type DroppedKind = { + [K in EventKind]: (typeof EVENT_PIPELINE)[K] extends { drop: true } ? K : never +}[EventKind]; + +type ConvertedButDropped = ConvertedKind & DroppedKind; +const _convertedKindsAreHandled: [ConvertedButDropped] extends [never] ? true : ConvertedButDropped = true; +void _convertedKindsAreHandled; diff --git a/packages/onebot/tests/event-pipeline.test.ts b/packages/onebot/tests/event-pipeline.test.ts index 38b8eb2e..55397401 100644 --- a/packages/onebot/tests/event-pipeline.test.ts +++ b/packages/onebot/tests/event-pipeline.test.ts @@ -234,6 +234,30 @@ describe('registerEventPipeline', () => { expect(dispatchCalls[0].notice_type).toBe('group_increase'); }); + it('does not subscribe to kinds the pipeline marks dropped', async () => { + const { ctx, bus, dispatchCalls } = makeContext(); + registerEventPipeline(ctx); + vi.mocked(convertEvent).mockClear(); + + await bus.emit({ + kind: 'online_devices_changed', + time: 1700000000, + selfUin: SELF_ID, + devices: [], + }); + await bus.emit({ + kind: 'friend_remark_changed', + time: 1700000000, + selfUin: SELF_ID, + userUid: 'u_peer', + userUin: PEER_UIN, + remark: 'x', + }); + + expect(dispatchCalls).toHaveLength(0); + expect(convertEvent).not.toHaveBeenCalled(); + }); + it('removes a recalled private message and reports its original OneBot id', async () => { const recordPrivateRecall = vi.fn(() => -7654321); const { ctx, bus, dispatchCalls } = makeContext({ From a7d293d79bf99dc45005dfa485570f860e1b1650 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 30 Aug 2026 16:14:56 +0800 Subject: [PATCH 08/11] fix(onebot): make the event pipeline tables type-check A handler shared by several event kinds now types as one kind at a time. The converter table still records which kinds are not converted, so the compile-time check for dropped converted kinds works. --- packages/onebot/src/event-converter/index.ts | 4 ++-- packages/onebot/src/event-pipeline.ts | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 60efddbf..add22c68 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -73,7 +73,7 @@ type ConverterFor = */ export type ConverterRegistry = { [K in QQEventVariant['kind']]: ConverterFor | null }; -export const CONVERTERS: ConverterRegistry = { +export const CONVERTERS = { // Messages. friend_message: convertFriendMessage, group_message: convertGroupMessage, @@ -107,7 +107,7 @@ export const CONVERTERS: ConverterRegistry = { online_devices_changed: null, // Internal-only identity synchronization from another QQ client. friend_remark_changed: null, -}; +} satisfies ConverterRegistry; export async function convertEvent( ctx: ConverterContext, diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index dcf4a36d..bbb0b169 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -424,7 +424,14 @@ function handlePttTransResult( traceEventTerminal(log, event.kind, state, 'internal', 'waiter_notified'); } -const convertOnly: PipelineHandler = convertAndDispatch; +function convertOnly( + ctx: OneBotInstanceContext, + log: Logger, + event: Extract, + state: EventTraceState, +): Promise { + return convertAndDispatch(ctx, log, event, state); +} const EVENT_PIPELINE = { friend_message: { handle: handleFriendMessage }, From f5e95fc634abf16d244f47866628afc92c3e70ac Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 30 Aug 2026 20:43:45 +0800 Subject: [PATCH 09/11] fix(protocol): keep private recall ids exact Private delete_msg could return success while the message stayed visible. The 64-bit id sent with a private recall is now built with integer bits so it matches the original message. Fixes #431 --- packages/core/src/bridge/apis/message.ts | 2 +- packages/core/tests/actions/group-message.test.ts | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index 13520804..30cdb3b8 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -715,7 +715,7 @@ export class MessageApi { info: { clientSequence: clientSeq, random, - messageId: BigInt((0x01000000 * 0x100000000) + random), + messageId: (0x01000000n << 32n) | BigInt(random >>> 0), timestamp, field5: 0, messageSequence: msgSeq, diff --git a/packages/core/tests/actions/group-message.test.ts b/packages/core/tests/actions/group-message.test.ts index f945a0b5..22824d5d 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -7,6 +7,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { + C2CRecallRequest, SsoReadedReportReq, SsoReadedReportResp, } from '@snowluma/proto-defs/oidb-actions/base'; @@ -66,6 +67,17 @@ describe('apis/message — recall + markRead', () => { expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg'); }); + it('recallPrivate keeps the 64-bit message id exact for any random', async () => { + const random = 0x1234567; + const bridge = mockBridge(); + await new MessageApi(bridge as any).recallPrivate(10001, 11110, 200, random, 1700000000); + + const [, body] = bridge.sendRawPacket.mock.calls[0]!; + const request = protobuf_decode(body); + expect(request.info?.random).toBe(random); + expect(request.info?.messageId).toBe(0x0100000001234567n); + }); + it('probes and confirms group plus private reads in the same packets', async () => { const sendRawPacket = vi.fn() .mockResolvedValueOnce(readReportResult({ From f327fc1276913b1ce3b72beb925c958c4e27ddc1 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 30 Aug 2026 21:31:27 +0800 Subject: [PATCH 10/11] fix(webui): explain unmet password rules after blur The requirement list still opens only while the new-password field is focused. After blur, unmet rules stay visible as field text, and Save can be pressed to return focus to that field. --- .../components/pages/change-password-form.tsx | 47 ++++++++++++++--- .../pages/onboarding-wizard-page.tsx | 4 +- packages/webui/tests/password-inputs.test.tsx | 52 +++++++++++++++++++ 3 files changed, 94 insertions(+), 9 deletions(-) diff --git a/packages/webui/src/components/pages/change-password-form.tsx b/packages/webui/src/components/pages/change-password-form.tsx index 89f47306..424d37b6 100644 --- a/packages/webui/src/components/pages/change-password-form.tsx +++ b/packages/webui/src/components/pages/change-password-form.tsx @@ -28,6 +28,23 @@ const EMPTY_RULES: readonly PasswordRule[] = [ const STRENGTH_LABELS = ['未输入', '很弱', '较弱', '一般', '良好', '强'] as const; +/** Shown under the new-password field only while the animated rule list is hidden. */ +export function passwordRequirementHint(options: { + focused: boolean; + value: string; + checked: boolean; + valid: boolean; + rules: readonly PasswordRule[]; + checkError: string; +}): string | null { + if (options.focused || options.value.length === 0) return null; + if (options.checkError) return `密码强度校验失败:${options.checkError}`; + if (!options.checked || options.valid) return null; + const unmet = options.rules.filter((rule) => !rule.ok); + if (unmet.length === 0) return '密码尚未满足全部要求'; + return `仍需满足:${unmet.map((rule) => rule.label).join('、')}`; +} + export interface ChangePasswordFormProps { /** Selects whether the form changes credentials or only rehearses validation. */ mode?: 'change' | 'rehearsal'; @@ -57,6 +74,8 @@ export interface ChangePasswordFormProps { className?: string; renderActions?: (state: { canSubmit: boolean; + /** Fields are filled enough to try saving; strength may still be unmet. */ + canAttempt: boolean; submitting: boolean; submitLabel: string; }) => ReactNode; @@ -118,12 +137,20 @@ export function ChangePasswordForm({ [displayedRules], ); const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword; - const canSubmit = + const canAttempt = !submitting && (rehearsing || effectiveOld.length > 0) - && valid && confirmMatches && (rehearsing || effectiveOld !== newPassword); + const canSubmit = canAttempt && valid; + const requirementHint = passwordRequirementHint({ + focused: newPasswordFocused, + value: newPassword, + checked: checkedCurrentPassword, + valid, + rules: displayedRules, + checkError: strengthError, + }); // Debounce the strength check so we don't slam the API on every keystroke. useEffect(() => { @@ -156,7 +183,12 @@ export function ChangePasswordForm({ const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - if (!canSubmit) return; + if (!canAttempt) return; + if (!valid) { + setNewPasswordFocused(true); + document.getElementById(`${idPrefix}-new`)?.focus(); + return; + } setSubmitting(true); setError(''); try { @@ -220,11 +252,12 @@ export function ChangePasswordForm({ onChange={setNewPassword} onFocus={() => setNewPasswordFocused(true)} onBlur={() => setNewPasswordFocused(false)} - validationKey={effectiveOld} + validationKey={`${effectiveOld}\0${newPasswordFocused}\0${valid}\0${strengthError}\0${requirementHint ?? ''}`} + reserveLines={2} validate={(value) => { if (value.length === 0) return '请输入新密码'; if (!rehearsing && value === effectiveOld) return '新密码不能与当前密码相同'; - return null; + return requirementHint; }} showValidIcon={false} endAdornment={( @@ -294,14 +327,14 @@ export function ChangePasswordForm({ )} - {renderActions ? renderActions({ canSubmit, submitting, submitLabel }) : ( + {renderActions ? renderActions({ canSubmit, canAttempt, submitting, submitLabel }) : (
{onCancel && ( )} - -