Commit Graph
154 Commits
Author SHA1 Message Date
DrSmoothl 1db287d8cc fix(c2c-file): rewrite sendC2cFileMessage wire shape per Lagrange.Core V2
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.
2026-05-19 23:45:40 +08:00
DrSmoothl f65fe959bb fix(send-private): split c2c file segments out to sendC2cFileMessage (was shipping "[空消息]")
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.
2026-05-19 23:36:12 +08:00
DrSmoothl cec38b4c1b fix(forward): piggyback every nested level onto the outermost long-msg upload (NapCat model)
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.
2026-05-19 23:29:59 +08:00
DrSmoothl 0b8dc1f7af fix(video): populate NTV2 fileInfo.time with the real duration (receiver was rendering 00:00)
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.
2026-05-19 22:20:38 +08:00
DrSmoothl 8f839f4f30 fix(group-file): correct GroupFileExtra wire shape — server was rejecting with result=79
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
2026-05-19 21:51:35 +08:00
DrSmoothl 04a905460b fix(file-upload): read upload host from rtpMediaPlatformUploadAddress (NT 2026 rollout)
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
2026-05-19 21:45:40 +08:00
DrSmoothl 3c65df668c fix(msg-push): silently acknowledge Event0x210 subType=380 (unmapped client state)
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.
2026-05-19 21:25:41 +08:00
DrSmoothl 87ac6ffedb fix(file-upload): fall back through parallel host fields when uploadIp is empty
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.
2026-05-19 21:18:08 +08:00
DrSmoothl 898898a507 feat(msg-push): handle three friend-related events we used to drop on the floor
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`).
2026-05-19 14:51:48 +08:00
DrSmoothl 604dbc3f64 fix(msg-push): Event0x210 subType=38 is the troop-shortcut-bar push, not friend-related
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.
2026-05-19 14:04:43 +08:00
DrSmoothl ff5fc651d0 fix(tests): declare full vi.fn arg signatures so CI typecheck doesn't trip on tuple length
CI's `tsc --noEmit` was rejecting `forward-nested.test.ts` because the
`vi.fn(async () => 'RES')` mocks for `bridge.uploadForwardNodes` only
inferred zero or one arg from the lambda — so
`uploadForwardNodes.mock.calls[0]` came out typed as `[]` or
`[nodes: any[]]`, and indexing `[1]` / `[2]` for groupId / userId
hit `Tuple type ... has no element at index 'N'`.

Local `tsc --noEmit` happened to be looser about this in my version,
which is why the bad assertions slipped past `e637647`.

Declare the full 3-arg signature on every `uploadForwardNodes` mock
— `(_nodes, _groupId?, _userId?)` — matching the real
`Bridge.uploadForwardNodes` contract. `mock.calls[i]` now types as a
3-tuple, the index accesses check out, and the assertions stay
unchanged. No production code touched, no test behaviour change.

626/626 still passing, typecheck clean.
2026-05-19 13:00:41 +08:00
DrSmoothl c758eb6569 fix(onebot): recursively parse nested forward chains (node-inside-node)
A custom forward node's `content` field can itself be a list of
`{type:'node'}` entries — that's the nested-forward case where one
forward bubble contains another. `parseForwardNodes` used to pass
the whole `content` straight into `parseMessage`, which routed
each inner `{type:'node'}` through `message-parser.ts:217 case
'node':` and turned them into opaque
`MessageElement{type:'node', resId: JSON.stringify(content)}`
placeholders. `element-builder.buildSendElems` then dropped those
at its default branch — so the outer forward shipped with either
zero elements (pure-nested → server rejects with "message is
empty") or text-only elements (mixed content → silently truncated
chat bubble). User-facing symptom: "嵌套转发解析后发不出去".

Add depth-aware recursion to `parseForwardNodes`, modelled on
NapCat's `SendMsg.uploadForwardedNodesPacket` (3-level cap):

  - When a node's `content` is *all* `{type:'node'}` entries,
    recurse: parse the inner chain into ForwardNodePayload[],
    upload it via `bridge.uploadForwardNodes` to mint an
    inner res_id, then embed a `{type:'forward', resId}` element
    in the outer node. The receive-side rendering pipeline already
    builds the ARK preview card for that element shape, so the
    QQ client renders a tap-to-expand nested bubble.
  - Mixed content (text + node siblings) deliberately stays on the
    flat path — the meaning is ambiguous, and forcing a recursion
    would silently drop the non-node siblings.
  - Hard cap at depth 3; deeper attempts throw "depth exceeds 3".
    Matches NapCat and prevents one slow inner upload from
    aborting an unreasonably deep tree.

Threading: each forward send entry point passes its destination
into the parser (`{groupId}` from group-send, `{userId}` from
private-send) so the inner forward uploads against the same
res_id namespace.

Test coverage in `tests/onebot/forward-nested.test.ts`:
  - group: inner uploads first, outer wraps inner res_id in a
    forward element, both calls happen in order
  - private: c2c path threads userId (not groupId) into the
    inner uploadForwardNodes
  - depth cap rejects 4-level nesting with /depth/
  - flat (non-nested) content still uploads exactly once
  - mixed content stays on the legacy parseMessage path

core: 626/626 tests pass (+5), typecheck clean, prod build clean.
2026-05-19 12:53:24 +08:00
DrSmoothl 10154cfbff fix(onebot): parse {type:'file', file_id:'…'} segments instead of dropping them
The companion to `e637647`. That commit fixed
`upload_group_file` / `upload_private_file` to publish the file as
a chat message atomically (matching napcat). This one fixes the
OTHER half of the same bug: when a bot framework does

  send_msg([{type:'file', file_id:'<previously uploaded>'}])

— attaching an already-uploaded file as a message segment — the
parser used to fall through to its default warn-and-drop branch
(`message-parser.ts:340`). The dropped segment then either:
  - became "message is empty" if it was the only segment, or
  - silently disappeared if it shared the payload with text,
producing a chat bubble missing the file.

Adds a `case 'file':` that maps the OneBot segment shape to the
existing `MessageElement{type:'file', fileId, fileName, fileSize,
md5Hex, sha1Hex}` that `element-builder` already knows how to
emit as `TransElem(24)`. Accepts the common alias spellings
(`file_id`/`fileId`, `name`/`filename`/`fileName`,
`size`/`fileSize`, `md5`/`md5Hex`, `sha1`/`sha1Hex`).

Deliberately rejects `{file: '/path'}` form — kicking off an
upload from inside the synchronous parser would either swallow
errors or restructure the whole parseMessage signature, neither
worth it. Callers wanting upload-and-send should keep using
`upload_group_file` / `upload_private_file`, which now does both
atomically.

core: 621/621 tests pass (+3), typecheck clean.
2026-05-19 12:42:47 +08:00
DrSmoothl e637647877 fix(bridge): publish uploaded files as chat messages (the "empty message" bug)
`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.
2026-05-19 12:31:05 +08:00
DrSmoothl 70715763bd fix(core): wire @snowluma/proton vite plugin into the production build
The proton plugin was only in `vitest.config.ts`, so tests and
typecheck passed but the bundled `dist/index.mjs` shipped with the
unsubstituted generic shells — every `protobuf_encode<T>()` /
`protobuf_decode<T>()` call hit the runtime fallback and threw:

  "protobuf_encode<T>() was not transformed by the
   @snowluma/proton Vite plugin. …"

