ad360c8eba5a555e40c64f3e3ecb4ee58d60f992
15
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
23352dcad4 |
refactor(protocol): resolve like-list UINs through Identity
GetLike already filled cached UINs in deserialize. ProfileApi then opened a second Contacts hop and threw on fetch failure. Misses now go through Identity.resolveUin after invokeOidb, coalesced by uid. ProfileApi.getLike is invoke-only. Unresolved rows stay uin=0 and no longer fail the action. |
||
|
|
fb4d7716a1 |
fix(core): restore group remarks in queries
Request and retain the group remark information needed by group list and group detail queries while preserving the existing safeguards for large rosters. Synchronize confirmed group remark changes with the local identity roster and persistent cache. Remote failures leave local state untouched, and missing roster entries remain observable without creating phantom groups. Add regression coverage for query mapping, request scope, persistence, failed updates, unknown groups, and closed identity stores. Fixes #304 |
||
|
|
659e0bd3d0 |
fix(friend): verify and synchronize remark updates
Validate the service result before reporting friend remark changes as successful. Rejected, incomplete, or contradictory confirmations now reach callers instead of being reported as completed. Keep confirmed remarks synchronized in the identity cache and consume cross-client remark updates without exposing a new OneBot event. Local cache failures remain observable without turning an already completed remote change into a retryable failure. Preserve friend remarks exactly across restarts and add request, response, persistence, receive-pipeline, and action-level regression coverage. Fixes #303. |
||
|
|
03aec3b052 |
fix(core): verify conversation read updates
Replace message-header sequence forwarding with a server-guided read flow for group and private conversations. Batch read reports conservatively, validate per-conversation results and cursor advancement, and fail with actionable errors when the server does not apply an update. Add regression coverage for mixed batches, pagination, already-current sessions, malformed responses, and private sequence-domain mismatches. |
||
|
|
9ca64bed10 | feat(core,onebot): implement trans_group_file action (#161) | ||
|
|
4e0ec92c23 |
fix(core): emit group_decrease + drop cache on set_group_leave (#133)
The server never pushes a member-decrease back to the member that left of its own accord, so set_group_leave produced no notice.group_decrease — downstream kept a 'zombie' group in its cache, and a later set_group_add_request failed with 'matching group request not found'. bridge.leave() now, after the 0x1097_1 OIDB succeeds, synthesizes a self group_member_leave (user_id = operator_id = self, sub_type 'leave') through the event bus — converted to notice.group_decrease by the existing path — and calls identity.forgetGroup() so get_group_list / member lookups drop it immediately (in-memory + DB inactive). Kick / disband already arrive via the GroupMemberDecrease push (PkgType 34). Limitation: a MANUAL leave in the NTQQ client isn't covered — SL is packet- based with no kernel callback, and a voluntary self-leave isn't pushed back; only kernel-based clients (NapCat/LLOneBot) catch that. Validated by unit tests (bridge leave emits the event + forgets the group). |
||
|
|
46b302f738 |
refactor(common): extract leaf utilities into @snowluma/common package
Phase 1 of the 4-package split called out in RoadMap #3. Moves the "infrastructure" leaves — files with zero business dependencies that @snowluma/bridge, @snowluma/core, and @snowluma/onebot all consume — into a dedicated workspace package. Mirrors what #4 (proto-defs) did for wire-protobuf definitions. Why --- - Cleaner layering: these were never bridge- or onebot-specific. Logger / hex codec / runtime config sit at the bottom of every module's import graph; giving them their own package makes that graph readable and prevents future leaks the other direction. - Sets up #3's bridge + onebot extractions: those need a clean leaf to depend on. Without this, every cross-package import would have to re-export through core, which defeats the split. - Mirrors @snowluma/proto-defs layout — per-file subpath exports (`@snowluma/common/logger`, `@snowluma/common/hex`, …) keep import sites unambiguous and let bundlers tree-shake aggressively. Layout ------ Moved (via `git mv` — history preserved): packages/core/src/utils/logger.ts → @snowluma/common/logger packages/core/src/utils/hex.ts → @snowluma/common/hex packages/core/src/utils/log-file-transport.ts → @snowluma/common/log-file-transport packages/core/src/utils/log-summary.ts → @snowluma/common/log-summary packages/core/src/protocol/packet-sender.ts → @snowluma/common/packet-sender packages/core/src/protocol/types.ts → @snowluma/common/protocol-types packages/core/src/common/runtime.ts → @snowluma/common/runtime Not moved (deferred to Phase 2): `packages/core/src/utils/event-format.ts` — it has reverse imports on `bridge/events`, `bridge/identity-service`, `onebot/message-store`, `onebot/types`. It moves into @snowluma/bridge in Phase 2, with the MessageStore parameter decoupled via a structural type so bridge doesn't end up depending on onebot. Changes ------- - New package `packages/common/` (package.json, tsconfig.json — no src/index.ts barrel, callers use the subpath exports directly to avoid pulling in `node:fs` when only the hex codec is needed). - 7 `.ts` files moved via `git mv`. - 50+ import sites rewritten via sed across `packages/core/src` and `packages/core/tests`. Old shapes (`../utils/logger`, `../../protocol/types`, `./common/runtime`, `../src/utils/hex`) all collapse to `@snowluma/common/<sub>`. - `@snowluma/core` depends on `@snowluma/common` (workspace:*). - `packages/core/src/{protocol,common}/` directories removed (empty). Verification ------------ - core typecheck: clean - common typecheck: clean - Full workspace `pnpm -r typecheck`: all 9 projects clean - core test suite: 552 passed / 552 total (pre-existing websocket-darwin-arm64.node addon failure unchanged — same baseline as the previous refactor commits) - Vite build with stubbed native binary: clean (143 modules, 2.84 MB bundle, 224 KB gzip — same size envelope as before) Note: `utils/event-format.ts` is the only file remaining under the old `utils/` namespace. It moves into @snowluma/bridge alongside the events / identity-service / packet-pipeline trio in Phase 2. |
||
|
|
dad501ebc0 |
refactor(api): move 17 group-file methods to GroupFileApi (#6 commit 4/13)
Inlines `actions/group-file.ts` into `apis/group-file.ts::GroupFileApi`,
deletes the old action file, removes the matching 17 facade methods
off `Bridge`, and slims `BridgeInterface` accordingly.
Method renaming follows the same "strip the redundant suffix" rule we
applied to GroupAdminApi:
uploadGroupFile → upload
uploadPrivateFile → uploadPrivate
sendGroupFileMessage → publish (OIDB 0x6d9_4)
fetchGroupFiles → list
fetchGroupFileCount → getCount
fetchGroupFileUrl → getUrl
fetchPrivateFileUrl → getPrivateUrl
fetchGroupPttUrlByNode → getPttUrl
fetchPrivatePttUrlByNode → getPrivatePttUrl
fetchGroupVideoUrlByNode → getVideoUrl
fetchPrivateVideoUrlByNode → getPrivateVideoUrl
deleteGroupFile → delete
moveGroupFile → move
createGroupFileFolder → createFolder
deleteGroupFileFolder → deleteFolder
renameGroupFileFolder → renameFolder
`upload`'s atomic upload+publish flow now calls `this.publish(...)`
directly instead of going through `bridge.sendGroupFileMessage`, and
`uploadPrivate` calls `this.ctx.apis.message.sendC2cFile(...)`.
Callers updated: `instance-context.ts`, `media-url-resolver.ts`,
`actions/group-file.ts` (onebot), `actions/extended.ts`,
`modules/{contact,media,message}-actions.ts`.
Tests: `group-file.test.ts` rewritten to use
`new GroupFileApi(bridge as any).method(...)`. The "verify publish was
called" assertions now use `vi.spyOn(api, 'publish').mockResolvedValue()`
since `publish` is an instance method on the same Api. `_helpers.ts`
gains `mockGroupFileApi()` for cross-Api callers and drops the flat
`sendGroupFileMessage` shim. `media-url-resolver.test.ts` and
`send-group-file.test.ts` switched to `bridge.apis.groupFile.*`; the
extended-actions `APIS_ROUTING` map now carries a `[area, newName]`
tuple so renamed methods auto-promote.
587/587 tests pass. The network-manager file remains as the only
failing test file (pre-existing infrastructure issue unrelated to #6).
|
||
|
|
6bf53890dc |
refactor(api): move contacts methods to ContactsApi (#6 commit 2/13)
Second of 13 commits decomposing Bridge. Moves the six "fetch the
roster / a profile / outstanding requests / download rkeys" methods
off Bridge and onto a new `apis.contacts.*`.
Methods moved
-------------
* fetchFriendList — OIDB 0xfd4_1 + identity.rememberFriends
* fetchGroupList — OIDB 0xfe5_2 + identity.rememberGroups
* fetchGroupMemberList — OIDB 0xfe7_3 + identity.rememberGroupMembers
(includes the 60s TTL + per-group inflight
coalesce cache that prevents Tencent
risk-control from triggering)
* fetchUserProfile — OIDB 0xfe1_2 + identity.rememberUserProfile
* fetchGroupRequests — OIDB 0x10c0_{1,2}
* fetchDownloadRKeys — OIDB 0x9067_202
Cache fields moved
------------------
The two member-list throttle maps (`memberListInflight_`,
`memberListLastFetch_`) move from Bridge to `ContactsApi` as private
fields. Same TTL, same semantics — just owned by the Api class that
exposes the method.
Constructor ordering
--------------------
`buildApiHub(this)` now runs BEFORE `identity.setFetcher(...)` in the
Bridge constructor because the `fetchProfile` / `fetchGroupMemberList`
callbacks installed there reach into `this.apis.contacts.*`. With
eager construction this is safe; the alternative (pass a thunk that
forwards once apis is built) was strictly worse for readability.
bridge-contacts.ts removed
--------------------------
The file existed solely as the previous module-function delegate
target; ContactsApi inlines every function body so there's nothing
left to keep.
Caller-site updates
-------------------
* `bridge/actions/friend.ts` — `bridge.fetchFriendList()` →
`bridge.apis.contacts.fetchFriendList()`.
* `onebot/manager.ts`, `onebot/instance-rkey.ts`,
`onebot/modules/contact-actions.ts`, `modules/request-actions.ts`,
`actions/extended.ts` — same shape rewrite (6 method names).
Test plumbing
-------------
* `tests/actions/_helpers.ts` — `mockApiHub()` grows a `contacts`
field built by `mockContactsApi()`.
* `tests/bridge-member-identity.test.ts::RefreshingBridge` — was
`override async fetchGroupMemberList()`. After the move the method
lives on `this.apis.contacts`, not `this`. Switched to patching the
method on the constructed ContactsApi instance directly.
* `tests/actions/friend.test.ts` — `bridge.fetchFriendList` →
`bridge.apis.contacts.fetchFriendList`; the "refresh throws" branch
overrides via `bridge.apis.contacts.fetchFriendList = vi.fn(…)`.
* `tests/onebot/contact-actions.test.ts`, `extended-actions.test.ts`,
`request-actions.test.ts` — local `fakeBridge` helpers gained an
auto-promotion shim that rewrites flat method stubs (the pre-#6
test API) into the new `apis.<area>.method` shape. Keeps existing
test setup readable while the production code uses the new path.
Tests: 587/587 pass (same baseline; pre-existing network-manager
native-addon failure unchanged).
|
||
|
|
3e5dca1bd4 |
refactor(api): introduce MessageApi + BridgeContext + ApiHub skeleton (#6 commit 1/13)
First of 13 commits decomposing the Bridge god-object into typed Api
classes following NapCat's `ctx.apis.XxxApi.method()` pattern. This
commit lays the foundation (BridgeContext, ApiHub, eager construction)
plus moves the message-send/recall/mark-read methods onto MessageApi.
Subsequent commits will move the other 12 areas (group admin, files,
profile, …) similarly.
Architecture
------------
* `bridge-context.ts` — new interface, the surface Api classes see.
Carries identity / events / apis / sendRawPacket / resolveUserUid /
next{Message,Client}Sequence helpers / upload meta cache. Replaces
the previous `BridgeInterface` for Api-class consumption (the
legacy interface still exists, just slimmed; full removal happens
in commit 13).
* `apis/index.ts` — `ApiHub` interface + `buildApiHub(ctx)` factory.
Each commit grows `ApiHub` by one entry; today only `message` is
populated.
* `apis/message.ts` — `MessageApi` with seven methods inlined from
the previous Bridge implementation:
sendGroup ← Bridge.sendGroupMessage
sendPrivate ← Bridge.sendPrivateMessage
sendC2cFile ← Bridge.sendC2cFileMessage
recallGroup ← actions/group-message.ts::recallGroupMessage
recallPrivate ← actions/group-message.ts::recallPrivateMessage
markGroupRead ← actions/group-message.ts::markGroupMessageRead
markPrivateRead ← actions/group-message.ts::markPrivateMessageRead
(Names trimmed: the `apis.message` prefix already signals the
context, so `apis.message.sendGroupMessage` would be redundant.)
Bridge changes
--------------
* Removed the 7 methods listed above (moved to MessageApi).
* Removed unused imports + `SEND_MSG_CMD` constant + `buildSendElems`
+ `protobuf_encode/decode` (now used only inside MessageApi).
* Added `readonly apis: ApiHub` field, built eagerly in constructor.
* Promoted `nextMessageRandom` / `nextClientSequence` from private →
public (Api classes need them to build SendMessageRequest packets).
* `BridgeInterface` now also lists `apis: ApiHub` + the two
generators; the 7 deleted method signatures are gone.
Caller-site updates (~9 files)
------------------------------
* `bridge/actions/group-file.ts` — `bridge.sendC2cFileMessage(...)`
→ `bridge.apis.message.sendC2cFile(...)`.
* `onebot/instance-context.ts` — markGroupMsgAsRead / markPrivateMsgAsRead
bindings now route through `apis.message.markGroup/PrivateRead`.
* `onebot/modules/message-actions.ts` — every send/recall site
rerouted; `typeof ref.bridge.sendXxx` type refs also updated.
* `onebot/actions/extended.ts` — same.
Tests (~5 files)
----------------
* `tests/actions/_helpers.ts` — `mockBridge()` grows an `apis` field
built by `mockApiHub()`; the previous flat `sendGroupMessage` etc.
vi.fn stubs are replaced with `mockMessageApi()`.
* All test files using direct `bridge.sendXxx` / `bridge.recallXxx` /
`bridge.markXxxAsRead` calls or stubs updated to `bridge.apis.message.*`.
* No behaviour changes — 587/587 pass (same baseline; pre-existing
network-manager native-addon failure unchanged).
|
||
|
|
c83c333e73 |
fix(file): route group publish through OIDB 0x6d9_4 and cache upload meta for c2c resend
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>]`.
|
||
|
|
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.
|
||
|
|
ac10c663f1 |
refactor(identity): absorb QQInfo into IdentityService
QQInfo's in-memory state (self identity, friends, group rosters,
profile cache) and read methods (findFriend / findGroup /
findGroupMember / findUserProfile / nickname / uin / selfProfile) now
live directly on IdentityService. The QQInfo class is gone; its
interfaces stay in `qq-info.ts` as plain types shared across the
remember*/find* surface.
This eliminates a long-standing duplication: every observation used to
maintain both QQInfo's in-memory structures and IdentityService's
SQLite mirror in parallel, with the uidByUin/uinByUid Maps tracked
separately. With one Module owning all three layers, every remember*
hydrates one set of structures and `loadSnapshot` repopulates the
in-memory uid↔uin index from SQLite on startup — closing the cold-cache
gap that previously forced findUidByUin to fall through to a SQLite
query after every restart.
Knock-on changes:
- `Bridge` no longer holds a QQInfo; constructor takes an
`IdentityService`. The CmdParser signature on the cmd dispatch
table now passes `IdentityService` to parsers.
- `msg-push-handler.ts` drops its private `resolveUidToUin(qqInfo, …)`
helper that bypassed IdentityService's cascade — the parser hot
path now reads through `identity.findUinByUid(uid, groupId)` and
benefits from the O(1) `uinByUid` map even on freshly-loaded
sessions.
- `BridgeManager`'s session-started callback drops the QQInfo
parameter; OneBotInstance no longer carries a `qqInfo` field and
exposes a `nickname` getter for the WebUI listing.
- `contact-actions` and the per-theme bridge action files stop
importing QQInfo; they read everything via `bridge.identity.*`.
|
||
|
|
030336a25c |
refactor(identity): consolidate UID resolution behind IdentityService
Pull the cache→DB→network-fetch fallback cascade for UIN→UID translation into a single async `resolveUid` on IdentityService, and drop the duplicated `resolveUserUid` helper that used to live in bridge-oidb. Bridge injects itself as the IdentityFetcher post-construction so the network fallback runs through the same OIDB profile fetch the helper used. Each action module's `resolveUserUid(bridge, uin, groupId?)` call becomes `bridge.resolveUserUid(uin, groupId?)` — same signature on Bridge, but internally it now goes through `identity.resolveUid` so future changes (retry, coalescing, alternative resolvers) only need to land in one place. This is part 1 of the IdentityService deepening (RoadMap item 1). The QQInfo bypass in msg-push-handler and the broader QQInfo absorption land in the follow-up commit. |
||
|
|
8506b60d07 |
refactor(core): split bridge-actions.ts (1814 lines) into themed action modules
bridge-actions.ts was a single 1814-line file holding 55 unrelated exported functions — admin/file/forward/interaction/recall/profile/ status/translate/sign/avatar all jumbled together. Each function already takes `bridge: Bridge` as its first parameter, so the "deepening" target (per-UIN state object threaded into themed action functions) was structurally there — what was missing was a coherent file-level grouping that AI tools and humans could navigate. This commit is candidate #2 from the deepening list, A-only variant: pure file split, no facade change, no caller change outside the bridge module. New layout under packages/core/src/bridge/actions/ : shared.ts 82 private helpers (toInt, ensureRetCodeZero, resolveSelfUid) and the MediaIndexNode type. group-admin.ts 153 mute/kick/leave + setGroup{Admin/Card/Name/ SpecialTitle/AddOption/Search/Remark/AddRequest} + getGroupAtAllRemain. (14 fns) group-file.ts 821 upload/list/url/delete/move/folder ops, both group + private files, media-URL fetchers for ptt/video, fetchGroupFileCount. Owns file- specific helpers (normalizeDirectory, buildGroupFileUploadExt, normalizeMediaNode, fetchNtv2DownloadUrl, ...). (15 fns) group-message 101 recall* / markRead* / setGroupEssence. (5 fns) interaction.ts 61 poke / like / reaction / emoji-likes. (4 fns) forward.ts 197 uploadForwardNodes, fetchForwardNodes + in-memory resId cache. (2 fns) friend.ts 53 setFriendAddRequest, deleteFriend, setFriendRemark. (3 fns) profile.ts 269 setOnlineStatus, setProfile, setSelfLongNick, setInputStatus, setAvatar, fetchCustomFace, getProfileLike, getUnidirectionalFriendList. (8 fns) misc.ts 173 translateEn2Zh, getMiniAppArk, clickInlineKeyboardButton, sendGroupSign. (4 fns) bridge.ts updates its imports — one themed import block per action module instead of one giant block from bridge-actions.ts. GroupFilesResult and MediaIndexNode type imports now point at actions/group-file and actions/shared. Public Bridge facade API is unchanged: every caller outside `bridge/` keeps the same `bridge.X(...)` surface and the delegated function it points at. bridge-actions.ts is deleted. The new shared.ts holds the three helpers that span themes; everything else lives co-located with the functions that use it. Adds 60 happy-path tests across tests/actions/ — one .test.ts per themed file plus a shared `_helpers.ts` (mockBridge fixture): group-admin 10 command + payload dispatch, UID resolution, flag-driven sub-command selection (mute on/off, add-request filtered/unfiltered). group-file 13 fetchGroupFileCount, upload happy path with and without highway, OIDB error bubbling, file listing pagination + folder/file split, URL builder shape, delete/move/folder dispatch, NTV2 URL assembly. group-message 5 recall (group/private), markRead, essence on/off, transport failure propagation. interaction 6 poke (group vs friend payload), like, reaction on/off, emoji-likes cookie/isLast logic. forward 5 empty-array rejection, dispatch + res_id return, transport failure, cache reuse after upload. friend 5 numeric flag → UID resolution path, opaque flag passthrough, delete + best-effort cache refresh. profile 9 status dispatch, setProfile no-op when undefined, setAvatar highway cmd 90, getProfileLike + getUnidirectionalFriendList JSON parsing. misc 6 translate, mini-app type guard, click + sign dispatch. Tests use vi.mock on `bridge-oidb` (and `highway-client`/`highway-utils` where relevant) so each action runs against a tiny fake Bridge, no native pipe / real OIDB exchange needed. Previously these 55 functions had zero unit-test coverage. 244 tests pass (was 184); only failing suite remains the pre-existing macOS-arm64 missing websocket native addon, unrelated. |