codex/async-sqlite-node24
27
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7c0519f75f | lint | ||
|
|
b1730d74cd |
test(core): add resolveUin to the group-file identity mock
MockBridge.identity gained resolveUin for the like-list Identity cascade. The uploadPrivate fixture listed every identity field and failed core typecheck in CI. |
||
|
|
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. |
||
|
|
e6a69b05a7 |
feat(onebot): expose group folder upload metadata
Decode the folder modifier metadata returned by group file listings and project it as last upload time, uploader ID, and uploader name for both folder listing actions. Regenerate the MCP catalog and add protocol, bridge, OneBot projection, and action schema coverage for the new fields. Closes #248 |
||
|
|
1b968b9126 |
feat(file): stream group + offline file uploads from disk (phase 5)
Wire the streaming primitives into the group-file and private/offline-file upload paths. Both now stage the source onto a local disk path (stageSourceToDisk — hardlink/download), hash it in one streaming pass (hashFileStreaming; the offline-file md510MCheckSum comes from the same pass via headLimit=MD5_HEAD_LIMIT), and PUT the file through a FileChunkSource — so a file up to the 4 GiB protocol ceiling never holds more than one 1 MiB chunk in RAM. The old readFileSync/loadBinarySource + computeHashes + md5First10MB buffered path is removed. The highway session is resolved before the file handle is opened (the handle's owner, uploadHighwayHttp, must be the next call so its finally-close always runs); a size+mtime guard re-checks the staged file before the PUT so a source mutated mid-send fails cleanly; and the staged temp is released in a finally on every exit. The OIDB preflight fields, the remembered-upload cache, the ext blobs, and the publish steps (group 0x6D9_4 / private sendC2cFile) are byte-for- byte unchanged. Tests re-mock at the stage/hash seams and assert the streamed FileChunkSource + cleanup for both group and c2c uploads. |
||
|
|
5324e2f014 |
refactor(highway): introduce ChunkSource for uploadHighwayHttp (phase 1)
Prep for streaming large media uploads from disk instead of buffering the whole file in RAM. Add a `ChunkSource` abstraction — `BufferChunkSource` (in-memory, byte-for-byte the old path) and `FileChunkSource` (disk-backed, reads exact-length chunks via a FileHandle, loops on short reads, throws on unexpected EOF) — and change `uploadHighwayHttp` to consume a `ChunkSource` instead of a `Uint8Array`. The uploader now owns the source and closes it once in `finally` (best-effort; never masks a primary upload error). Pure structural refactor: no streaming is wired yet. All five call sites (pipeline runPuts, group + private file upload, personal + group avatar) wrap their bytes in `BufferChunkSource`, so behavior is unchanged. Adds a byte-oracle test proving FileChunkSource ≡ BufferChunkSource across block boundaries, plus short-read/EOF/empty-input coverage. |
||
|
|
9ca64bed10 | feat(core,onebot): implement trans_group_file action (#161) | ||
|
|
02de2acea4 |
fix(core): support file sources in forwarded messages (#144)
Pre-upload file/url/base64 segments for forwarded message nodes into the target scope, re-upload cached file_ids when crossing private/group scope, and suppress standalone file-message publishing during forward preparation. |
||
|
|
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). |
||
|
|
c16064d7e3 |
refactor(packages): rename @snowluma/bridge → @snowluma/protocol
The package previously named "bridge" houses the protocol-byte layer (OIDB cmds, msg-push decoders, highway uploaders, element-builder, event bus). The name "bridge" suggested transport/lifecycle, which it isn't — that role lives in core/hook and core/bridge/manager. Rename to match what's actually inside. This is a pure rename: zero logic changes, all 73 import sites updated mechanically and TS-verified. core/onebot dependencies key updated. ESLint override path adjusted for the moved oidb-services directory. Rename detection threshold: git log --find-renames=20% recommended when following history across this commit — content-replacement (@snowluma/bridge → @snowluma/protocol) dropped per-file similarity below git's default 50% on import-heavy files. |
||
|
|
521808a6eb |
refactor(oidb): migrate group-file.ts OIDB cmds to namespaces
Splits the 16 OIDB cmds from GroupFileApi into self-contained
namespaces under @snowluma/bridge/oidb-services/group-file/. Adds
@snowluma/bridge/oidb-services/shared with `toInt` / `ensureRetCodeZero`
helpers so namespaces can validate sub-responses without an
@snowluma/core dependency.
Boundaries:
- Single-OIDB methods (publish / getCount / list-page / *url /
delete / move / *folder) become one-line forwarders.
- 3-stage methods (`upload` / `uploadPrivate`) keep their
orchestration on the facade — OIDB preflight goes through the
new namespace, but highway PUT + publish/sendC2cFile + upload-
cache bookkeeping stay where they are.
- `list` keeps its pagination loop on the facade; the page-fetch
namespace is one call.
- The NTV2-rich-media URL fetchers (group/private × ptt/video)
share a deserialize helper (`parseNtv2DownloadUrl`) so all four
namespaces only differ in their scene block.
Wire-byte equivalence preserved. The 0x6D6 family shares one
OidbGroupFileReq envelope; each namespace populates a different
slot (file / download / delete / move) and proton monomorphizes
per call site as before.
|
||
|
|
f7a03ca05a |
refactor(bridge): extract protocol layer into @snowluma/bridge package
Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files — events / event-bus / identity-service / packet-pipeline / element- builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* + the bridge-side formatters — out of `packages/core/src/bridge/` into the new `@snowluma/bridge` workspace package. Everything that translates QQ wire bytes ↔ typed events/elements now lives there. Why --- - `packages/core/src/bridge/` was actually two layers: a low-level "protocol decoder + I/O" set (msg-push, highway, packet-pipeline, identity, element-builder) AND the Api-class host (bridge.ts + apis/*). The Api layer can't move without the protocol layer moving first, but the two had grown into one directory. - Bridge-internal consumers (highway uploaders, OIDB envelope helper, element-builder, msg-push parsers) only ever needed `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata cache. Splitting them out lets that minimal surface live in the bridge package as `BridgeContext` while the api-layer's extended context (with `apis: ApiHub`) stays in @snowluma/core. What stays in @snowluma/core (apis layer): - bridge.ts ── the god-class that composes the protocol building blocks + mounts apis - bridge-interface.ts ── public façade for OneBot consumers - manager.ts ── per-uin BridgeManager hub - apis/* ── the 13 typed Api classes - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim BridgeContext with `apis: ApiHub` so the 13 Api classes keep their typed `this.ctx.apis.X.method()` access. Layout ------ Moved via `git mv` (history preserved): events / event-bus / identity-service / packet-pipeline / element-builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* → @snowluma/bridge/<sub> utils/event-format.ts → @snowluma/bridge/format.ts (the last one renamed because the destination directory only has bridge-related files; `format.ts` reads cleaner than `event-format`. Listed as a rename in git's `RM` output — content unchanged.) Layering fixes (functionality preserved, just type signatures) -------------------------------------------------------------- - `element-builder.SendContext.bridge` → typed as `BridgeContext` instead of `Bridge`. Reads only `bridge.identity` and the upload-cache (both on BridgeContext); the concrete `Bridge` instance still passes via free upcast. - `bridge-oidb.runOidb` signature widened from `Bridge` to `BridgeContext` — same reason. - `highway/{highway-client,pipeline,image-upload,ptt-upload, video-upload}.ts` — same. - `format.ts::formatReply` parameter typed as a new local `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject | null }`) instead of `MessageStore` from @snowluma/onebot. The OneBot `MessageStore` is a structural superset; consumers pass it through unchanged. - JSON value types moved to a new `@snowluma/common/json` subpath (consumed by format.ts) — `onebot/types.ts` re-exports them so external `import { JsonValue } from '<…>/onebot/types'` paths keep working. - `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts` into `@snowluma/bridge/bridge-context.ts` — element-builder + the forward-builder both read the upload cache through BridgeContext, so the type has to live in @snowluma/bridge. `bridge.ts` keeps its re-export for back-compat. Changes ------- - New package `packages/bridge/` (package.json with per-file subpath exports mirroring legacy `core/src/bridge/<x>` layout 1:1, tsconfig.json, typecheck script). - 35 `.ts` files moved via `git mv` (3 files counted by git as RM — rename + modify because Bridge → BridgeContext type swap). - 150+ import sites rewritten across `packages/core/src` and `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`, `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`. - `@snowluma/core` depends on `@snowluma/bridge` (workspace:*). - `@snowluma/bridge` depends on `@snowluma/common`, `@snowluma/proto-defs`, `@snowluma/proton`. - `packages/core/src/utils/` directory removed (empty). Verification ------------ - Full workspace `pnpm -r typecheck`: all 10 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, identical envelope to the pre-split build. Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The runnable `index.ts` stays in @snowluma/core as the application entry, importing `OneBotManager` from `@snowluma/onebot`. |
||
|
|
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).
|
||
|
|
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).
|
||
|
|
6c7e56d5a1 |
refactor(proto-defs): extract wire-protobuf definitions into standalone package
Move `packages/core/src/bridge/proto/proton/*.ts` (13 files, ~3.3k LOC) into a new `@snowluma/proto-defs` workspace package. The proton spike landed in the previous commit means bare-specifier imports (`@snowluma/proto-defs/oidb`, `…/message`, …) now resolve correctly through proton's vite plugin, so call-site replacement still fires. Why --- - Lets downstream consumers share the same wire definitions without copy-pasting them — multiple workspace packages can now depend on `@snowluma/proto-defs` directly. - Trims `@snowluma/core`'s surface: the bridge no longer owns the protocol schema, only its consumers. - Sets up future #5 (`message-parsing perf`) and #6 (`Api-on-ctx refactor`) — both want a thinner core. Layout ------ Per-file subpath exports (mirrors the legacy `proto/proton/<sub>` shape 1:1). The barrel `index.ts` intentionally skips `highway` and `oidb-actions/media` because the two files share six NTV2-prefixed type names — `export *` would silently drop one side. Subpath imports are unambiguous, which is also why every call site in core uses them. Changes ------- - New package `packages/proto-defs/` (package.json, tsconfig.json, src/index.ts). - 13 `.ts` files moved via `git mv` to preserve history. - 44 import sites across 26 source files + 15 tests rewritten via sed from `./[…/]proto/proton/<sub>` → `@snowluma/proto-defs/<sub>`. - `@snowluma/core` depends on `@snowluma/proto-defs` (workspace:*). Verification ------------ - proto-defs typecheck: clean - core typecheck: clean - core test suite: 587 passed (same baseline as before the refactor; one failure is the pre-existing websocket native addon, unrelated) - proton test suite: 99 passed (8 files including the new cross-package.test.ts from the spike) - Full workspace `pnpm -r typecheck`: all 8 projects clean Note: proton's `dist/index.js` MUST be rebuilt for the vite plugin to pick up the bare-specifier resolution. The previous commit's source change is only effective after `pnpm -F @snowluma/proton build`. |
||
|
|
5ea1c3a961 |
Remove bridge proto schemas and parity test
Delete proto schema modules under packages/core/src/bridge/proto (action.ts, element.ts, highway.ts, longmsg.ts, message.ts, notify.ts, oidb-action.ts, oidb.ts) and the related test packages/core/tests/proton-parity.test.ts. These files contained protobuf schema definitions for the bridge layer; remove them as part of a cleanup/refactor. Update any imports or references to these modules to their new locations or replacements. |
||
|
|
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>]`.
|
||
|
|
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 |
||
|
|
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. |
||
|
|
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.
|
||
|
|
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
|
||
|
|
b3df633c87 |
fix(bridge): correctness pass on highway, hook, and identity service
* 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. |
||
|
|
59cdfa98a2 |
refactor(oidb): replace 3 positional helpers with one named runOidb
bridge-oidb.ts used to expose three thin functions —
makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode — and every
action file repeated the same five-step envelope assembly with long
positional argument lists. Collapse them into one `runOidb(bridge,
call)` taking an OidbCall object: cmd / oidbCmd / subCmd / request
{ schema, value, isUid? } / response? { schema }.
Behavioural contract is preserved:
- No `response`: verify success + gotResponse, peek envelope retCode
iff response data is present (fire-and-check semantics).
- With `response`: require responseData, decode through the base
schema, validate retCode, return the inner body typed as TResp.
Migration touches 51 call sites across 9 source files (bridge-contacts,
actions/{group-file, group-admin, profile, group-message, friend,
interaction, misc}, web-actions/cookies) plus 9 test files that used
to assert on positional `.mock.calls[0]![4]` indices and now read
through `.mock.calls[0]![1].request.value` / `.cmd` / `.oidbCmd`.
Net effect: callers now name what each piece is for, and adding
cross-cutting OIDB behaviour (retry / timeout / per-cmd logging) is a
single-site change inside runOidb instead of a sweep across 9 files.
|
||
|
|
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. |