at every msg-push, rkey/friend/group/profile warmup, etc. on the
Win/Linux releases.

Add `protobufVitePlugin()` to the shared `BaseConfigPlugin` so the
transform runs in both dev (`vite build --mode development`) and
prod (`vite build`). Sanity-check on a fresh `vite build` shows the
bundle now contains 481 distinct monomorphized codecs (704 encode +
511 decode call-site replacements), and the only remaining
"was not transformed" string is the dead runtime fallback that no
longer has a caller.
2026-05-19 11:20:47 +08:00
DrSmoothl d821336943 fix(onebot): hot-reload HTTP server accessToken without re-binding
`HttpServerAdapter.startServer` baked `accessToken` into the
`createServer` callback's closure, then relied on
`bindingSignature` including the token to trigger a
`close()`+`open()` round-trip on every change. Two problems:

  1. The three sibling adapters (`ws-server`, `http-post`,
     `ws-client`) all read `this.config.accessToken` inline at the
     point of use, so the HTTP-server's closure-capture pattern was
     the odd one out.
  2. `server.close()` is asynchronous; the immediately-following
     `server.listen()` on the same port can race with the OS
     releasing it. When it loses, the new listener fails with
     EADDRINUSE (logged via `server.on('error', …)` but not bubbled
     up), the old server is gone, and the operator's `reload` looks
     successful while the endpoint is actually broken — which lines
     up with the "token didn't hot-reload" reports.

