fetchPrivateFileUrl now uses the current account UID (resolveSelfUid) as receiverUid instead of resolving the peer UID, matching Lagrange.Core/NapCat behavior and avoiding NTQQ fulllink handler timeouts. The userId parameter is intentionally unused. runOidb gained an optional timeoutMs argument and the private-file request uses a 5000ms timeout; bridge.sendRawPacket is forwarded this timeout.
CI tsc flagged two strict-mode issues in d1aade6:
* element-builder: `ctx?.forwardFake` doesn't carry the non-null
narrowing to a subsequent `ctx.groupId` access — replace with an
explicit `ctx && ctx.forwardFake` guard.
* forward-file.test: `vi.fn(async () => [])` infers `mock.calls`
as `[][]`, so `const [, ctx] = mock.calls[0]!` is "Tuple of length
'0' has no element at index '1'". Declare the mock's parameter
types (`unknown[], Record<string, unknown>?`) so the call tuple
has the right arity, and use `ctx?.groupId` since the ctx slot
is now typed as optional.
Previous fix split file segments off at the OneBot live-send layer
(c2c → sendC2cFileMessage, group → sendGroupFileMessage) and made
element-builder drop any `{type:'file'}` segment that reached it.
That broke forward messages: send_forward_msg encodes each node
through buildSendElems for the long-msg upload, so file segments
inside a forward node hit the drop-with-warn path and the forward
bubble shipped without the file.
Forward upload is NOT a live PbSendMsg — it stores the gzipped
protobuf verbatim through `trpc.group.long_msg_interface.MsgService.
SsoSendLongMsg`, and the recipient decodes file entities through the
normal msg-push path (transElem(24) → GroupFileExtra; msgContent →
FileExtra { file: NotOnlineFile }). So `result=79` doesn't apply here.
Add a `forwardFake?: true` flag on SendContext; when set:
* group file → element-builder emits transElem(24) again (restored
makeGroupFileElem, exactly the receive-side wire shape).
* c2c file → element-builder still skips; forward-builder pulls the
segment off the node and writes `body.msgContent` as
FileExtra { file: NotOnlineFile }, with file metadata hydrated
from the upload cache when inline fields are missing (same
pattern as send_private_msg).
Mirrors NapCat's PacketMsgFileElement.{buildElement,buildContent}
split (dev/napcatQQ/.../packet/message/element.ts:530-610) and
Lagrange.Core V2's MultiMsgUploadService.cs.
The chat-publish step after upload_group_file used to ship a PbSendMsg
with a transElem(elemType=24) — but that wire shape is RECEIVE-side
only, and current QQ-NT rejects it on send with `result=79`. Lagrange.
Core V2 uses a dedicated `OidbSvcTrpcTcp.0x6d9_4` for the publish
(`GroupSendFileService.cs`); mirror that. Send_group_msg with a
`{type:'file', file_id}` segment now routes through the same path
after the OneBot layer splits file segments out (matching the c2c
file split pattern).
Separately, send_private_msg with just `{file_id}` was shipping a 0 B
file because the wire packet for c2c file send needs fileSize/fileMd5/
fileName/fileHash but the OneBot caller only echoes the file_id from
upload_private_file. Add a bounded (1024-entry, FIFO) bridge cache
populated at upload time so the send-message path can rehydrate the
full tuple; inline segment fields still take precedence so callers
that track the metadata themselves can bypass the cache. Parser now
also accepts `file_hash`/`fileHash` on file segments.
Also: file segments no longer get a `[空消息]` log line — the format
string now shows `[文件:<name-or-id>]`.
The c2c file send path was wrong on three independent axes — every
c2c file the bot tried to deliver was getting rejected by the QQ-NT
server. Aligned to `dev/Lagrange.Core` (V2 branch) which is the only
direct-protocol reference for c2c files; NapCat goes through QQ-NT
IPC and never builds this packet itself.
Three wire-shape fixes:
1. **Routing**: `routingHead.c2c { uin, uid }` → `routingHead.trans0x211
{ ccCmd: 4, uid }`. RoutingHead field 15 is the c2c-file scene's
slot. `MessagePacker.BuildPacketBase` makes this conditional on
`chain.HasTypeOf<FileEntity>()`: when a file is present, C2C goes
nil and Trans0X211 carries the routing.
2. **File payload location**: `messageBody.richText.notOnlineFile {...}`
→ `messageBody.msgContent = serialize(FileExtra{file: NotOnlineFile})`.
The server doesn't read c2c file metadata from `richText` at all —
`MessageBody.cs:12` even has the comment "Offline file is now put
here(?". Confirmed by `FileEntity.PackElement()` returning empty
and `PackMessageContent()` returning the FileExtra wrapper.
3. **contentHead.c2cCmd**: `11` → `0` (default/omitted). `11` was a
stale go-cqhttp value the QQ-NT server doesn't recognise on the
c2c-file dispatcher. Lagrange leaves it at the C# default (0).
Schema fixes (proton + legacy, both directions):
- `RoutingHead` gains `trans0x211?: pb<15, RoutingTrans0x211>`. The
new message has `toUin@1`, `ccCmd@2`, `uid@8`.
- `SendMessageBody` gains `msgContent?: pb<2, bytes>` (the receive-side
`MessageBody` already had it).
- `FileExtraInfo` deleted — was wrong on every tag (fileSize=1,
fileName=2, fileMd5=3, fileUuid=4, fileHash=5, none of which match
the wire). `FileExtra { file: pb<1, NotOnlineFile> }` now wraps the
same `NotOnlineFile` used on the receive path. This is why c2c file
PUSHES were also silently failing the four-field truthy check in
`extractMsgContent` — the schema couldn't decode anything.
- `NotOnlineFile` gains the three intake-validator fields the server
requires on send: `subcmd@9 = 1`, `dangerEvel@50 = 0`, `expireTime@55`
= now+7d.
Receive side (`rich-body-decoder.ts::extractMsgContent`): drop the
"all four fields must be truthy" guard (it was a workaround for the
broken schema) and accept any payload that decodes a fileUuid.
Tests:
- `bridge-private-routing.test.ts`: new regression that round-trips
`sendC2cFileMessage` through `protoDecode` and asserts trans0x211
routing, msgContent FileExtra wrapper, NotOnlineFile field tags,
c2cCmd=0. Catches each of the three wire-shape regressions
independently.
- `send-private-c2c-file.test.ts`: vi.fn arg signatures explicit for
CI typecheck.
647/647 tests pass.
User report: `send_private_msg` with a `{type:'file', file_id}` segment
fired `[ElemBuilder] file send via elems[] is group-only; use bridge.
sendC2cFileMessage for c2c` and the message went out as "[空消息]".
Root cause: c2c files live on `RichText.notOnlineFile` (parallel to the
elems array, see proto/proton/message.ts), not inside `elems[]`. The
element-builder explicitly drops c2c `{type:'file'}` elements with a
warning. `sendPrivateMessage` was passing the file straight to
`bridge.sendPrivateMessage(userId, [fileElement])` which then ran
through `buildSendElems`, lost the file at the drop, and shipped a
0-element wire send — rendered as "[空消息]" by every receiver.
Fix: split at the OneBot layer in `sendPrivateMessage`. Pull file
elements out of the batch and dispatch each via
`bridge.sendC2cFileMessage`; route the rest through the regular
elems[] path. Matches NapCat's `dev/NapCatQQ/.../SendMsg.ts:404-415`
where FILE / VIDEO / ARK / PTT each get their own sendMsg call and
never mix with the regular elems[] batch.
- File-only message: only the c2c file API is called (single roundtrip)
- Mixed text + file: two sends, text first then file
- File without file_id: dropped with a warn (was silently shipping
empty messages)
- UID resolution failure: surfaced as throw instead of empty send
Also rewrote the element-builder fallback warn from "use
sendC2cFileMessage for c2c" (now stale advice) to "BUG: c2c file
reached element-builder — should be split out at the OneBot layer".
Tests: 4 new regression cases under
`tests/onebot/send-private-c2c-file.test.ts`. 646/646 pass.
Cross-referenced `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`
(208-347): every layer of a nested forward attaches its own msgBody to
the *outer* long-msg upload under a uuid `actionCommand` slot. Receiver
walks the whole tree from one server fetch instead of resolving each
layer's res_id separately.
`dev/Lagrange.Core` (V2 branch on `linwenxuan04/v2`,
`MultiMsgUploadService.cs:23-31`) only writes a single MultiMsg action
— that's why NapCat-style receivers couldn't follow our previous
nested-forward sends past the first level.
Refactor:
1. `ForwardNodePayload` gets an optional `innerForward?:
ForwardNodePayload[]` field. `parseForwardNodes` no longer eagerly
uploads inner chains — it just attaches them here.
2. `uploadForwardNodes` now drives the whole recursion. The new
`uploadForwardNodesRecursive`:
- walks each node, recursively uploads any `innerForward` first
- replaces that node's `elements` with a real `{type:'forward'}`
preview pointing at the inner res_id
- piggybacks the inner level's `{uuid, msgBody}` + every deeper
level it surfaced into this level's `myInnerActions`
- encodes the long-msg payload as
`[{MultiMsg, ownMsgBody}, ...innerActions.map(uuid+msgBody)]`
- returns `{resId, msgBody, uuid, innerActions}` so an outer call
can keep climbing
Top-level public signature unchanged: `Promise<string>`.
3. New `deriveInnerSource` / `previewLinesFromNodes` /
`previewFromElements` helpers synthesise the ARK preview metadata
the inner bubble shows before the user taps to expand. They handle
text/image/record/video/file/forward/face element previews.
4. `parseForwardNodes`: when `content` is an all-node array, attach
the parsed inner chain to `node.innerForward` and let the upload
pipeline take over. `elements = []` placeholder is replaced by
`uploadForwardNodes` once it has the real res_id.
Tests:
- `actions/forward.test.ts`:
- `uploadForwardNodes recursively uploads nested innerForward chains
(NapCat piggyback model)` — asserts two SsoSendLongMsg roundtrips
(inner first, then outer) and the outer res_id propagates up
- `flat sends still take a single roundtrip` — backwards-compat
- `onebot/forward-nested.test.ts`: rewritten — mock now sees exactly
one `uploadForwardNodes` call with `innerForward` attached, instead
of two sequential calls; depth-limit + mixed-content tests
unchanged.
The NTV2 upload request for video carried `time: 0` on the main mp4
sub-file, mirroring NapCat's transformer. But NapCat lives on top of
the desktop QQ-NT client's IPC layer, which patches the duration into
the resulting MsgInfo before the wire send — we don't have that layer,
so the `time: 0` we passed in ended up baked into the `VideoFile.
fileTime` field of every video the bot sent. Receivers then rendered
every video bubble as "00:00".
Cross-checked acidify's `RichMediaUpload.kt::buildVideoUploadInfoList`
(2026-04 refactor) — they're a protocol-direct client too and write
`time = payload.videoDuration` for exactly this reason. We already
have `video.duration` from `loadVideo` (probed via ffprobe), so it's
a one-liner.
Width/height kept at 0 deliberately — acidify fills them, NapCat
zeros them, and our earlier comment recorded "QQ NT server treats
non-zero values here as schema mismatch on c2c sends". Out of scope
for this fix; revisit if a c2c regression surfaces.
Test asserts `fileInfo.time === 10` for the main sub-file (matches
FINGERPRINT.duration) and stays 0 on the thumb.
Two off-by-one bugs in the group-file chat-post element that combined
to make the QQ-NT server reject every group file send with result=79
(visible as "group file uploaded but chat post failed" in the logs):
1. Inner GroupFileInfo fields were shifted one tag left:
- fileSha was field 5, should be field 6
- extInfo was field 6, should be field 7
- fileMd5 was field 7, should be field 8
Field 5 is actually a uint32 placeholder (`field5` in both NapCat
and acidify). With the bug, our fileSha bytes were landing where
the server expected a varint and the rest of the message got
skipped as garbage.
2. Outer GroupFileExtra was missing the magic field1=6 + fileName
slots that NapCat's encoder writes
(`packet/message/element.ts:589`). Acidify's schema also models
them as required even though it serialises with defaults. The
current server build rejects sends without these slots populated.
Cross-referenced:
- NapCat `GroupFileExtraInfo` (component.ts:146-155) — matches our
new field numbers exactly
- acidify `GroupFileExtra.Inner.Info` (proto/message/extra/GroupFileExtra.kt)
— same field numbers; their schema uses generic `field5`/`field7`
names but the wire layout is identical
Changes:
- Proton + legacy schemas: shift inner fields, add outer field1/
fileName/display
- `makeGroupFileElem`: write field1=6 + fileName on the outer wrapper
- Regression test asserts each inner tag lands at 50/58/66 (not the
old 42/50/58) and verifies the new outer field1 + fileName bytes
are present
The 2026 QQ-NT server has stopped populating *every* legacy host field
(uploadIp / uploadDomain / uploadIpList / uploadHttpsDomain / uploadDns).
The host now arrives in the new field 210 `rtpMediaPlatformUploadAddress`
— a repeated `IPv4` message carrying `inIP`/`inPort` (LAN) and
`outIP`/`outPort` (WAN). Coworker's debugging hint "host 好像是 fix64"
was the 8-12-byte length-delimited IPv4 message looking like a
fixed-width field on the wire.
Cross-referenced acidify (https://github.com/LagrangeDev/acidify) —
the only NT-protocol fork that's tracked this change (refactored in
their 2026-04 protobuf rewrite). They read `inIP`+`inPort` exclusively
because that's the address the highway PUT actually needs to reach
(same DC as the OIDB endpoint). LagrangeGo / Lagrange.Core / NapCat
still ship the old schema and would fail the same way against this
server build.
Changes:
- Proton schema: add `IPv4` message (fields 1-5: outIP/outPort/inIP/
inPort/iPType, all int32 varint) + field 210 on the upload response
- Consumer: prefer `rtpMediaPlatformUploadAddress[0].inIP`+`inPort`
before falling back through the legacy host chain
- New helper `int32ToIpv4Dotted` reverses acidify's `Int.toIpString()`
(little-endian byte order, `>>>` for unsigned shift so high-bit IPs
don't render as negative octets)
- Diagnostic warn-log now dumps the rtp address array too
- Regression test: 192.168.1.1 (LE-packed 0x0101A8C0 = 16885952) +
inPort=8080 should reach highway PUT
Surveyed Lagrange.Core (PushMessageService.cs), LagrangeGo
(client/listener.go), lagrange-python (server_push/msg.py), mania
(push_msg.rs), and the tsuzcx/qq_apk decompile — zero handlers for
380 / 0x17C across the lot. Pattern matches subType=38 (also a
QQ-client-internal state push with no OneBot mapping); drop it
through the same silent-acknowledge path so we stop spamming
`MsgPush.Unknown` at debug level on every push.
User report: `upload_private_file` was failing with "private file upload
host is invalid" on a fresh upload (boolFileExist=false). The OIDB call
succeeded but `uploadIp` (field 60) came back empty, and we treated
that single field as the only source of truth.
Cross-referenced LagrangeGo's `OidbSvcTrpcTcp0xE37_800.proto` + NapCat's
`Oidb.0XE37_800.ts`: the server has six parallel host slots on this
response (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain
/ uploadDns / uploadLanip). LagrangeGo + Lagrange.Core only read field
60 and would hit the same dead-end — we walk the chain instead. Also
log the full slot set when we genuinely can't find a host so future
reports can name which field the server actually populated.
Adds two regression tests: one proves the fallback to `uploadDomain`
goes to highway successfully, one proves we still throw when every
slot is empty.
Close three coverage gaps surfaced by the cross-Lagrange-family
audit (Lagrange V2 / LagrangeGo / acidify / lagrange-python):
- **0x210 subType 179 + 226 (NewFriend)** — mutual-accept friend
notice. 179 fires when bot sent a request and the other side
accepted; 226 fires for the opposite direction. Both decode
through the same wire shape. LagrangeGo handles the pair via a
`case 226: case 179:` fallthrough in `client/listener.go:248`.
We surface them as `kind: 'friend_add'`, which the existing
converter routes straight to OneBot `notice.friend_add` — bot
frameworks that wait for "auto-add a friend after they accept"
were previously stuck because nothing arrived.
- **0x210 subType 139 (self-recall)** — bot recalled its own
message sent to a friend. Same `FriendRecall` wire shape as 138
but the peer is on `toUid` instead of `fromUid` — acidify's
`parseFriendRecall:380` splits exactly this way. Without 139,
self-recalls disappeared and downstream `notice.friend_recall`
handlers thought the bot had never recalled anything.
- **PkgType 85 (bot self-joined a group)** — fires on the bot's
session once `set_group_add_request` is approved or an invite is
accepted, ported from lagrange-python's `server_push/msg.py:108`.
PkgType 33 (GroupMemberIncreaseNotice) only fires for *other*
members joining, so without 85 the bot never received its own
`notice.group_increase` until the first message arrived. We
decode `SelfJoinInGroup` and emit `kind: 'group_member_join'`
with `userUin = selfUin`; the existing converter picks
`sub_type: 'approve' | 'invite'` from the operator/user equality
so consumers see the standard OneBot shape.
While wiring 139, also fix a *pre-existing* prod bug spotted via
proton call-site analysis on the resulting bundle: `event-0x210.ts`
imported `FriendRecall` from both `proto/proton/notify` (as
`FriendRecallNotify`) *and* `events` (as the event interface).
Proton's import-resolver registers `importedTypeSources` keyed on
the *imported* name (last-write-wins), so the events.ts import
shadowed the proto one — `protobuf_decode<FriendRecall>(...)` lost
its codec, fell through to the runtime fallback throw, and was
silently swallowed by `MsgPushRegistry.decode`'s catch. Verified by
the substituted codec list in `dist/index.mjs`: pre-fix it had
`FriendRequest` / `GeneralGrayTipInfo` but no `FriendRecall`;
post-fix `FriendRecall` / `NewFriend` / `SelfJoinInGroup` are all
emitted as expected. Side-step the collision by importing the
proto types unaliased and re-deriving the colliding event type via
`Extract<QQEventVariant, { kind: 'friend_recall' }>`.
New proto interfaces in `proto/proton/notify.ts`:
- `NewFriend` + `NewFriendInfo` (uid/time/message/nickName fields,
fields 1-9; ported from
`LagrangeGo/.../notify.proto:25 NewFriend`)
- `SelfJoinInGroup` (groupUin / operatorUid + a few placeholder
fields; ported from
`lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`)
Regression coverage in `tests/msg-push-handler.test.ts`:
- subType 179/226 both produce identical friend_add events
- falls back to `routingHead.fromUin` when the new friend's uid
isn't in the local cache (matches LagrangeGo's
"emit-then-resolve" pattern)
- subType 138 keeps fromUid as the peer (other recalled their
own msg to us); subType 139 picks toUid (we recalled ours
sent to them)
- PkgType 85 emits group_member_join with userUin == selfUin,
operator resolved through identity when known
core: 635/635 tests pass (+7), typecheck clean. Production bundle
now contains substituted codecs for FriendRecall, NewFriend,
SelfJoinInGroup (cross-checked via `grep protobuf_decode_X` on
`dist/index.mjs`).
Earlier this commit acknowledged subType 38 as a placeholder
"FriendGrayTipInfo" because none of the LagrangeDev-family projects
(Lagrange V2 / lagrange-python / LagrangeGo / acidify) have a
handler for it — they all just fall through with a generic
"unknown subType" debug log. The "best guess" gray-tip framing was
wrong.
A contributor traced it through the decompiled stock QQ Android
client to `com.tencent.imcore.message.ext.codec.decoder.msgType0x210
.SubType0x26` (tsuzcx/qq_apk @ afe46ef). The payload is
`submsgtype0x26.MsgBody` dispatching on `uint32_sub_cmd`:
- 0x1 → `UpdateAppUnreadNum`: a list of
`{group_code, app_id, unread_num}` keeping group-internal
"mini-app" badge counts (e.g. `appId=101846662` / `101896870`
for the troop shortcut bar) in sync.
- 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
discussion-group app tips, routed through `getGAudioHandler()`.
- 0x4 → delegated to the troop online-push handler.
None of these have a meaningful OneBot mapping — they're
QQ-client-UI state pushes (badge counts, in-app tips), not
conversation events. Rename the enum entry to `GroupAppStatePush`
to reflect the actual semantics, cite the decompiled source
inline, and keep the silent-drop behaviour from the previous
attempt. Tests + decoder routing follow the rename.
628/628 tests pass (unchanged), typecheck clean.
`upload_group_file` / `upload_private_file` used to do only the
upload half of the napcat-equivalent flow:
OIDB 0x6D6_0 alloc → highway PUT → return fileId
The fileId was real, the bytes were on QQ's CDN, the logs said
"uploaded" — but the chat showed nothing because no message was
ever sent referring to the upload. NapCat's `UploadGroupFile`
action (`dev/napcatQQ/.../UploadGroupFile.ts:54-58`) does the
upload AND immediately calls `MsgApi.sendMsg(peer, [fileElement])`
in the same action; that second step is what makes the file
visible in the chat.
Add the missing send step. Two paths because the wire shape
differs:
- **Group files** ride on `Elem.transElem` (type 24) in the
`RichText.elems` array. Add a `makeGroupFileElem()` helper +
`case 'file':` in `element-builder.buildSendElems`, then
`bridge.sendGroupMessage(groupId, [fileElement])` after a
successful upload. The TransElem wraps a `GroupFileExtra`
protobuf in `0x01 | BE16(len) | payload`, byte-symmetric with
the receive-side decoder at `rich-body-decoder.ts:171-185`.
- **C2C (private) files** live on `RichText.notOnlineFile`
(field 3 on RichText, parallel to `elems`), so they can't go
through `buildSendElems` at all. Add `Bridge.sendC2cFileMessage`
that builds the `SendMessageRequest` with `notOnlineFile`
directly and dispatches via `sendRawPacket`. The decoder side
that lifts these back to `{type:'file'}` segments has lived
at `rich-body-decoder.ts:425-433` the whole time.
Behavioural detail: both upload paths call the chat-publish step
*only* when `uploadFile=true` (the default). `uploadFile=false`
keeps the upload-only semantics for callers that just want a
fileId without dropping a message in the chat. If the chat post
fails for any reason (server rejection / network), the action
still returns the fileId with a warning log — the file is on QQ's
side, callers can re-publish if they want.
Regression coverage in `tests/actions/group-file.test.ts`:
- publishes the file as `{type:'file'}` via sendGroupMessage on
group upload
- skips the post when uploadFile=false
- returns success even when the chat post fails
- same trio for private upload going through sendC2cFileMessage
- and confirms private path does NOT route through the
`sendPrivateMessage` elems[] pipeline
core: 618/618 tests pass (+5), typecheck clean. Production build
contains 8 substituted call sites for the new GroupFileExtra +
SendMessageRequest paths under proton.
PR #31 landed 4 TRPC group-album actions on the legacy runtime
schema encoder. Migrate them to the compile-time codec, matching
the pattern established by the OIDB migration: TS interfaces in
`proto/proton/oidb-action.ts` are monomorphized at build time and
each `protoEncode/Decode` call site now calls `protobuf_encode<T>` /
`protobuf_decode<T>` directly.
- Add 33 proton interfaces for the new TRPC envelopes (GetMediaList,
DoQunComment, DoQunLike, DeleteMedias, plus all nested types) —
inline anonymous schemas in legacy lifted to named interfaces.
- Migrate `actions/group-album.ts` to the proton API; drop the
`(resp as any)` casts now that decoded responses are typed.
- Add 4 wire-byte parity tests for the new envelopes; non-default
field values throughout so byte equivalence holds (proto3 omission
of defaults is the documented divergence).
- Drop dead `GroupAvatarUploadExtSchema` from `proto/highway.ts` and
unused `import * as console from "node:console"` in
`web/group-album.ts` — leftovers from the original PR review.
core: 609/609 tests pass, typecheck clean.
Closes the OIDB phase of the proton migration. Every consumer that
talked to the OIDB service through the old runtime
`makeOidbBaseSchema()` factory now goes through the compile-time
generic `OidbBase<T>` instead — proton monomorphizes the codec per
call-site instantiation.
@snowluma/proton — two analyzer fixes uncovered by the migration:
1. Skip queuing call-site type-args that reference an *enclosing
generic function's* type parameter for monomorphization. Before
this, a wrapper like
export function encodeOidbEnv<T>(env: OidbBase<T>): Uint8Array {
return protobuf_encode<OidbBase<T>>(env);
}
would cause the analyzer to mint a literal `OidbBase__T` registry
entry with `body.typeName = 'T'`, which the post-walk wire-type
guard then tripped on. The enclosing-scope type params are tracked
on a stack as the walker descends into FunctionDeclaration,
FunctionExpression, ArrowFunction, MethodDeclaration nodes; matching
call sites are skipped (the wrapper-binding path is still
responsible for materialising concrete codecs at downstream call
sites).
2. Register *explicitly* empty interfaces (`interface X {}`) as
zero-field proto messages. OIDB has a handful of these
('this call has no meaningful response body' placeholders —
Oidb0xeb7Resp, Oidb0xcd4Resp, Oidb0x112aResp, Oidb0x8a0Resp,
Oidb0xf16Resp, OidbClientKeyReq). Proto3 wire allows zero-field
messages, and downstream code does `protobuf_decode<OidbBase<X>>`
where X is one of these — the wire-type guard would otherwise trip
on the missing `X` registration. Interfaces that have members but
no pb-marked fields are still NOT registered.
@snowluma/core — the OIDB-layer refactor itself:
bridge-oidb.ts ditches the runtime ProtoSchema factory and exposes:
- makeOidbEnvelope<T>(oidbCmd, subCmd, body, isUid) pure helper
- encodeOidbEnv<T>(env) pass-through
- decodeOidbEnv<T>(bytes) pass-through
- runOidb(bridge, cmd, envelopeBytes) non-generic raw
`encodeOidbEnv` / `decodeOidbEnv` are pure pass-through generic
wrappers — proton wrapper-binds them and substitutes every call site
with the inlined `protobuf_encode_OidbBase__X` / `protobuf_decode_…`
function. `runOidb` is non-generic (proton leaves it alone) so it can
be mocked in tests. `makeOidbEnvelope` is plain TS — also mockable for
introspection.
56 `runOidb` call sites across 11 files migrated to the new API:
- bridge-contacts.ts, actions/extras.ts, actions/friend.ts,
actions/group-admin.ts, actions/group-file.ts,
actions/group-message.ts, actions/interaction.ts,
actions/misc.ts, actions/profile.ts, web-actions/cookies.ts,
highway/pipeline.ts
pipeline.ts also drops `makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)`
and the residual `protoEncode({...}, EncodableMediaMsgInfoSchema)` —
both go through proton now.
Tests:
- 8 test files migrated from `vi.mocked(decodeOidbEnv).mockReturnValueOnce`
to `vi.mocked(runOidb).mockResolvedValueOnce(protobuf_encode<OidbBase<X>>({body: …}))`
— the proton substitution means the old mock layer is bypassed at
build time, so the only mockable point is the bytes layer at `runOidb`.
- 2 new parity tests pinning `OidbBase<T>` ↔ legacy
`makeOidbBaseSchema(InnerSchema)` byte equivalence.
Verification:
- @snowluma/proton: 95/95 tests pass, tsc --noEmit clean
- @snowluma/core: 605/605 tests pass (network-manager.test.ts
fails to load due to a missing darwin-arm64 native binary in this
environment — pre-existing), tsc --noEmit clean
Phase 2 of the OIDB migration: one-to-one mirror of every schema in
bridge/proto/oidb-action.ts as a proton interface. Purely additive —
the legacy `*Schema` constants stay in place; no call sites are
switched yet.
Translation is mechanical:
- export const XxxSchema = { ... } satisfies ProtoSchema;
→ export interface Xxx { ... }
- { field: N, type: 'uint32' as const } → pb<N, uint_32>
- { field: N, type: 'repeated_message',
schema: YSchema } → pb_repeated<N, Y>
- … (etc, for every primitive + message + repeated_*)
All section headers (`// --- 0x1253_1: Mute group member ---`) and
inline NTQQ-specific comments (the FE1_2 field-2 note, the NTV2
default-value note, the Lagrange-observed annotations on
GroupAvatarExtra, etc.) preserved verbatim.
Verification:
- 183 interfaces emitted, exact match to the legacy schema count
- tsc --noEmit clean
- 604/604 core test suite passes (no behaviour change — additive
only)
Phase 3 next: refactor runOidb to use protobuf_encode<OidbBase<TReq>>
and migrate the 67 runOidb call sites across 10 files + pipeline.ts.
Phase 1 of the OIDB migration: stages the proton-side type definitions
and pins their wire equivalence to the legacy makeOidbBaseSchema()
runtime factory. No call sites are switched yet — that lands in
phase 2 along with the proton/oidb-action.ts schema mirror and the
runOidb refactor.
The legacy bridge/proto/oidb.ts exports a `makeOidbBaseSchema(body)`
factory function that synthesizes the OidbSvcTrpcTcpBase envelope
ProtoSchema at runtime. Proton is compile-time, so the natural form
is the generic interface
OidbBase<T> { command, subCommand, errorCode, body: T, errorMsg,
properties, reserved }
which the plugin monomorphizes per-instantiation. This is exactly the
"generic template with generic-instantiated field" usage that this
package's earlier edge-case fixes#2 and #3 were designed to support,
and the new parity test pins that they actually work on the real
shape (a fully populated OidbSvcTrpcTcp0xFE5_2Response with nested
groupOwner/customInfo).
Also added:
- OidbProperty (for the envelope.properties repeated field)
- OidbBaseMeta — envelope-only view for fire-and-check OIDB calls
that just need to peek at errorCode without decoding the body
- All 8 concrete schemas from oidb.ts (FriendList, GroupList,
GroupMemberList, GroupRequest families)
Verification:
- 2 new parity tests
* OidbBase<OidbSvcTrpcTcp0xFE5_2Response> ↔ makeOidbBaseSchema
byte equivalence
* round-trip encode → decode preserves nested body
- 602+2 = 604 core tests pass (network-manager file still env-fails
on missing native binary)
- tsc --noEmit clean
Mirrors all 35 schemas in bridge/proto/highway.ts as proton interface
forms and switches the two non-OIDB-wrapped consumers
(highway/highway-client.ts and actions/group-file.ts) over to the new
compile-time API.
Migrated schemas (proton/highway.ts):
DataHighwayHead, SegHead, LoginSigHead, ReqDataHighwayHead,
RespDataHighwayHead, HighwayDomain, HighwayIPv4, HighwayNetwork,
HighwayHash, HighwayMsgInfoBody, NTV2RichMediaHighwayExt,
FileUploadUrl, FileUploadHost, FileUploadHostConfig,
FileUploadNameInfo, FileUploadClientInfo, FileUploadFileEntry,
FileUploadBusiInfo, FileUploadEntry, FileUploadExt,
EncodableMediaExtBizInfo, EncodableMediaMsgInfo, HttpConn,
HttpConn0x6FF501Request, ServerAddr, ServerInfo, HttpConnResponse,
HttpConn0x6FF501Response, NTV2FileType, NTV2FileInfo,
NTV2UploadInfo, NTV2ExtBizInfo, NTV2UploadReq, NTV2C2CUserInfo,
NTV2GroupInfo, NTV2UploadSceneInfo, NTV2CommonHead, NTV2ClientMeta,
NTV2UploadReqHead, NTV2UploadRichMediaReq, NTV2IPv4,
NTV2SubFileInfoResp, NTV2UploadRespMsgInfo, NTV2UploadRespBody,
NTV2UploadRespHead, NTV2UploadRichMediaResp
Consumer switches:
- highway/highway-client.ts: protobuf_encode/decode for HttpConn
session fetch, ReqDataHighwayHead frames, NTV2RichMediaHighwayExt
extend bytes, RespDataHighwayHead per-chunk responses
- actions/group-file.ts: protobuf_encode<FileUploadExt> for both
group + private file upload ext bytes
NOT migrated (depends on the OIDB factory pattern):
- highway/pipeline.ts — uses makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)
to wrap the NTV2 upload in an OIDB envelope at runtime. Waits for
the oidb.ts migration to land a generic OidbBase<T> form.
Verification:
- 5 new parity tests for highway schemas (HttpConn0x6FF501 req+resp
with the high-numbered 0x501 tag, ReqDataHighwayHead with multiple
nested messages, NTV2RichMediaHighwayExt with repeated_bytes,
FileUploadExt with the 100/200/400/600/700 high-numbered tags)
- 602/602 core test suite passes — the existing image / ptt / video
upload tests implicitly validated wire format equivalence
- tsc --noEmit clean
Mirrors all 11 schemas in bridge/proto/action.ts as proton interface
forms and switches the two consumers (element-builder.ts and the
send-message paths in bridge.ts) over to the new compile-time API.
Migrated schemas (proton/action.ts):
RoutingC2C, RoutingGroup, RoutingHead, SendContentHead,
MessageControl, SendRichText, SendMessageBody, SendMessageRequest,
SendMessageResponse, MentionExtraSend, MarkdownData
Consumer switches:
- element-builder.ts: protobuf_encode<MentionExtraSend> for @ mention
pbReserve payload; protobuf_encode<MarkdownData> for markdown elem
- bridge.ts: protobuf_encode<SendMessageRequest> +
protobuf_decode<SendMessageResponse> for both sendGroupMessage and
sendPrivateMessage
The `ProtoElem` type alias in element-builder.ts (Partial<ProtoDecoded<typeof
ElemSchema>>) stays as-is — it's a pure TS type used internally for
building elem objects and doesn't affect runtime behaviour. Replacing
it with the proton Elem type is a larger refactor that can come later
when there's a reason to.
Verification:
- 6 new parity tests for action schemas (RoutingHead c2c+grp,
SendMessageRequest full shape, SendMessageResponse, MentionExtraSend,
MarkdownData)
- 591/591 core test suite passes — the existing send-message and
element-builder tests implicitly validated wire format equivalence
- tsc --noEmit clean
Completes the proton migration started in the previous PoC commit. All
schemas needed by actions/forward.ts are now mirrored as proton interface
forms, the legacy ProtoSchema constants stay in place for back-compat,
and forward.ts has been switched over to the new compile-time codecs.
Migrated schemas:
- element.ts (35 schemas: TextElem, FaceElem, OnlineImage, NotOnlineImage,
TransElem, MarketFace, CustomFace, RichMsg, GroupFileElem, ExtraInfo,
VideoFile, SrcMsg, LightAppElem, CommonElem, GeneralFlags, Elem,
MentionExtra, QFaceExtra, QSmallFaceExtra, FileType, FileInfo,
IndexNode, PicUrlExtInfo, PictureInfo, PicExtData, PicExtBizInfo,
VideoExtBizInfo, PttExtBizInfo, ExtBizInfo, C2cSource, TroopSource,
HashSum, MsgInfoBody, MsgInfo, GroupFileInfo, GroupFileExtraInner,
GroupFileExtra, Preserve, …)
- message.ts (PushMsg, PushMsgBody, ResponseHead, ContentHead, Ptt,
NotOnlineFile, RichText, MessageBody, FileExtra, …)
- longmsg.ts — the three remaining schemas (LongMsgContent / LongMsgAction
/ LongMsgResult) that depend on PushMsgBody
forward.ts now calls:
protobuf_encode<LongMsgResult>(...) // upload payload
protobuf_encode<SendLongMsgReq>(...)
protobuf_decode<SendLongMsgResp>(...)
protobuf_encode<RecvLongMsgReq>(...)
protobuf_decode<RecvLongMsgResp>(...)
protobuf_decode<LongMsgResult>(...) // download payload
protobuf_encode<PushMsg>(...) // re-wrap for parseMsgPush
The unused legacy schema constants are intentionally left in place — they
still back the existing forward.test.ts mock encoder and any other consumer
that hasn't been migrated yet. They will be removed in a follow-up once
every consumer is on the new API.
Verification:
- 18/18 parity tests pass (encode + decode equivalence for every
representative shape across element / message / longmsg)
- 585/585 core test suite passes (network-manager.test.ts fails to load
due to a missing native binary in this environment — pre-existing)
- tsc --noEmit clean
Migrates a self-contained subset of bridge/proto/longmsg.ts to the new
@snowluma/proton compile-time DSL form and verifies wire-format parity
against the legacy runtime ProtoSchema encoder. End-to-end proof that
the toolchain works in core's vitest pipeline.
What's covered:
- LongMsgUid / LongMsgSettings / SendLongMsgInfo / SendLongMsgReq /
SendLongMsgResp / SendLongMsgRespResult / RecvLongMsgInfo /
RecvLongMsgReq / RecvLongMsgResp / RecvLongMsgRespResult
- The three schemas that pull in PushMsgBody (LongMsgContent /
LongMsgAction / LongMsgResult) stay on the legacy API for now, since
migrating them requires also migrating message.ts and element.ts.
Toolchain changes:
- @snowluma/proton gets a tsup build step. The ./vite subpath now
points at the built dist/index.js so it is loadable as plain Node
ESM from vite.config.ts / vitest.config.ts (the source-only .ts
layout can't be consumed from outside the Vite transform pipeline).
The . (runtime) subpath stays at TS source — it's only ever
imported from user code, which IS Vite-transformed.
- prepare script ensures dist/ exists after pnpm install.
- @snowluma/core depends on @snowluma/proton (workspace:*) and adds
protobufVitePlugin() to its vitest config so test files get
transformed.
Documented divergence:
proton follows proto3 semantics: fields equal to their default value
(0 / false / "" / empty bytes) are NOT emitted on the wire. The legacy
runtime encoder always emits them. Both forms are round-trippable
through a conforming proto3 reader. The parity test pins this
behaviour explicitly.
8/8 parity tests pass.
Follow-up to c62f517. Dropping the obsolete field 2 from the body was
necessary but insufficient: newer QQ NT still rejects the request with
[oidb] one of uid/openid is invaild
The actual trigger is the OIDB envelope-level `reserved` flag.
Lagrange.Core's FetchStrangerByUin sets `Reserved = 1`, our call sent
`Reserved = 0`. The server uses that bit to pick its validation path:
- reserved=1 → UIN-form variant: server translates body.uin to the
internal uid itself
- reserved=0 → UID-form variant: server expects a uid/openid string
in the body and rejects when it can't find one
Our request body has only `uin` + `keys`, so the UID-form path was
always going to fail. Setting `isUid: true` (which is the existing
flag that flips envelope `reserved` to 1; the parameter name is
historical and misleading) puts the call onto the correct branch.
Applied to both call sites that target OidbSvcTrpcTcp.0xfe1_2:
- fetchUserProfile (bridge-contacts.ts) — fixes the
"failed to load self profile for UIN N" warmup warning.
- getStrangerStatus (actions/extras.ts) — same OIDB cmd; would
have failed identically if exercised against newer QQ NT.
Also updated the `isUid` JSDoc on OidbCall to spell out the actual
semantic (UIN-form variant marker, not "this call uses UID-keyed
data") since the name will keep tripping people otherwise.
Follow-up to a07521d. The reporter's correction (895 friends / 221
groups account) was that turning off only field5003 + all of config2
wasn't enough — field5002 has to go too, otherwise QQ NT still emits
a response large enough to blow the named-pipe write buffer and
fetchGroupList dies with EPIPE.
The response decoder (OidbSvcTrpcTcp0xFE5_2GroupInfoSchema) only knows
about tag numbers 1/2/3/4/5/18/19/30, and fetchGroupList itself only
reads groupName / memberCount / memberMax / customInfo.remark off the
result. Tag 5002 isn't in the response schema and isn't consulted by
any caller, so silencing it on the request side is purely a payload
reduction with no observable behavior change.
QQ has been pushing Event0x2DC subType=16 every time someone tapped
an emoji on a message in a group, and we were dropping it silently
(only surfacing the PR5 [MsgPush.Unknown] debug line that prompted
this issue). Now we decode it into a first-class event and fan it
out to OneBot clients.
Wire details (cribbed from NapCat's GroupReactNotify transformer):
- body.msgContent has a 7-byte magic prefix; strip before decoding.
- GroupReactNotify { groupUin(4), field13(13), groupReactionData(44) }.
- field13 is a discriminator — same subType is reused for other
notify variants, only 35 means "emoji react". Other values now
fall through to MsgPush.Unknown so we still spot future variants.
- Inside groupReactionData (3-level nested data wrapper, ugh):
code emoji id (system face = numeric str, market = code)
count usually 1
operatorUid needs identity.findUinByUid to resolve to uin
type 1 = add, else = remove
target.seq msg_seq of the reacted-to message
New event kind `group_msg_emoji_like` flows through the standard
pipeline: bridge event → event-bus → converter → OneBot wire.
Converter emits the gocqhttp / NapCat extension shape:
notice_type: group_msg_emoji_like
sub_type: add | remove
group_id, user_id, operator_id, message_id, message_seq,
likes: [{ emoji_id, count }]
message_id is reconstructed via hashMessageIdInt32(msgSeq, groupId,
GROUP_MESSAGE_EVENT) so it matches whatever id the bot originally
handed out for the message being reacted to, even if it's no longer
in the message store.
formatEvent also gets a case so the [Event] log reads cleanly:
表情回应 [群名(123)] | [Alice(99999)] +[76] msgSeq=4242
7 new tests cover the happy path, type=2 (remove), field13!=35
(routed to MsgPush.Unknown), prefix-too-short edge, converter
shape both for add and remove, and the formatEvent string.
closes#42
On accounts with ~200+ groups, fetchGroupList was asking QQ to fill
in every config flag (all 32 bools in config1 plus all 8 in config2)
even though our response decoder reads only groupName / memberMax /
memberCount / customInfo.remark / a handful of named info fields.
QQ NT obligingly packs every requested field into the response. At
group counts >= ~200 the payload is large enough to blow the
named-pipe write buffer on the QQ side; SnowLuma reads EPIPE and
the entire session dies during warmup:
WARN [Hook] pipe error: PID=23928 err=read EPIPE
INFO [OneBot] session closed: UIN=...
WARN [OneBot] failed to load groups for UIN ...: qq_hook client closed
Issue #42 reporter (airline233) bisected the breakage to two
clusters of unused bool flags:
- config1.field5003 (a 5xxx-range expansive descriptor)
- the whole of config2 (per-group aux info we don't decode)
This commit applies exactly their verified safe combination and
inlines a comment so nobody flips them back on without context.
The decoded response shape (groupName, memberCount, memberMax,
remark, etc.) is unchanged.
QQ now rejects fetchUserProfile() with:
[oidb] one of uid/openid is invaild
The cause: SnowLuma's request schema declared field 2 as a
zero-valued uint32 (`field2: 0`) and our encoder doesn't skip 0
varints. Newer QQ NT versions reinterpret field 2 of OIDB 0xFE1_2 as
`uid: string` / `openid: string`, so a varint 0 there decodes as an
empty/invalid uid → server bounces the whole request.
NapCat's equivalent transformer (Oidb.0XFE1_2.ts) emits only `uin`
(field 1) and `key[]` (field 3) — nothing in field 2. Match that
shape exactly.
Effect: warmUpBridgeState's "self info via profile" fallback path
now succeeds for accounts that QQ omits from the friend list, so
the WebUI shows their nickname instead of leaving it blank.
The previous commit (257686e) widened printEvent's signature to take
IdentityService but only updated the synchronous call at line 97.
The async post-refresh dispatch path (line 127, called when a group
member join arrives without a resolved uin) still used the old
two-arg form, which CI caught as TS2554. Local tsc somehow didn't
flag it on the editing machine.
Both sites now pass this.deps.identity so the readable rendering
applies to both prompt and post-refresh dispatch paths.
Notice events (recall / join / leave / poke / admin / mute / essence
/ request / invite) and the received-message log now resolve group
IDs and user IDs against the Identity cache so output reads as
human names instead of raw QQ numbers.
Before:
[Event] 群撤回 12345 | 67890 被 99999 撤回
[Event] 群 12345 | NickName(67890): ID:42 你好 [图片]
After:
[Event] 群撤回 [SnowLuma群(12345)] | [Alice(67890)] 被 [Bob(99999)] 撤回
[Event] 群 [SnowLuma群(12345)] | [Alice(67890)]: ID:42 你好 [图片]
Reply segments now expand one level via messageStore.findEvent —
"[回复:42]" becomes "[回复 [Alice(100)]: 早安]" when the original
is still in the message store, falling back to the bare id when it
isn't.
New file utils/event-format.ts owns:
- formatGroup / formatUser identity-aware name resolution
- formatMessageSegments shared element preview (replaces
the inline switch in
logReceivedMessage)
- formatReply one-level reply chain expansion
- formatEvent notice-class event renderer
Every formatter wraps its lookup in try/catch and degrades to the
prior numeric form on cache miss / throw, so log formatting can
never crash the calling path. The QQ numeric ID is preserved
alongside the name so third-party parsers that scrape uids still
find them.
26 unit tests cover cache hit / miss, malformed input, throw
recovery, and per-event-kind rendering shapes.
Two related cleanups so unexpected failures stop being invisible:
void-promise wrappers
Every `void this.something()` fire-and-forget call now has a
.catch(err => log.warn(...)) attached. Affected sites:
- packet-pipeline.ts: dispatchAfterIdentityRefresh
- instance.ts: openAll / applyConfigDiff / closeAll / emitEvent
- http-post-adapter.ts: postEvent
- ws-client-adapter.ts: handleApiMessage
Most of the network-manager fan-outs already isolate per-adapter
errors, but the outer catches guard against future refactors and
surface stack traces immediately rather than as unhandled rejection
warnings.
silent-catch sweep (Bridge.Web)
bridge/web/group-honor.ts, group-essence.ts, group-notice.ts had
`} catch (e) { return undefined; }` patterns that turned every QQ
Web API failure into a silent empty response. Now log.warn with
the full stack first, then return the same fallback so behavior is
unchanged. The commented-out `// console.error(e)` debris is gone.
Plus one console → logger conversion in message-parser.ts (music
sign fallback path).
Highway upload path now emits per-type entry + shared pipeline ops:
DEBUG [Highway.Image] uploading 234567 bytes md5=abc12345... → group 12345
DEBUG [Highway] image OIDB requires bytes, PUT 234567 bytes (sub=top)
DEBUG [Highway] image PUT done in 1234ms
-- or --
DEBUG [Highway] image fast-upload hit (server already had bytes)
The three pipeline-side lines come from runNtv2Upload() and are
shared across image/video/ptt; the per-type entry log lives in each
*-upload.ts wrapper so the scope identifies the media kind. md5 is
truncated to its first 8 hex chars for line width; PUT latency is
reported in ms.
MsgPush silent dispatch defaults are now visible at debug:
DEBUG [MsgPush.Unknown] no decoder for PkgType=999 subType=0
DEBUG [MsgPush.Unknown] Event0x2DC unknown subType=42
DEBUG [MsgPush.Unknown] Event0x210 unknown subType=42
Captures protocol drift (new NT QQ subtypes) and "we forgot to
register this PkgType" oversights, neither of which used to leave
any trace in the log.
All new lines are debug-level so console output (default info) stays
unchanged; file transport sees them for post-mortem.
Switches the per-account classes from module-level loggers to
per-instance ones derived via Logger.child({ uin }) so their log
lines land in both the shared file and the account's logs/<uin>/
sub-file, and the [UIN] slot appears in console output:
- IdentityService (Identity scope)
- IncomingPacketPipeline (Bridge + Event scopes)
- OneBotInstance (Event scope)
- HttpServerAdapter (OneBot.HTTP)
- HttpPostAdapter (OneBot.POST)
- WsClientAdapter (OneBot.WS-Client)
- WsServerAdapter (OneBot.WS-Server)
The standalone printEvent() in packet-pipeline now takes a Logger
argument so it routes through this.eventLog instead of a captured
module-level reference. Behavior unchanged otherwise; bridge.ts,
bridge/manager.ts and process-level scopes (App / WebUI / Hook /
OneBot.Config) keep their module-level loggers since they aren't
bound to a single account.
For a private send_private_forward_msg, the inner image/record/video
needs an OIDB upload scene — but uploadForwardNodes never received the
recipient, so the SendContext fell back to {bridge} only and the
element builder threw "private image target uid is missing".
Plumb userId through uploadForwardNodes → buildForwardPushBody and,
when the nodes contain media, resolve it to a uid via
bridge.resolveUserUid() once up-front. Group forwards are unchanged
(they already passed groupId). Mirrors NapCat's design where the
destination peer is threaded all the way down to createSendElements.
QQ's short-video element protocol hard-limits a single video at 100 MB
(NapCat enforces the same cap in highwayContext.uploadVideo with the
same threshold and tells operators to switch to file upload). Mirror
that hint so OneBot bot authors who hit the cap immediately see the
correct alternative — `upload_group_file` / `upload_private_file`,
which ride the FtnUpload path and go up to 4 GiB — instead of having
to read the docs to figure out why a send_msg with a 200 MB video
silently 'won't work'.
Follow-up on the previous highway commit, addressing two real holes the
Copilot review caught:
* loadBinarySource HTTP path was buffering the entire response via
`await resp.arrayBuffer()` BEFORE length-checking. A server that omits
or understates `Content-Length` (chunked transfer, malicious upstream,
proxy stripping headers) bypassed the cap entirely. Switch to a
streaming reader: accumulate chunks, abort + reject as soon as the
running total exceeds `maxBytes`. The Content-Length precheck still
short-circuits the obvious case before we read a byte.
* video-upload `stageVideoSource` has its own local-path fast-path that
never went through `loadBinarySource`, so the 100 MB MAX_VIDEO_SIZE
guard ran AFTER `fs.readFileSync` had already allocated the entire
file. A 10 GiB local-file pointer would OOM the bot before the check
fired. Add an `fs.statSync` precheck on the local branch, and pass
`MAX_VIDEO_SIZE` explicitly when the source falls through to
`loadBinarySource` so the HTTP / base64 cap matches the on-disk one.
Update the DEFAULT_MAX_BINARY_SIZE comment to stop claiming video paths
are bounded by it — they're bounded by the smaller MAX_VIDEO_SIZE,
enforced inside video-upload.
Adds five regression tests:
- chunked streamed download (no Content-Length) over cap → throws
- Content-Length over cap → throws before reading body
- streamed download inside cap → returns full bytes
- local file over cap (statSync precheck) → throws
- base64 over cap → throws
* highway/utils detectImageFormat: JPEG SOF marker check now excludes
0xC4 (DHT), 0xC8 (JPG), and 0xCC (DAC). The old `(marker & 0xFC) ===
0xC0` matched DHT et al. and then read Huffman table bytes as image
dimensions, producing junk width/height for many real JPEGs.
* loadBinarySource takes an optional maxBytes; defaults to 1 GiB to
defend against an authenticated client triggering a multi-GB load
into memory. Group/private file uploads pass FILE_UPLOAD_MAX_BYTES
(4 GiB) because QQ's file protocol legitimately supports that size.
HTTP fetches also pick up a 60s timeout and a Content-Length precheck.
* highway-client.tcpConnect detaches its error/timeout listeners after
a successful connect so subsequent upload IO errors don't reject an
already-resolved promise. readHttpResponseBody uses local listener
refs + a central detach(), eliminating MaxListenersExceededWarning
during multi-chunk uploads.
* hook/qq-hook-client.nextRequestId now wraps inside uint32 explicitly
and skips id 0 / in-flight ids. The previous `nextRequestId++ >>> 0`
loses precision past Number.MAX_SAFE_INTEGER (postfix increment
evaluates before the shift) and could collide live request ids on
very long-running processes.
* identity-service.rememberUidUin removes stale partner entries before
inserting a new (uid, uin) pair. The old code left orphan uidByUin /
uinByUid entries after a uid/uin re-bind, so the two maps could
disagree.
Commit 29f28d6 changed c2c video `compatQmsgSceneType` from 2 to 1
as a "symmetric asymmetry" cleanup, matching the image/ptt convention
where the field tracks the upload's sceneType (c2c=1, group=2). For
video this is wrong.
Image and ptt have *different* legacy compat elements per scene
(notOnlineImage vs customFace; ptt c2c vs group), so the server needs
to know which scene shape to emit. The legacy `videoFile` element
(packet element type 19) has no scene split — fromChatType /
toChatType live inside the element itself — so the QQ NT server
emits a single group-shaped compat payload regardless. NapCat
hardcodes `compatQMsgSceneType: 2` for *both* UploadGroupVideo and
UploadPrivateVideo for exactly this reason.
Setting it to 1 on c2c made the server emit a c2c-scene shaped
compat blob that older QQ clients failed to resolve, showing the
message as "视频已过期" on those receivers. Newer clients only read
the commonElem(48, 11) and displayed fine — which is why only "some
devices" saw the breakage.
Keep `commonElem.businessType = isGroup ? 21 : 11` untouched — that
piece of 29f28d6 is still correct and is what fixed PbSendMsg
result=79.
- P0-1: restore customExt field in SetStatusReqSchema
- P0-2: remove duplicate setGroupAvatar implementation
- P1-3: add attach_info pagination support for get_group_album_media_list
- P1-5: clean up commented console.log statements
- P1-6: remove raw field from GroupAlbumMediaResult
OneBot clients commonly send [CQ:at,qq=12345] without a name field; we
were piping `@12345` into the text element so QQ rendered the bare uin
instead of the member's card/nickname (napcat resolves via getGroupMember
before encoding). Move the fallback into the element builder so it
consults the IdentityService roster and only falls back to the uin when
the roster has nothing.
Private-chat video and voice sends were getting bounced by the QQ NT
server with `PbSendMsg result=79`. Highway upload logs said success,
but the final SendMsg the bot constructed used the group-scene tag
inside the outgoing commonElem, and the c2c routing path doesn't
recognise it.
The convention — verified against the receive-side decoder at
msg-push/rich-body-decoder.ts:261-330 which explicitly branches on the
pairs — is:
image : commonElem.businessType c2c=10 group=20
video : commonElem.businessType c2c=11 group=21
record : commonElem.businessType c2c=12 group=22
makeImageElem already honoured the split (`isGroup ? 20 : 10`).
makeVideoElem and makePttElem hardcoded the group value for both
scenes. Fix them to follow the same pattern.
Also fix a symmetric asymmetry inside the highway upload itself:
uploadVideoMsgInfo hardcoded `compatQmsgSceneType: 2` while
uploadImageMsgInfo and uploadPttMsgInfo both use `isGroup ? 2 : 1`.
Same root cause — group value leaking into the c2c path.
Regression test (tests/element-builder.test.ts) pins all six
businessType pairs by mocking the highway upload functions and
inspecting the proto element the builder returns; would have caught
the bug had it existed at the time element-builder.ts was written.
Port the Lagrange.Core protocol path for group avatar upload —
napcat's NTQQ GroupService.setHeader has no oidb wrapper, but
Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs
spells out the wire shape: same highway HTTP endpoint as personal
avatar, but with cmdId=3000 and a GroupAvatarExtra proto carried as
the `extend` blob (type=101, groupUin, field3={field1=1}, field5=3,
field6=1 — all four are protocol-prescribed constants).
Adds:
- GroupAvatarExtraSchema in proto/oidb-action.ts
- bridge.setGroupAvatar(groupId, source) wrapping the highway upload
- BridgeInterface.setGroupAvatar
- OneBot set_group_portrait action (was a stub returning
'not yet implemented'; accepts the same file-source variants as
set_qq_avatar)
5 new tests: 3 bridge-action (cmdId, extra-blob round-trip, empty-file
guard) + 2 OneBot (forwarding, param validation) — also tightens the
existing setAvatar test to assert the extend blob stays empty.
DIY online status reuses the existing StatusService.SetStatus wire
call. napcat hardcodes status=10 / extStatus=2000 and threads the
faceId / wording / faceType through a customExt sub-message (field 4
of SetStatus, per napcat packet/transformer/proto/action/action.ts).
Implementation:
- Extend SetStatusReqSchema with optional customExt field. Encoder
skips undefined fields so the existing set_online_status path stays
byte-identical on the wire (verified by a new round-trip test).
- New bridge.setDiyOnlineStatus(faceId, wording, faceType) wraps the
same dispatchSetStatus helper as setOnlineStatus.
- OneBot action set_diy_online_status accepts napcat-style payloads
(face_id / face_type can be string or number; wording defaults to '').
9 new tests across actions/profile and onebot/extended-actions.
Wires 16 OneBot actions that napcat exposes but SnowLuma previously
either lacked or stubbed:
Tier 1 (pure glue over existing Bridge capabilities)
- send_packet / .send_packet: real impl over Bridge.sendRawPacket
- bot_exit, nc_get_packet_status, nc_get_rkey
- get_group_ignored_notifies / get_group_ignore_add_request: project
fetchGroupRequests(filtered=true) into napcat shapes (was empty stub)
- delete_group_folder alias for delete_group_file_folder
Tier 2 (new oidb proto + Bridge method)
- set_/complete_/cancel_group_todo (oidb 0xF90_1/2/3)
- nc_get_user_status (oidb 0xFE1_2 with napcat's status decode)
- get_ai_characters / get_ai_record / send_group_ai_record (oidb
0x929D / 0x929B; AI voice reuses the existing fetchGroupPttUrlByNode)
BridgeInterface now exposes sendRawPacket as the deliberate escape
hatch for send_packet — every other surface method already wraps it.
46 new tests: 13 bridge-action (mocked runOidb dispatch checks) + 33
OneBot-action (ApiHandler.handle end-to-end).