Drop the closure capture: `handleRequest` reads
`this.config.path` and `this.config.accessToken` fresh per request
(`reload()` already replaces `this.config` in place via
`structuredClone(next)`). Remove `accessToken` from
`bindingSignature` so a token change no longer triggers a port
re-bind. `host`/`port`/`path` stay in the signature because Node's
`Server.listen()` binds the socket on those.

Four hot-reload tests pin the new contract: token swap, clearing
to empty, setting from empty, and "token-only change returns
`NetworkReloadType.Normal`" (no Reopened/Closed). All four hit a
single OS-assigned port and verify the port is unchanged after
reload — a re-bind would either land on a different port or fail.

core: 613/613 tests pass (+4), typecheck clean.
2026-05-19 11:16:54 +08:00
DrSmoothl 76b87f6b27 feat(proton): migrate group-album actions (PR #31) to proton codec
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.
2026-05-19 08:28:11 +08:00
DrSmoothl 5802812392 feat(proton): finish OIDB migration — runOidb on protobuf_encode<OidbBase<T>>
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
2026-05-19 08:19:14 +08:00
DrSmoothl 6f3646e956 feat(proton): add proton/oidb-action.ts (183 schema mirrors)
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.
2026-05-19 08:19:14 +08:00
DrSmoothl c543ce9227 feat(proton): add proton/oidb.ts with generic OidbBase<T> envelope
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
2026-05-19 08:19:14 +08:00
DrSmoothl 7526622917 feat(proton): migrate highway.ts schemas + highway-client + group-file
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
2026-05-19 08:19:14 +08:00
DrSmoothl ccc31a760c feat(proton): migrate action.ts schemas + bridge.ts + element-builder.ts
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
2026-05-19 08:19:14 +08:00
DrSmoothl 9f32dbd60c feat(proton): migrate notify.ts schemas + all 6 msg-push consumers
Mirrors all 27 notify.ts schemas as proton interface forms and switches
the entire msg-push decoder family over to the new compile-time API.

Migrated schemas (proton/notify.ts):
  OperatorField1, OperatorInfo, GroupChange, GroupAdminExtra,
  GroupAdminBody, GroupAdmin, InvitationInner, InvitationInfo,
  GroupInvitation, GroupInvite, GroupJoin, FriendRequestInfo,
  FriendRequest, FriendRecallTipInfo, FriendRecallInfo, FriendRecall,
  GroupMuteState, GroupMuteData, GroupMute, RecallMessage,
  GroupRecallTipInfo, GroupRecall, TemplParam, GeneralGrayTipInfo,
  EssenceMessage, NotifyMessageBody, GroupReactionDataInnerDataTarget,
  GroupReactionDataContent, GroupReactionDataInnerData,
  GroupReactionDataInner, GroupReactionData, GroupReactNotify

Consumer files switched to protobuf_decode<T>():
  - msg-push/helpers.ts (decodeOperatorUid)
  - msg-push/decoders/event-0x2dc.ts (5 call sites: GroupMute,
    GroupRecall, GroupGreyTip, GroupEssence, GroupMsgEmojiLike)
  - msg-push/decoders/event-0x210.ts (3 call sites: FriendRequest,
    FriendRecall, FriendPoke)
  - msg-push/decoders/group-admin.ts
  - msg-push/decoders/group-member-change.ts (join + leave)
  - msg-push/decoders/group-join-request.ts (join request + invitation
    + invite)

The notify.ts FriendRecall interface collides with events.ts's own
FriendRecall event type; the decoder imports it under the local alias
FriendRecallNotify to keep the existing event type intact.

Verification:
  - 6 new parity tests pinning notify wire equivalence
  - 591/591 core test suite passes (the existing decoder tests —
    group-msg-emoji-like, group-admin, etc. — implicitly validated
    wire format equivalence against real captured QQ payloads)
  - tsc --noEmit clean
2026-05-19 08:19:14 +08:00
DrSmoothl b7d8952163 feat(proton): full longmsg + element + message migration; forward.ts on new API
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
2026-05-19 08:19:14 +08:00
DrSmoothl d323318a7e bench(proton): proton vs legacy runtime encoder/decoder
Standalone tsx script benchmarking the codecs generated by
@snowluma/proton against the existing src/protobuf/decode.ts runtime
implementation, using the actual long-message schemas already in the
codebase (the proton interface form + the legacy *Schema constants).

Proton codecs are materialised at bench startup via the public
analyzeSource + generateCode API — exactly what the Vite plugin does at
build time — so there is no chicken-and-egg dependency on a Vite build.

Headline numbers on Node 24 / darwin-arm64:
  - simple 4×uint32 encode: ~8.5× speedup
  - simple 4×uint32 decode: ~35× speedup
  - deeply nested SendLongMsgReq encode: ~9.5×, decode: ~13×
  - 64-byte payload RecvLongMsgResp encode: ~4.3×, decode: ~10×

Run with:
  pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts
2026-05-19 08:19:14 +08:00
DrSmoothl 3d739c255a feat(proton): proof-of-concept migration — longmsg parity test
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.
2026-05-19 08:19:13 +08:00
H3CoF6 0d40a03f28 Merge upstream/dev into feat/onebot 2026-05-19 02:40:14 +08:00
H3CoF6 64530cc287 Implement some actions: comment, send and cancel like, delete media for group album! 2026-05-19 02:37:11 +08:00
墨梓柒 f316073431 Merge pull request #43 from airline233/dev
feat(http-server): support parse content-type of urlencoded
2026-05-18 17:51:41 +08:00
墨梓柒 692a1b7665 Merge pull request #52 from Stlara-F/dev
fix(request-actions): match group add/invite flags by UID and add regression tests
2026-05-18 15:19:15 +08:00
DrSmoothl 941e60dea5 chore(release): v1.8.5 2026-05-18 15:03:45 +08:00
stla b99f5c0bf1 fix(request-actions): match group add/invite flags by UID and add regression tests 2026-05-18 07:03:45 +00:00
DrSmoothl 562fd4f7f9 fix(oidb): set envelope reserved=1 on OIDB 0xFE1_2 (user / stranger)
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.
2026-05-18 14:58:58 +08:00
DrSmoothl 6a7c9a5de1 fix(bridge): also drop config1.field5002 from the OIDB 0xFE5_2 mask (#42)
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.
2026-05-18 14:36:20 +08:00
DrSmoothl 24056c3de0 feat(msg-push): decode group message emoji reactions (Event0x2DC subType=16)
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.
2026-05-18 14:06:44 +08:00
DrSmoothl a07521d9de fix(bridge): drop bloated fields from OIDB 0xFE5_2 group-list request
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.
2026-05-18 13:48:13 +08:00
DrSmoothl c62f51750a fix(oidb): drop the obsolete field 2 from OIDB 0xFE1_2 (user profile)
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.
2026-05-18 13:39:54 +08:00
DrSmoothl b94775cb6f chore(release): v1.8.4 2026-05-18 13:31:17 +08:00
DrSmoothl 5524c73eed chore(webui): keep search engines out of the admin surface
Even the login page leaks "there's a SnowLuma admin panel at this
IP / hostname" to anyone scanning, and right now that page is
publicly indexable. Three overlapping signals so we don't depend on
any one being honoured:

1. Hono middleware on every response sends
     X-Robots-Tag: noindex, nofollow, noarchive, nosnippet, noimageindex
   Hardest for compliant bots to ignore — it's a header, not
   content. noimageindex also covers logo.png / avatar/* from
   showing up in image search.

2. A GET /robots.txt route returns "User-agent: * / Disallow: /"
   for crawlers that read it before fetching pages. Sits before
   the auth middleware so no token is required (otherwise the
   crawler would get 401 here, which it'd then refuse to obey).

3. <meta name="robots"> (plus googlebot / bingbot) in index.html
   as a fallback for the case where a reverse proxy strips the
   X-Robots-Tag header.
2026-05-18 13:18:31 +08:00
DrSmoothl 4c513c015d feat(logger): runtime log level toggle via WebUI
The console / subscriber level was captured at module load
(`const MIN_LEVEL = resolveMinLevel()`), so any change to
SNOWLUMA_LOG_LEVEL after Node started had no effect — restart was
the only way to flip levels, which makes "go to debug for 30s to
see what's happening" pretty painful.

logger.ts now keeps `currentLevel` mutable and exports
setLogLevel() / getLogLevel(). The env var still seeds it on
startup; nothing about the boot-time behavior changes. File
transport remains unaffected — it always sees debug-and-up.

WebUI gets two new endpoints, both behind the existing auth
middleware:
  GET  /api/logs/level       → { level, levels }
  POST /api/logs/level body  → { level: 'debug' } updates it

Logs page picks up a "服务端级别" row of pills next to the
existing client-side filter pills, so an operator can flip the
console firehose on/off in one click without touching env vars
or restarting the bot. The label clarifies that file logging
stays at debug regardless.
2026-05-18 13:15:05 +08:00
DrSmoothl 4a49c55775 fix(hook): refresh pipe snapshot before verifying unload took
After native unload returns, the verification check
  if (pipeWatcher.isPipeLive(pid)) { ... unload-failed message ... }
read PipeWatcher's cached snapshot, which is updated every 1500ms.
On Windows clicking "Unload" in WebUI almost always tripped this:
the native unload succeeded and the kernel pipe object was gone, but
the watcher's cached "live" state from the previous tick was still
fresh, so the session reported "DLL卸载失败:命名管道仍然存在" even
though the DLL was successfully unloaded. The user then sees the
status flip back to connecting and waits for a real (cached) refresh.

PipeWatcher already exposes tickNow() for exactly this situation —
the load path doesn't need it because injection's verification runs
async via onPipeUp, but unload verifies inline.

HookSessionDeps.pipeWatcher gains an optional `tickNow` and
unloadInternal awaits it before reading isPipeLive. Existing test
mocks that pass only `{ isPipeLive }` keep working (optional chain
is a no-op there). New regression test covers the production
scenario — stale-true cache flipped to false by tickNow.
2026-05-18 13:07:10 +08:00
DrSmoothl e04a539b26 fix(logger): pass identity to the second printEvent call site
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.
2026-05-18 12:47:34 +08:00
DrSmoothl 257686eac6 feat(logger): identity-aware readable event rendering
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.
2026-05-18 12:32:18 +08:00
DrSmoothl 84e746c278 chore(observability): defensive depth pass
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).
2026-05-18 01:36:12 +08:00
DrSmoothl 7ec479bb88 feat(logger): protocol-layer observability for highway and msg-push
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.
2026-05-18 01:29:06 +08:00
DrSmoothl 1ba45e2659 feat(logger): observability for OneBot action dispatch
Every OneBot action call now emits a single debug line under
[Bridge.Action]:
  DEBUG [Bridge.Action] send_group_msg group_id=12345 message=[len=3]

On failure, dispatch logs a warn with the full stack instead of
silently folding the error into the response. Unknown actions also
get a debug entry so "the bot is ignoring me" is no longer invisible.

Notes:
- New summarizeParams() helper caps each value at 40 chars / line at
  200 chars to keep arrays / nested payloads from blowing the line
  width. Lives in utils/log-summary.ts for reuse (highway will too).
- ApiHandler now takes an optional uin and binds a child logger so
  per-account file routing works. OneBotInstance passes its parsed
  uin.
- Control-char strip in logger/file-transport was exempting only ESC;
  also exempt TAB (0x09) and LF (0x0A) so stack traces stay
  multi-line in both console and file output.
- vitest.config sets SNOWLUMA_LOG_LEVEL=debug so the ring buffer
  receives the new debug entries that tests assert on.
2026-05-18 01:19:30 +08:00
DrSmoothl 1d66693cc3 refactor(logger): bind per-account loggers in target classes
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.
2026-05-18 00:57:46 +08:00
DrSmoothl 93b9b03667 feat(logger): add .child({ uin }) API and per-UIN file fan-out
Logger now supports deriving a UIN-bound child:
  const log = createLogger('Bridge');
  this.log = log.child({ uin: this.uin });

The child stamps a fixed-width [UIN] slot into rendered lines so the
[Scope] column stays vertically aligned, and routes the same line to
a per-UIN sub-file:
  logs/snowluma-YYYY-MM-DD.log       (shared, all UINs)
  logs/<uin>/snowluma-YYYY-MM-DD.log (per-account)

Both pathways share daily rollover, size cap, and retention.
LogEntry now carries uin so SSE subscribers (WebUI) can filter later.

Other meta keys passed to child() are preserved in opts.meta for
forward compat (requestId / traceId etc.) but not rendered yet.

Module-level callers are unchanged; no callsites migrated in this PR.
SNOWLUMA_LOG_PER_UIN=0 disables the per-account sub-file while
keeping the shared one.
2026-05-18 00:50:15 +08:00
DrSmoothl 51f46e15fd feat(logger): add file transport with daily rotation and size cap
Adds a hand-rolled FileTransport that fans out every log line (debug
and up, regardless of console filter) to
./logs/snowluma-YYYY-MM-DD.log. When the current file exceeds the
configurable size cap it rolls into snowluma-YYYY-MM-DD.1.log, and
files older than the retention window are unlinked at startup and on
each day rollover.

Config (all env, no settings.json):
- SNOWLUMA_LOG_FILE      0 to disable file output (default: on)
- SNOWLUMA_LOG_DIR       output directory       (default: ./logs)
- SNOWLUMA_LOG_MAX_MB    per-file cap, MB       (default: 50)
- SNOWLUMA_LOG_RETAIN_DAYS retention window     (default: 7)

closeLogger() awaits the WriteStream's finish event; SIGINT and
SIGTERM handlers now await it before process.exit so the buffer
makes it to disk.

vitest config sets SNOWLUMA_LOG_FILE=0 to keep the suite from
polluting cwd; the new tests under tests/log-file-transport.test.ts
flip it back on per-test against a tmpdir.
2026-05-18 00:44:30 +08:00
DrSmoothl c6f4d5c5a2 chore(release): v1.8.3 2026-05-18 00:10:43 +08:00