Commit Graph
228 Commits
Author SHA1 Message Date
DrSmoothl 45d651614b feat(webui): layout schema for mobile overview + topbar items (B2)
Schema foundation for the B2 dashboard batch, mirroring the navItems shape:

- `overviewMobile: UiLayoutItem[]` — a separate single-column (id+visible)
  ordering for phones, kept fully disjoint from the desktop 2D `overviewBlocks`
  grid so mobile ordering never pollutes grid coords.
- `topbarItems: UiLayoutItem[]` — show/hide list for toggleable top-bar
  elements (status badge, theme toggle, kiosk button); essential elements stay
  pinned in the consumer.

Server `normalizeLayout` round-trips both (idOr + dedup, total over corrupt
input); defaults seed first run. `LayoutContext` exposes them with
setOverviewMobile/setTopbarItems setters and reconcile-on-consume semantics, so
adding a widget/element later just appears. Old configs lacking the fields fall
back to defaults on load.

Consumers (mobile render, topbar render + config, drag-sort panel) land in
follow-up B2 commits.
2026-06-16 14:14:03 +08:00
DrSmoothl 5b07f518cc feat(webui): custom fonts + theme-variable override panel (B1)
Adds two appearance customizations from the WebUI plan's B1 batch:

- Custom fonts: new `fontSansCustom`/`fontMonoCustom` free-form family
  fields (mirroring accent's preset/custom dual-field). A "自定义" segment
  reveals a text input; on Chromium it gets a native <datalist> of installed
  fonts via `queryLocalFonts()`, feature-detected with a silent fallback to
  a plain text box on Firefox/Safari/mobile. No font-file uploads.

- Theme-variable panel: new `cssVars` map lets the operator override
  individual theme tokens (background/foreground/primary/…) with colour
  pickers, layered last over palette+accent. Both keys (token whitelist) and
  values (hex/named/functional colour) are validated, so — unlike customCss —
  this stays safe to serve to the unauthenticated login page.

Server `normalizeAppearance` gains `fontFamilyOr` (rejects control
chars/injection) and `normalizeCssVars` (whitelist keys + colour-only values,
total over corrupt input). Client `ThemeContext` re-validates defensively
(the localStorage cache is locally tamperable) before injecting into CSS.

Tests for the new normalizers land with the B4 batch.
2026-06-16 14:04:59 +08:00
DrSmoothl e0d5b47488 feat(msg-push): filter C2C control pushes by c2c_cmd, matching QQ NT (#102)
Upgrades the blank-body heuristic to NT's exact discriminator. RE of
wrapper.linux.node (msg_header_codec_helper.cc::DecodeRoutingHead, sub_3B42650)
shows the official client classifies a C2C push by (svr_msg_type, c2c_cmd):
msgType ∈ {141,166,167} with c2c_cmd ∈ {1,73,75,129,131,133,135,192} is routed
through OnRecvSysMsg (long_cnn_msg_mgr.cc) as a system/control signal and never
shown as a chat bubble — the group-invite "[空消息]" phantom is one of these.

- proto-defs: ContentHead field 3 was mislabelled `divSeq`; it is `c2c_cmd`.
  Renamed (only other use was forward.ts, which zeroes it on a fake send).
- MsgPushHead now carries c2cCmd; new isC2cControlPush() in blank-filter.ts.
- parseMsgPush + both history fetches drop control pushes by (msgType, c2cCmd)
  regardless of body, so a control signal carrying stray content is caught too
  (not just the empty case). isBlankMessage stays as the fallback for
  content-less pushes we don't yet classify by cmd. Live path debug-logs a
  control push that carried elements, in case the table ever eats real content.

NOTE: the c2c_cmd set is taken from NT; we have not captured #24's actual cmd
(our diagnostic never logged field 3), so the blank fallback remains load-bearing
until a live capture confirms which cmd the invite phantom uses.
2026-06-16 01:34:38 +08:00
DrSmoothl 300fa70148 feat(spike): add logging and handling for KickNT command in bridge and session 2026-06-16 00:34:03 +08:00
DrSmoothl b0bfb9e6a7 feat(contacts): resolve non-member group name via 0x88D_0 (group invites)
A group invite push carries no group name (confirmed across SnowLuma / Lagrange
/ NapCat — all three invite protos only have groupUin + invitorUid), and
get_group_info only resolved joined groups (fetchGroupList → roster), so an
invited group rendered "未知群名". Add a by-id server lookup so the name
resolves even when the bot isn't a member.

- proto-defs: 0x88D_0 request (field1 + config.uin + a request-mask `flags`
  block) + response (groupInfo.results: name / member counts / owner / …),
  field tags transcribed from
  dev/Lagrange.Core/.../OidbSvcTrpcTcp0x88D_0{,Response}.cs.
- protocol: FetchGroupDetail oidb-service. Envelope reserved=0 (NO uinForm) —
  Lagrange's GetGroupInfoService builds it with isUid=false.
- core: ContactsApi.fetchGroupDetail(gid) → QQGroupInfo | null; deliberately
  NOT remembered into the joined-groups roster (mustn't pollute get_group_list).
- onebot: get_group_info falls back to fetchGroupDetail for non-member groups,
  behind a 5-min per-id TTL cache so a burst of invites for one group can't
  hammer 0x88D_0 (rate-limit / kick risk). noCache bypasses it.
- tests: request/envelope round-trip (reserved=0, uin, command), response
  decode; + non-member resolve / cache-hit / noCache-bypass at the onebot layer.

Live note: byte-identical to Lagrange's 0x88D_0, but not verified against a real
account on this host.
2026-06-15 14:33:06 +08:00
DrSmoothl 28633f3c62 feat(onebot): back-fill a quoted message from the server when not stored
When an incoming reply quotes a message SnowLuma's store doesn't have (e.g. one
from before it was running, or never observed), the receive pipeline now fetches
just that message from the server and persists it before dispatch — so a
consumer's get_msg on the quote resolves instead of returning "message not
found". Works for both group and private (c2c).

- core: MessageApi.getGroupMessageBySeq / getC2cMessageBySeq — fetch a single
  message over a 1-wide [seq,seq] range, through the shared history throttle
  gate (same rate-limit as the bulk history APIs — no flood / kick risk).
- onebot: backfillReplyTarget — on a group/friend reply whose target isn't in
  the store, fetch (group SsoGetGroupMsg / c2c SsoGetC2cMsg, uid resolved for
  c2c) and persist under the EXACT id the reply resolves to, so get_msg hits
  regardless of who sent the quoted message (a bot self-sent c2c message
  converts with user_id=self but is keyed under the peer session). Awaited
  before dispatch so the consumer sees it; best-effort — a back-fill failure
  never blocks delivery of the live message.
- tests: gating (already-stored / no-reply / nothing-on-server) + keying
  (group, c2c, c2c self-sent under peer session).

Only fires on a store miss, so the common path (no reply, or quote already
stored) stays zero-cost.
2026-06-15 13:53:04 +08:00
DrSmoothl 58c02d415f feat(onebot): fetch real private (c2c) history from server (#99)
Mirror the group-history fetch for private chats via SsoGetC2cMsg
(trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg, fields per Lagrange:
flat friendUid/start/end request, messages@7 response). get_friend_msg_history
now resolves the anchor sequence + the friend's UID, fetches real history from
the server, converts + persists each message, and falls back to the local
store on unknown anchor / no uid / empty / error.

- protocol: fetchC2cMessageRange (decodes via the friend decoder).
- core: the group + c2c fetch now share a generic walkBackHistory loop
  (same throttle gate + caps); added MessageApi.getC2cHistory.
- onebot: getFriendHistory + a generalized persistHistoryEvent (keys private
  by sender uin, exactly like the live path — so reply to old private
  messages resolves too).

Tests: SsoGetC2cMsg request/response round-trip + friend-decode reuse.
2026-06-14 20:15:38 +08:00
DrSmoothl 987ac09896 feat(onebot): fetch real group history from server (#99)
get_group_msg_history was served only from the local observed-message store,
so it could never return more than what SnowLuma saw live (the "only 100
messages" symptom). It now fetches real history from the server.

- protocol: new SsoGetGroupMsg packet (trpc.msg.register_proxy.RegisterProxy
  .SsoGetGroupMsg, sequence-range fetch; fields per Lagrange). Each returned
  PushMsgBody is decoded by the existing group decoder via a factored-out
  buildContextFromMessage.
- core: MessageApi.getGroupHistory walks backward in small sequence windows
  with rate-limiting + data-volume guards — a process-wide throttle (≥300ms
  between sends), 30-seq chunks, ≤12 requests, ≤200 messages per call — so a
  hammering client can't make us flood the server and get kicked.
- onebot: get_group_msg_history resolves the anchor sequence (requested
  message_id or latest observed), fetches from the server, converts + returns,
  and persists each fetched message. Falls back to the local store on
  unknown anchor / empty / error.

Persisting fetched history also fixes replying to pre-injection messages:
the reply path resolves message_id→sequence via the store, which now contains
the fetched messages.

Tests: SsoGetGroupMsg request/response round-trip + decode reuse (protocol);
walk-back chunking/dedup/cap/floor (core).
2026-06-14 19:11:03 +08:00
DrSmoothl 44a29c6ee4 feat(webui): OLED/accent/palette theming fixes + light-dark reveal
- OLED: toggle switch off-track is now a neutral foreground tint with a white
  knob (was invisible bg-muted + bg-background on pure black); the OLED sidebar
  override is scoped to sidebar-style=follow so panel/accent work in OLED too.
- Accent: the chosen accent now also tints the selected-state surfaces
  (--accent / --sidebar-accent) so the sidebar active item and settings nav
  rail follow it — default palette only, respecting accent scope.
- Palettes: add 6 more soft schemes (Rosé Pine / Moon / Dawn, Nord, Everforest
  dark + light) via a pal() builder; schema unions + normalizer + bootstrap
  light/dark classification updated to match.
- Light/dark switch now animates: a circular View Transitions reveal from the
  click (mode/palette/intensity changes only; gated off under reduced/disabled
  motion; instant fallback where the API is absent).
2026-06-14 16:20:05 +08:00
DrSmoothl 985dfd4705 feat(webui): animated login background + three independent motion settings
Login page now has a mouse-reactive wavy-line background (ported a-waves +
embedded Perlin noise, themed to the accent, rendered behind the card which
sits on a 95%-opaque blurred surface so content stays readable). A "我觉得这个
界面很卡怎么办?" link opens a dialog that toggles it off — a device-local
preference (localStorage, works pre-auth, defaults off when the OS prefers
reduced motion), independent of the system motion settings.

Motion settings are now three:
- 关闭登录页的动效 — the login background toggle above (device-local).
- 减弱动效 (reduceMotion) — soft: transforms/springs off, durations
  collapsed, page/sidebar instant; gentle entrance fades remain.
- 关闭全部动效 (disableMotion, NEW appearance field) — everything reduce does
  plus data-no-motion CSS (kills pulse dots; spinners excluded so "busy"
  stays legible) and the entrance opacity fades gated off across
  overview/processes/logs/config lists.
2026-06-14 00:41:18 +08:00
DrSmoothl e93a17de78 feat(webui): add Catppuccin Latte/Frappé/Macchiato/Mocha palettes
Add a "配色方案" picker offering the four Catppuccin flavors as full color
schemes alongside the default sky theme.

- Schema: new `palette` field on UiAppearance (core + client mirror),
  normalized to a 5-value whitelist defaulting to 'default'.
- Apply: each flavor's base/surface tokens are injected into the shared
  theme stylesheet over :root (Latte) or .dark (the three dark flavors);
  accent (--primary/--ring) stays separate so it composes. A flavor fixes
  light/dark (Latte→light, rest→dark), overriding `mode`, and forces
  dark-intensity to soft so the OLED "black" rule can't fight the palette.
  sidebar-style + high-contrast still compose (higher specificity).
- Pre-paint bootstrap is palette-aware (no light↔dark flash on reload).
- Settings: swatch-preview picker; mode + dark-intensity controls disable
  while a flavor is active. The top-bar ThemeToggle hides then (it would be
  inert under a fixed-scheme palette).
2026-06-13 23:42:16 +08:00
DrSmoothl 056fff415c feat(webui): per-page preferences (phase 7)
A `pages` section in config/ui.json (3rd section-merge alongside appearance +
layout):
- defaultRoute: the page to open after login (chosen in Settings → 数据与格式;
  DefaultRouteRedirect navigates there once, only from '/', respecting
  deep-links + later navigation).
- logs: persisted visible levels, max lines, auto-scroll, line-wrap, and
  keyword→colour highlight rules — edited live on the logs page; maxLines is
  read via a ref so it never re-subscribes the SSE.
- processes: pid / name / status sort (persisted, default from prefs).
- config: remembers the last-used tab.

"重置全部" now also clears pages. The server normalizer is total and caps the
logs fields (levels subset, maxLines 100-5000, <=20 highlight rules, trimmed
keywords). Verified by an adversarial review round (normalizePages total
against 30 adversarial inputs; zero MUST/SHOULD-FIX).
2026-06-13 21:17:24 +08:00
DrSmoothl 7c2923dd04 feat(webui): custom CSS + config export/import/reset (phase 6)
A "高级" Settings tab adds:
- Custom CSS (appearance.customCss, <=50KB) applied post-auth only, as the
  last <style> so it overrides everything. It never reaches the login page:
  the server strips it from /api/ui/public, applyAppearance gates injection on
  a bearer token (so the localStorage cache can't leak it pre-auth), and the
  login page clears any lingering <style> on mount. `?safe-mode=1` (sticky for
  the tab session) disables custom CSS so a broken rule can't lock the
  operator out.
- Export / import the whole UI config as JSON (import is normalized
  server-side, then reload); reset-all behind a confirm dialog.

POST /api/ui and the import file are size-capped (256KB) on top of the
per-field caps. Verified across 2 adversarial review rounds — the pre-auth
cached-CSS leak/lockout vector found in round 1 is closed across the boot /
logout / 401-expiry / re-login paths.
2026-06-13 21:17:23 +08:00
DrSmoothl 3258300539 feat(webui): per-widget config — alerts levels/count, sessions sort/filter (phase 5)
Overview widgets can carry an opaque `config` (stored per grid item). v1:
- alerts: how many entries + which log levels (was fixed at 5 warn/error);
  the alert row colour now uses the full 6-level palette instead of a
  warn/error binary.
- sessions: sort (recent / uin / nickname) + a nickname/uin filter.

A gear in the layout editor opens an inline config form per configurable
widget; edits apply live (no grid re-init — config isn't in the grid key) and
persist via the section-merge save. Config is parsed client-side with total,
clamping parsers (count 1-50, known levels only, filter <=100 chars); the
server stores it opaquely within a 4KB bound. Widgets with no config render
exactly as before. Verified across 2 adversarial review rounds.
2026-06-13 21:17:23 +08:00
DrSmoothl f07f309c51 feat(webui): free-form draggable/resizable dashboard grid (phase 4)
The overview becomes a gridstack-backed free grid — drag, resize, and show/
hide 9 widgets (the 5 top stat tiles split out of the old single block, plus
connections/alerts/host/sessions), persisted to config/ui.json's
layout.overviewBlocks as {id,x,y,w,h,visible}.

- gridstack (zero-dep, vanilla; chosen over react-grid-layout whose
  react-draggable uses the React-19-removed findDOMNode). React renders each
  widget into a gridstack item via a portal (context flows through); gridstack
  owns layout/drag/resize. Per-widget minW/minH prevent content collapse.
- Desktop = editable in place; narrow screens = auto single-column, read-only.
  Fixed cellHeight => no ResizeObserver => the narrow column-clamp never
  persists over the desktop coords.
- Edit mode shows a panel: widget show/hide + nav reorder (the phase-3 motion
  list); the grid below is live-editable. Reset + empty-state preserved.
- Server UiLayoutItem gains optional x/y/w/h (clamped); the stats->5-tiles
  migration + default placement live client-side (lib/dashboard-layout.ts).

Verified across 2 adversarial review rounds (gridstack+React lifecycle traced
against the library source: StrictMode-safe, no mount-persist loop, no
re-init on coord change, no narrow-visit data loss).
2026-06-13 21:17:23 +08:00
DrSmoothl ac1ffc46d3 feat(webui): appearance customization — theme/accent/background/fonts/a11y (phase 2)
Wires the Phase 1 store into a full appearance layer.

ThemeContext is rewritten to load/save UiAppearance from the server (with a
localStorage anti-flash cache + a one-time migration of the legacy per-browser
theme keys), apply ~12 dimensions to <html>, and theme the login page pre-auth.

New Settings controls (外观 / 数据与格式): free-hex accent (+ presets + apply
scope), dark intensity (soft / OLED black), sidebar style, background
(solid / gradient / uploaded image with opacity + blur), font presets, UI
scale, reduce-motion, high-contrast, default-collapsed sidebar, 12h/24h time
format (wired into logs + overview timestamps).

- index.html gains a pre-paint bootstrap script that applies the cached theme
  before the bundle mounts, eliminating the dark/OLED/scale FOUC.
- server saveUiConfig is now a section-level merge so appearance-only and
  layout-only saves never clobber each other.
- reduce-motion uses Framer MotionConfig; the background renders on a fixed
  layer revealed by transparent app roots; custom-accent hex and ui-scale are
  validated/clamped before use (localStorage-tamper hardening).

Verified across 2 adversarial review rounds (FOUC + CSS-injection + impure
state-updater + ref-staleness all fixed).
2026-06-13 01:15:00 +08:00
DrSmoothl 0b5087b410 feat(webui): UI customization config store + endpoints (phase 1)
Backend foundation for the WebUI appearance + layout customization feature.

- core/src/webui/ui-config.ts: config/ui.json store with TOTAL normalization
  (any input -> safe config), atomic write, lazy memoized cache, and the
  background-image lifecycle (magic-number sniff for PNG/JPEG/WebP).
- server.ts: GET/POST /api/ui (bearer), GET /api/ui/public (unauth cosmetic
  subset for pre-login theming), POST/DELETE /api/ui/background (upload with
  Content-Length pre-check + 5MB cap + magic-number validation), and unauth
  GET /ui-asset/background (serves the uploaded bytes with sniffed mime +
  nosniff). SPA fallback excludes /ui-asset/.
- webui: `ui` API-client namespace + mirror types (no UI wiring yet).

Server-managed background fields (hasImage/imageMime/imageVersion) are taken
from the trusted source per path — the file on load, the on-disk config on
save — so a client save can never forge them, and a wallpaper survives a
restart. Verified across 3 adversarial review rounds.
2026-06-13 01:15:00 +08:00
DrSmoothl 6a2fd9e8f3 fix(bridge): don't crash the daemon when the hook pipe closes mid-send
When the control pipe drops while a send() is awaiting its ack,
rejectControlPending() rejects both the ack and the reply deferreds. The
reply is only awaited after the ack, so an ack-first rejection leaves the
reply promise rejected with NO awaiter — an unhandled rejection that, under
Node's default policy, kills the process. In Docker supervisor restarts it
(every session drops for ~1s); on a bare Windows run it just dies, surfacing
as "connection pipe closed" with the bot offline after hours of uptime.

Attach a no-op .catch() to each deferred at creation so a rejection can never
go unhandled (the real await still observes the value/rejection). Add a
regression test that drops the pipe mid-send and asserts no unhandled
rejection escapes — it fails without the guard.

Also install last-resort process guards (unhandledRejection / uncaughtException)
in the app entry: log and keep serving instead of exiting, so any other stray
rejection cannot take the daemon down and its stack is captured. The bridge's
watcher reconnects the dropped pipe on the next tick.
2026-06-07 22:15:07 +08:00
DrSmoothl 56dc934106 feat(webui): notify when a newer release is available
Advisory, read-only update check: the core polls GitHub's latest stable release, compares it against the running build, and surfaces a notice in the sidebar footer plus a detailed card (changelog + download link + platform-matched asset hint) in Settings → About.

SnowLuma never downloads or applies anything itself — cross-platform self-update is a minefield (Windows locks loaded .node/.dll, Docker bakes the app into image layers, bare installs have no supervisor), so the user downloads and applies manually.

The backend caches results for 6h to stay under GitHub's unauthenticated rate limit, degrades silently on failure, and can be disabled via SNOWLUMA_UPDATE_CHECK=0.
2026-06-05 16:08:38 +08:00
DrSmoothl fc21d87a9b feat(onebot): fetch_ptt_text via async 0x210/61 result push (#79)
Live testing showed the voice-to-text text is delivered by an async push
(Event 0x210 subType 61), not the request response — so the previous
poll-by-resend never got it. Captured a real push and decoded its protobuf:
outer { f1, f2:item }; the item echoes the request msgId at field 1 (the
correlation key) and the recognised text at field 8.

- proto-defs: PttTransPush / PttTransPushItem (live-verified).
- protocol: Event0x210SubType.PttTransResult = 61 + decoder → internal
  `ptt_trans_result` event { msgId, text } (replaces the temp hex dump).
- core: translatePttToText now sends ONE trigger and returns the inline text
  only if present (already-transcribed); empty = pending.
- onebot: ptt-trans-waiter (keyed by selfUin:msgId), event-pipeline subscribes
  `ptt_trans_result` to resolve it; fetch_ptt_text registers the waiter,
  fires the trigger, and awaits the push (20s timeout).

Decoded one real push as text "12311123。" end to end.
2026-06-02 22:01:07 +08:00
DrSmoothl 15e4e261c5 feat(log): memory-only trace level + request correlation + chokepoint tracing
Debugging from user-supplied logs was impossible: a successful action left
one terse, over-summarized debug line and nothing about what it sent QQ or
what QQ returned. Add full-chain tracing that stays off disk so it scales to
hundreds of groups.

common:
- New `trace` level (below debug). Never written to file — it lives only in
  an in-memory ring + the WebUI stream, so the high-volume full chain costs no
  disk. `emit` early-returns for trace before format/render (and before any
  lazy producer) when trace isn't active → ~free at the default level.
- Dedicated O(1) circular ring for trace (default 5000, SNOWLUMA_TRACE_BUFFER),
  separate from the normal 1000-entry buffer (also switched off array .shift);
  getRecentLogs merges both by id.
- request-context.ts: AsyncLocalStorage request id. The logger auto-stamps
  `[req#N]` on every line in a request's async chain — across packages, zero
  signature threading — and records it on the entry.
- log-summary.renderParamsVerbose: deep render of params (nested structure,
  per-string cap, total budget, token/password/secret redaction).

chokepoints (auto-cover every action without touching 100+ handlers):
- onebot api-handler: wrap each action in a request id (only when trace is
  live); trace the full params on entry and status+elapsed on exit; the terse
  debug breadcrumb still persists to file, failures still warn.
- core bridge.sendRawPacket: trace on success (cmd, sizes, elapsed); warn on
  errorCode!=0 / no response (cmd, code, message) so disk keeps real problems.
- protocol highway: fold the bare console.log lines into the logger (trace).

webui: trace as the lowest filterable level; render the `[req#N]` tag and let
search match it. Server needs no change — LOG_LEVELS, getRecentLogs and the
SSE stream carry it through.
2026-06-02 21:01:19 +08:00
DrSmoothl 7336352cd3 feat(onebot): voice-to-text action fetch_ptt_text (#79)
Adds NapCat-compatible voice-to-text. New `fetch_ptt_text` action (aliases
`get_ptt_text` / `get_record_text`) takes a message_id, resolves the cached
`record` fingerprint (uuid + md5 + duration/size/format), drives QQ's native
`pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq`, and returns { text }.

The response carries the text inline once transcription is done; an empty
text means the server is still transcribing (there is no dedicated push
command — confirmed via RE), so the bridge re-sends with a short backoff
until the text lands, mirroring NapCat's fire-then-re-read shape.

Layers:
- proto-defs/ptt-trans: PttTransReq/Resp + per-scene items.
- core ExtrasApi.translatePttToText: encode -> sendRawPacket -> decode -> poll.
- onebot media-actions.fetchPttText + api-handler/instance-context wiring.
- onebot extended: register the action + aliases.

The commands + request/response field tags were reverse-engineered from
QQ-NT wrapper.node (im_core/msg/ptt/ptt_trans_worker.cc). The numeric tags
are solid; the length-delimited fields (uuid/md5) and the response text tag
are RE-derived and want one live capture to confirm before relying on them.
2026-06-02 20:47:06 +08:00
DrSmoothl 0e4b881f76 feat(webui): add live connection status for OneBot adapters in dashboard 2026-05-30 18:02:01 +08:00
DrSmoothl 0110b71dd3 fix(protocol): send browser UA + Referer retry on media downloads
loadBinarySource issued a header-less fetch(source) for remote media.
Anti-hotlink / anti-bot front-ends reset such requests, surfacing as
undici `TypeError: fetch failed` (not a clean 403) — so quoting a
command and sending an image/GIF whose source is a guarded URL bounced
with send_group_msg retcode 1200 "fetch failed".

Mirror NapCat's download path: send a browser User-Agent on every
request and retry once with a Referer pointing at the resource when the
first attempt is refused (network error or 403/4xx). Size-limit
rejections are tagged noRetry so an oversized body isn't re-downloaded.
Also route set_group_notice's image fetch through loadBinarySource so it
inherits the same hardening (plus http/file/base64 handling).
2026-05-29 17:37:10 +08:00
H3CoF6 00ca582f1a feat(protocol): implement OIDB 0xcde_2 (RequestDbKey) (#69) 2026-05-28 15:18:06 +08:00
手瓜一十雪 456086599c Normalize imports, typings and formatting
Reorder and normalize imports, add missing type imports, and fix whitespace/formatting across multiple files. Notable updates: eslint.config.ts import ordering; core bridge APIs (group-album, misc, web) now import Json types; tests/highway pipeline import ordering and added type imports; protocol changes (element-builder, highway client/pipeline) reorganized imports and added proto type imports; many oidb service modules moved protobuf encode/decode imports for consistency; web group modules (album, essence, honor, notice, request-util) reordered imports, adjusted typings/indentation, and small whitespace fixes. These edits are stylistic and typing improvements and should not change runtime behavior.
2026-05-24 13:39:35 +08:00
手瓜一十雪 80ee12ecc2 Enforce no-explicit-any; allow in tests
Enable @typescript-eslint/no-explicit-any as an error in the ESLint config to tighten typing across the codebase, and add an override to disable this rule for test files. Also apply non-functional cleanup in packages/proton/src/runtime.ts: reorder/imports and adjust formatting/indentation and string alignment for readability — no behavioral changes.
2026-05-24 13:38:13 +08:00
手瓜一十雪 acc5084647 Refactor group-album and remove eslint ignore
Remove an unused Bridge import, the asBridge helper and a stale comment from group-album, and relocate the GroupAlbumMediaResult and GroupAlbumCommentResult interfaces to the end of the file. In the sqlite package, remove the inline eslint-disable-next-line for @typescript-eslint/no-explicit-any near the BetterSqlite3 constructor. These edits clean up dead/stale code and re-enable the lint rule; there are no behavioral changes.
2026-05-24 13:16:36 +08:00
手瓜一十雪 a49e507e15 Refactor Bridge APIs, slim Bridge and reorder imports
Move and standardize API implementations under bridge/apis, slim down the Bridge class (remove inline action implementations, caches and large comment blocks) and relocate related types/exports. Clean up and reorder imports across many bridge/api modules, normalize constructors, add logger imports where needed, and adjust WebUI routing/import ordering. These changes centralize API logic, reduce Bridge surface area, and tidy module boundaries and imports.
2026-05-24 13:13:23 +08:00
DrSmoothl f53df5e313 refactor(packages): extract @snowluma/bridge (hook + QQ lifecycle)
Split the QQ NT client lifecycle / hook injection layer out of
@snowluma/core into its own self-contained package. The new bridge
package owns:
  - native hook addon loader (injector)
  - HookManager + per-PID HookSession orchestration
  - PipeWatcher for QQ process discovery
  - QqHookClient pipe protocol
  - qq-port-probe for early UIN sniffing

The hook layer used to type its main collaborator as
`BridgeManager` directly. To keep the new package free of any
dependency on @snowluma/core, the cross-package coupling is now
expressed via a 3-method `BridgeManagerSink` interface that lives
in the bridge package. BridgeManager (in core) satisfies the
interface structurally with no source changes; the top-level
app/webui still inject it the same way.

Pure file relocation otherwise: git mv preserves history at 100%
on every file, the only logic edit is the interface introduction
in hook-manager.ts and an updated `nativeSearchDirs()` offset
(one fewer `..` since hook now lives at packages/bridge/src
instead of packages/core/src/hook).
2026-05-23 23:40:57 +08:00
DrSmoothl 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.
2026-05-23 23:31:03 +08:00
DrSmoothl d8c72c2ebc fix(events): surface verify-text on group_invite ("你们好" → comment)
User report:
  SnowLuma's group_invite event renders to OneBot with empty
  `comment`, so the bot's approval-prompt template shows nickname
  + uin + flag but loses the requester's verify message.

  NapCat's same flow shows the verify text:
    【进群申请】批准/驳回:
    昵称:KitaIkuyo
    QQ:1957003260
    flag:1779543612823906
    等级:7
    你们好               ← only NapCat shows this line

Root cause:
  The OIDB push (GroupRequestJoinNotice subType=84) only carries
  `(groupUin, targetUid)` and a few opaque numeric fields — no
  string for the verify text. NapCat doesn't use the push directly;
  they poll `nodeIKernelGroupService.getGroupNotifies` (= our OIDB
  0x10C0 pending-request queue at `FetchGroupRequests`) which
  returns each pending row with `postscript` (the verify text) and
  `seq` (server sequence id). Reference:
    dev/NapCatQQ/packages/napcat-onebot/index.ts:483-498
    (`flag = notify.seq`, `comment = notify.postscript`).

  Our pipeline didn't enrich. The decoder set `message: ''` and
  emitted, so OneBot's `comment` was empty.

Fix:
  - Extend `PacketPipelineDeps` with a `resolveGroupJoinRequest(
    groupId, uid, subType)` hook. Bridge.ts wires it to
    `fetchGroupRequests` and matches on `(groupId, uid)` —
    targetUid for `subType='add'`, invitorUid for
    `subType='invite'`.
  - `dispatchAfterStrangerResolve` now fires the profile + request
    lookups in PARALLEL via `Promise.allSettled` so a flake on one
    path doesn't kill the other. The request lookup's `comment`
    lands on `event.message`; OneBot converts that to `comment`.

Decisions:
  - Kept the existing `add:<groupId>:<uid>` flag format (consumer
    bots already parse it). Switching to NapCat's sequence-form
    flag would break callers and is a separate breaking change.
  - Both lookups fail-open: if either rejects, the event still
    emits with whatever info we did get, so the bot at least sees
    the request and can render the bare nickname.

Regression tests:
  - `populates event.message from the pending-request queue` — pins
    the user-reported "你们好" case end-to-end through the pipeline.
  - `runs lookups in parallel` — profile resolves, request fails;
    event still ships with the resolved uin and an empty message.
  - `invite subtype matches the request on invitorUid` — explicit
    contract for the invite-forwarded-to-admin case where the
    pending row's REQUESTER is `invitorUid`, not `targetUid`.

345 bridge tests pass (was 342 + 3 new); typecheck + lint clean.
2026-05-23 22:00:14 +08:00
DrSmoothl a4909ec9e5 fix(events): resolve stranger nickname on group_invite (no more 未知昵称)
User report: when a stranger requests to join a group, the bot
receives `user_id=<groupId>` (instead of the requester's actual
uin) and `get_stranger_info` returns no nickname → bot displays
"未知昵称".

Two layered bugs:

  1. **Decoder fallback was wrong.** `decodeGroupJoinRequest` /
     `decodeGroupInvitation` / `decodeGroupInvite` all passed
     `ctx.fromUin` as the fallback uin when `resolveUidToUin` missed
     the local cache. But for group-scoped pushes `ctx.fromUin` is
     the GROUP's own uin — falling back to it produces the bogus
     `fromUin === groupId` collision the user saw. Fix: pass 0.

  2. **No async resolve for stranger UIDs.** The push only carries
     the requester's UID string. When the UID isn't in our cache
     (true for any stranger who isn't yet a group member), we have
     no UIN — and our UIN-form `FetchUserProfile` can't help. The
     pipeline never tried to look up the stranger by UID, so the
     event went out with `fromUin=0` (or, with the old fallback,
     the group's own uin).

Cross-checked against Lagrange.Core's flow:

  dev/Lagrange.Core/.../MessagingLogic.cs:215-224
    case GroupSysRequestJoinEvent join:
        var fetchUidEvent = FetchUserInfoEvent.Create(join.TargetUid);
        var results = await Collection.Business.SendEvent(fetchUidEvent);
        uint targetUin = results.Count == 0 ? 0
            : ((FetchUserInfoEvent)results[0]).UserInfo.Uin;
        var joinArgs = new GroupJoinRequestEvent(join.GroupUin, targetUin);

  dev/Lagrange.Core/.../OidbSvcTrpcTcp0xFE1_2.cs:9-26
    — UID-form variant of the same OIDB 0xFE1_2: field 1 is `uid:
      string`, envelope `reserved=0` (no uinForm flag).

  dev/Lagrange.Core/.../FetchUserInfoService.cs:66-78
    — picks UID vs UIN form based on which input is set.

Changes:

  - `proto-defs/oidb-actions/base.ts`: add `OidbUserInfoByUidRequest`
    (same shape as the UIN variant but field 1 is `uid: string`).
  - `bridge/oidb-services/contacts/fetch-user-profile-by-uid.ts`:
    new namespace at 0xFE1_2 with UID-form encoding, no `uinForm`.
  - `bridge/msg-push/decoders/group-join-request.ts`: 3 decoders'
    `resolveUidToUin` fallbacks change `ctx.fromUin` → 0.
  - `bridge/packet-pipeline.ts`: new `resolveStrangerProfile(uid)`
    dep + `needsStrangerResolve` check + async dispatch that fires
    the lookup before emitting the event. Fail open if the lookup
    rejects (event still ships with `fromUin=0` so the OneBot bot
    can fall back to the uid in the flag).
  - `core/bridge/apis/contacts.ts`: `fetchUserProfileByUid(uid)`
    facade method.
  - `core/bridge/bridge.ts`: wire `resolveStrangerProfile` into the
    pipeline deps so it routes through the new namespace.

Tests:
  - UID-form namespace: declares the right cmd/subcmd, packages uid
    as field 1, decodes nickname + uin so the pipeline patch works.
  - Pipeline stranger resolve: patches event.fromUin from the
    resolver response; fails open on null / throw; skips the wire
    call when fromUin is already populated or fromUid is empty.

All 655 tests pass (was 645 + 10 new); typecheck + lint clean.
2026-05-23 17:15:59 +08:00
DrSmoothl cd9403f27a fix(forward): align resid+uniseq for nested forwards
Multi-layer 合并转发 was uploading correctly but the outer's
LongMsgResult piggyback was *unreachable* by the receiver because
two things were missing:

  1. The forward preview element was emitted as the old XML
     `richMsg serviceID=35 m_resid=…` shape, which carries the
     inner resId but has NO uniseq field.
  2. The piggyback `actionCommand: <uuid>` slot generated a fresh
     UUID that was never reflected into the preview either.

Result: QQ-NT receivers saw the inner preview's resid, scanned the
outer's actions[] for a matching uniseq, found none, and either
fell back to a fresh server fetch per layer or dropped the layer
entirely.

Cross-checked against:
  - dev/Lagrange.Core/Lagrange.Core/Message/Entity/MultiMsgEntity.cs:43-115
  - dev/NapCatQQ/packages/napcat-core/helper/forward-msg-builder.ts:52-122
  - dev/NapCatQQ/packages/napcat-onebot/action/msg/SendMsg.ts:208-347

Both upstream impls use the modern `com.tencent.multimsg` LightApp
JSON whose `meta.detail.uniseq` is the round-trip key that links
the inner preview to the matching `actionCommand` in the outer's
LongMsgResult — no separate fetch needed.

Changes:
  - `element-builder.makeForwardElem` now emits a deflated
    `com.tencent.multimsg` LightApp JSON (LightAppElem, field 51)
    instead of the XML RichMsg (field 12). `forwardUuid` on the
    MessageElement is baked into `meta.detail.uniseq` and
    `extra.filename`. Auto-generates a UUID when absent.
  - `MessageElement.forwardUuid?: string` added for the round-trip.
  - `forward.uploadRecursive` threads `inner.uuid` into the outer's
    preview element AND uses the same uuid for the outer's
    piggyback actionCommand — closing the receiver-side lookup loop.
  - `forward.fetch` now walks ALL actions (not just `MultiMsg`),
    indexes piggybacks by uuid, and pre-populates the cache for
    each inner resId discovered in the outer's preview bubbles.
    Follow-up `fetch(innerResId)` hits the cache instead of the wire.
  - `rich-body-decoder` parses LightApp JSON; when `app ===
     com.tencent.multimsg`, emits `{type: 'forward', resId,
     forwardUuid}` so the OneBot layer can walk in. Legacy XML
     serviceID=35 path stays as a fallback for mobile QQ senders.

Wire-byte tests cover:
  - send: lightApp.data is 0x01-prefixed deflated JSON with the
    right meta + extra fields
  - send/nested: outer LongMsgResult carries `MultiMsg` AND a
    uuid-keyed piggyback; the piggyback uuid matches the
    preview's `meta.detail.uniseq` baked into the same outer
    msgBody
  - send/3-deep: outermost action[] has 1 + 2 entries (own
    MultiMsg + 2 piggybacks hoisted from deeper levels)
  - recv: lightApp `com.tencent.multimsg` → forward element with
    both resId and forwardUuid; non-multimsg LightApp falls
    through to {type:'json'}; legacy XML path still emits
    {type:'forward'}.

641 tests pass (was 628 + 13 new); typecheck clean; lint clean.
2026-05-23 12:45:26 +08:00
DrSmoothl 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.
2026-05-23 00:22:59 +08:00
DrSmoothl 8d22868777 refactor(oidb): migrate group-admin.ts OIDB cmds to namespaces
Splits the 14 OIDB cmds from GroupAdminApi into self-contained
namespaces under @snowluma/bridge/oidb-services/group-admin/. The
facade becomes one-line forwarders; per-cmd capability is narrowed
to OidbSender (+ resolveUserUid / identity where the cmd actually
needs it).

Notes:
  - 0x89A_0 hosts MuteAll, SetAddOption, SetSearch, SetGroupName —
    same (cmd, subcmd) tuple, four different proto bodies; each gets
    its own namespace so proton can monomorphize independently.
  - 0x8A0_1 splits KickMember (single) and KickMembers (batch) for
    the same reason.
  - SetAddRequest carries uinForm=true and dynamic subCommand
    (filtered ? 2 : 1) on the same namespace.
  - GetAtAllRemain needs the bot's own uin → declares
    Pick<BridgeContext, 'identity'> in its Deps.

Wire-byte equivalence preserved; corner case for getAtAllRemain
empty-envelope path now returns {false, 0, 0} instead of throwing —
the new infrastructure normalises empty bodies and the OneBot action
ergonomics are unchanged.
2026-05-23 00:06:40 +08:00
DrSmoothl 014b87c7ce refactor(oidb): migrate contacts.ts OIDB cmds to namespaces
6 OIDB cmds moved; pagination + per-group cache + inflight
coalescing stay on the facade because they need cross-call state.

  - FetchFriendListPage       (0xFD4_1) — facade drives the cursor loop
  - FetchGroupList            (0xFE5_2) — uinForm; verbatim config blob
  - FetchGroupMemberListPage  (0xFE7_3) — facade drives the token loop +
                                          owns the TTL cache + inflight
                                          coalescing that keeps busy
                                          OneBot clients from tripping
                                          Tencent risk-control
  - FetchUserProfile          (0xFE1_2) — uinForm; full property-key
                                          catalogue cross-checked against
                                          LagrangeV2 FetchStrangerService.cs
  - FetchGroupRequests        (0x10C0_1/_2) — dynamic subcmd via filtered flag
  - FetchDownloadRkeys        (0x9067_202) — uinForm; respHead.retCode
                                             check moved into deserialize

35 new namespace-level tests covering serialize / deserialize edge
cases (property decoding, sex enum mapping, avatar URL suffix,
empty body handling, pagination cursor behaviour).

Verification:
  - typecheck green
  - @snowluma/bridge: 30 files / 233 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:51:33 +08:00
DrSmoothl 80afa31f5c refactor(oidb): migrate extras.ts OIDB cmds to namespaces
5 logical OIDB cmds → 4 namespace files (group todo's 3 sub-cmds
collapse into one namespace with a dynamic resolver):

  - GroupTodo          (0xF90_1/2/3) — set/complete/cancel via the
                                       new `action` discriminator
  - GetStrangerStatus  (0xFE1_2)     — uinForm=true; preserves the
                                       (status*10, ext_status) decode
                                       quirk verbatim
  - FetchAiVoiceList   (0x929D_0)
  - FetchAiVoice       (0x929B_0)    — single poll; retry loop
                                       stays on the facade so callers
                                       can plug their own back-off

Facade keeps the 6 public methods (setGroupTodo / completeGroupTodo /
cancelGroupTodo / getStrangerStatus / fetchAiVoiceList / fetchAiVoice)
as one-line forwarders; only `getStrangerStatus` wraps in try/catch
to preserve its "return null on transport failure" contract, and
`fetchAiVoice` keeps the polling loop.

30 new namespace-level tests; extras.test.ts moved onto the
sendRawPacket assertion model.

Verification:
  - typecheck green
  - @snowluma/bridge: 24 files / 195 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:45:13 +08:00
DrSmoothl 8356121518 refactor(oidb): migrate web.ts OIDB cmds to namespaces
2 OIDB cmds moved (the only OIDB calls in this file — the rest are
HTTP cookie / qun.qq.com / qzone web requests):

  - ForceFetchClientKey (0x102A_1) — used by ptlogin2 jump flow to
                                     swap clientKey → cookie jar
  - GetPskey            (0x102A_0) — p_skey fallback when ptlogin2
                                     omits it

The private `forceFetchClientKeyInner` / `getPSkey` helpers in
WebApi are now one-line forwarders into the namespaces. Facade
methods (`getCookies`, `getCsrfToken`, `getCredentials`, etc.) and
all HTTP-only cmds untouched.

12 new namespace-level tests covering deserialize edge cases
(empty server response, missing fields, dropped invalid items)
and e2e wire routing.

Verification:
  - typecheck green
  - @snowluma/bridge: 20 files / 165 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:40:17 +08:00
DrSmoothl 58e8081420 refactor(oidb): migrate misc.ts OIDB cmds to namespaces
3 OIDB cmds migrated; the 1 non-OIDB cmd (getMiniAppArk via
LightAppSvc) stays on the facade unchanged.

  - TranslateEnToZh           (0x990_2)
  - ClickInlineKeyboardButton (0x112E_1)
  - SendGroupSign             (0xEB7_1) — preserves historic UPPERCASE
                                          EB7 wire name via the new
                                          `wireName` override (the only
                                          cmd in the codebase with this
                                          quirk; every other cmd uses
                                          the default lowercase).

Tests:
  - misc.test.ts moved to bridge.sendRawPacket assertion model
  - 18 new namespace-level tests covering serialize, deserialize edge
    cases, magic constants, BigInt widening, and the EB7 case quirk

Verification:
  - typecheck green
  - @snowluma/bridge: 18 files / 153 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:37:41 +08:00
DrSmoothl f78431242c refactor(oidb): migrate friend.ts to namespaces
3 OIDB cmds moved to self-contained namespaces:
  - HandleFriendRequest (0xB5D_44) — digit-only flag still
                                     auto-resolves via resolveUserUid
  - DeleteFriend        (0x126B_0) — verbatim magic constants in the
                                     nested field2 sub-message
                                     (130/109/8/8/50 — server-side
                                     discriminator, MUST stay byte-
                                     equal to NTQQ wire)
  - SetFriendRemark     (0xB6E_2)

Cache invalidation (fetchFriendList after deletion) stays in the
facade — that side-effect needs `ctx.apis.contacts`, which namespaces
deliberately can't reach.

Tests migrated to assert against bridge.sendRawPacket. 15 new
namespace-level tests covering each invoke branch + serialize edge
cases.

Verification:
  - typecheck green
  - @snowluma/bridge: 15 files / 133 tests
  - friend.test.ts: 5/5
Wire bytes unchanged.
2026-05-22 23:33:22 +08:00
DrSmoothl a38f7ea26e refactor(oidb): migrate profile.ts OIDB cmds to namespaces
5 of profile.ts's methods were thin OIDB wrappers — migrated to the
new namespace pattern. The 5 non-OIDB methods (setOnlineStatus /
setDiyOnlineStatus / setAvatar / setGroupAvatar / fetchCustomFace)
stay on the facade unchanged — they hit `trpc.qq_new_tech.*`,
Highway, or `Faceroam.OpReq` directly and aren't in scope for the
OIDB-namespace refactor.

New namespaces (each with focused Pick<BridgeContext, …> deps):
  - SetProfile               (0x112A_2)  — needs identity for uin
  - SetSelfLongNick          (0x112A_2)  — same cmd different proto, ditto
  - SetInputStatus           (0xCD4_1)   — needs resolveUserUid
  - GetLike                  (0x7ED_12)  — needs identity + resolveUserUid
  - GetUnidirectionalFriendList (0xE17_0) — needs identity; non-standard
                                            wire name handled via the new
                                            wireName override on OidbCallSpec

Infrastructure tweak:
  - OidbCallSpec gains an optional `wireName(cmd, sub) → string`. Most
    cmds use the default `OidbSvcTrpcTcp.0xNNNN_N` scheme; 0xe17_0
    routes through `MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`.

Test mock updates:
  - profile.test.ts moves the migrated cmds onto bridge.sendRawPacket
    mock (the new path bypasses the bridge-oidb runOidb mock). Non-OIDB
    cmds (setOnlineStatus, setAvatar, etc.) keep their existing mocks.
  - 36 new namespace-level tests in @snowluma/bridge covering serialize
    branches, deserialize edge cases, deps resolution, and e2e wire
    routing.

Verification:
  - pnpm -r typecheck: green
  - @snowluma/bridge: 12 files / 118 tests
  - @snowluma/core: 33 files / 302 tests
Wire shape unchanged across migrated cmds — same bytes produced.
2026-05-22 23:29:55 +08:00
DrSmoothl ff2b902cbd refactor(oidb): migrate interaction.ts remaining 3 cmds to namespaces
Completes the InteractionApi facade — every method is now a one-line
forwarder. New namespaces:
  - SendPoke   (0xED3_1)  — group + friend variants discriminated by
                            which of groupUin/friendUin is set
  - SendLike   (0x7E5_104) — thumbs-up to a target user
  - SetEssence (0xEAC_1/_2) — set/unset essence message, dynamic subcmd

Facade methods reduced to thin forwarders, mirror-fixed comment block
removed (the namespaces now own the wire-shape commentary).

Tests: 28 new in @snowluma/bridge covering each namespace's serialize
edge cases + dynamic subcmd resolution + e2e wire name + envelope body
shape. Cleaned the legacy `vi.mock('bridge-oidb')` setup out of
interaction.test.ts — the post-migration path doesn't route through
the mocked symbols anymore.

Wire behavior unchanged: every cmd produces the same bytes as before,
verified by encode round-trip in the unit tests.
2026-05-22 23:22:26 +08:00
DrSmoothl 0238bcb280 refactor(oidb): namespace-per-cmd service layer — vertical slice (3 cmds)
Introduce a new way to organise OIDB cmd implementations:

  - one TypeScript namespace per (cmd, subcmd) tuple
  - the namespace's exported members ARE the OidbCallSpec (structural
    typing — no `implements` clause)
  - a single invokeOidb() template method drives every call:
    envelope build → encode → send → errorCode check → decode →
    deserialize transformation
  - each namespace declares its own minimal `Deps` capability via
    Pick / intersection on BridgeContext (Interface Segregation):
    most cmds need only OidbSender (the `sendRawPacket` method)

The facade Api classes (InteractionApi etc.) stay for now, with the
migrated methods reduced to one-line forwarders that hand off to the
namespace. Callers still write `bridge.apis.X.Y(...)`; the OIDB
wire-encoding work just moved to a self-contained file per cmd.

Vertical slice scope: 3 cmds (the reaction line)
  - SetReaction              (0x9082_1 / _2; dynamic subcmd)
  - FetchReactionSummary     (0x9084_1)
  - GetEmojiLikes            (0x9083_1; legacy stub)

Infrastructure:
  - new packages/bridge/src/oidb-service.ts:
      OidbSender (sendRawPacket-only capability),
      OidbCallSpec<TReq, TResp, TParams, TResult>,
      invokeOidb(), buildOidbRequest(), parseOidbResponse(), OidbError
  - runOidb() refactored to accept OidbSender instead of BridgeContext
    (structurally compatible — no caller changes anywhere)
  - new OidbEmpty placeholder type in proto-defs/oidb.ts for cmds whose
    response carries no body (proton needs a real message interface,
    not `void` / `never`)
  - empty-body responses substituted with {} in invokeOidb so
    deserialize always receives a defined object

Tests (65 in @snowluma/bridge, all green):
  - oidb-service.test.ts (20): every helper branch — static + dynamic
    subcmd, uinForm flag, error code propagation as OidbError, empty
    body substitution, sender failure modes (success=false /
    gotResponse=false / both with and without errorMessage),
    timeoutMs propagation
  - set-reaction.test.ts: const declarations, dynamic subcmd both
    ways, type=1/2 boundary on code length, e2e envelope inspection
  - fetch-reaction-summary.test.ts: BigInt serialization, catalog-tail
    filtering, default emojiId/Type/lastReactionTime
  - get-emoji-likes.test.ts: BigInt serialization, default count /
    emojiType, base64 cookie round-trip, uin=0 filtering, isLast
    computation, e2e

Existing interaction.test.ts moved off the now-bypassed runOidb mock
onto sendRawPacket mock (the new invokeOidb path routes there).

Workspace-wide typecheck: green. Workspace test totals:
  proton  99/99, bridge 65/65, core 302/302, onebot 257/257
  (1 pre-existing onebot suite failure, network-manager native addon
  load — unrelated to this change.)
2026-05-22 23:15:20 +08:00
DrSmoothl c3675aef7c feat(emoji-like): back fetch_emoji_like / get_emoji_likes with a local cache
Two rounds of production wire-level probing established that the OIDB
SSO path cannot surface the reactor user list for an emoji:

  - 0x9083_1                  → 4-byte ack `18 01 20 01` (no list)
  - 0x9084_1                  → per-emoji summary (count + timestamp,
                                still no user IDs)
  - 0x9082_3..5, 0x9083_0/2/3, 0x9084_2..5, 0x9085_1/2, 0x9087_1
                              → "no privilege" — the cmds exist but
                                aren't in NTQQ's client capability
                                bitmap, so the server blocks anything
                                not registered at login. NTQQ itself
                                serves getMsgEmojiLikesList from a
                                wrapper-internal cache, not SSO.

Mirror that wrapper-cache approach on the OneBot side. SnowLuma
already receives GroupMsgEmojiLikeEvent push events for every
reaction add/remove (with operator uin + uid + emoji + msgSeq); we
just weren't persisting them. Now we do.

Changes:

* proto-defs: add Oidb0x9084 Req/Resp schema for the summary call.
  RespEntry's lastReactionTime/count are optional because the
  "available reactions catalog" tail entries omit both — only the
  "used" subset carries metadata.

* core InteractionApi: revert the 9-candidate probe loop, restore a
  single 0x9083_1 call as a legacy stub (returns empty list, with a
  debug-level hex dump on empty responses), and add
  fetchReactionSummary() that calls 0x9084_1 and yields the per-emoji
  summary (count + last-reaction timestamp).

* onebot ReactionStore: new SQLite-backed cache, schema
  reactions(group_id, msg_seq, emoji_id, emoji_type, operator_uin,
  operator_uid, set_at), PK on (group_id, msg_seq, emoji_id,
  operator_uin). Mirrors MessageStore design — prepared statements at
  construction, WAL journal.

* onebot event-pipeline: subscribe group_msg_emoji_like, call
  reactionStore.recordAdd / recordRemove before convertAndDispatch so
  a fetch_emoji_like racing with the push still sees the new row.

* onebot instance / instance-context: own the ReactionStore, expose
  it on OneBotInstanceContext, close it on dispose. New
  fetchEmojiLikeUsers helper on ApiActionContext combines local-cache
  reads with a 0x9084_1 cross-check so callers can detect cache gaps
  (events missed before bot boot, etc).

* onebot actions: get_emoji_likes and fetch_emoji_like now read from
  the cache. fetch_emoji_like's NapCat-style cookie becomes a numeric
  offset for cache pagination (no real cursor needed against local
  SQLite).

* tests: 7 new ReactionStore unit tests (CRUD + pagination +
  cross-key isolation + summarizeMessage). Existing event-pipeline
  test harness picks up a no-op ReactionStore stub.
2026-05-22 22:08:45 +08:00
DrSmoothl 65636953e7 chore(interaction): round-2 cmd probe — focus on 0x9084 family
Round-1 wire dump revealed:
  - 0x9083_1 returns a 4-byte ack (`18 01 20 01`), no user data
  - 0x9082_3/_4, 0x9083_0/_2/_3 all return "no privilege" (server-side
    deny linked to iwiki.woa.com permission docs)
  - 0x9084_1 returns 932 bytes — a real reaction *summary* on the
    message: first entry carries (timestamp, count, type, emoji_id)
    for the used emoji ("76" with count=3 in our test), followed by
    a 28-entry catalog of available reaction emojis. NOT a user list,
    but proves 0x9084 family has live handlers.

The "fetch users who reacted with emoji X" sibling is almost
certainly another subcmd of 0x9084. Probe the immediate neighborhood:

  0x9084_2..5   first-choice candidates (sibling subcmds)
  0x9085_1..2   exploratory adjacent cmd
  0x9086_1, 0x9087_1  wider probe
  0x9084_1      kept at end so we still capture the summary baseline
2026-05-22 21:38:13 +08:00
DrSmoothl 7e3e833f84 chore(interaction): probe 7 OIDB cmd candidates per fetch_emoji_like call
Replace the env-driven probe with an unconditional round-robin across
the candidate list every fetch_emoji_like invocation:

  0x9083_1  baseline (returns 4-byte ack, known not to be fetch)
  0x9082_3  sibling of set/unset reaction
  0x9082_4
  0x9083_0
  0x9083_2
  0x9083_3
  0x9084_1  exploratory

For each candidate the cmd, response length, parsed user count,
request hex, and response hex are dumped at debug level. The first
candidate that surfaces users wins and is returned; failures inside
runOidb (server-side error code, no handler) are caught + continued
so a bad cmd in the middle doesn't tank the whole probe.

fetch_emoji_like is user-triggered ("view who reacted"), so the
extra SSO traffic on each call is acceptable for a debug build —
we only need one production hit to identify the real cmd.
2026-05-22 21:13:37 +08:00
DrSmoothl a24272b25a chore(interaction): env-driven cmd/subcmd override for fetch_emoji_like probing
Wire dump from production confirmed 0x9083_1 is a real server endpoint
(routed, errorCode=0, trace string echoes "OidbSvcTrpcTcp.0x9083_1")
but its reply is always a 4-byte minimal ack `18 01 20 01` regardless
of message / emoji / whether the caller just set a reaction — so the
semantics of 0x9083_1 are not "fetch emoji-like users". The real cmd
must be a sibling (0x9082_3, 0x9082_4, 0x9083_2, 0x9083_3, …) but we
don't yet know which.

Rather than rebuild for each candidate, accept an env override
`SNOWLUMA_EMOJI_FETCH_CMD=0x9082_3`. Format is `0xNNNN_N`; a malformed
value warns and falls back to the historic 0x9083_1. Wire name is
recomputed from the parsed (cmd, subcmd) so the trpc routing matches
the OIDB envelope cmd field.

Also unconditionally dump req/resp hex at debug level while we're
probing — once we land on a working tuple the dump can be tightened
back to "only on empty users". The pre-existing log line is widened
to include the wire name and the result count so deployment can scan
multiple cmd values from a single log stream.
2026-05-22 21:10:39 +08:00
DrSmoothl 2638d13d11 feat(profile): surface QQ level from OIDB 0xFE1_2 number-property 105
`fetchUserProfile` already requested key 105 in the keys[] array but
the decode pass never read it, so callers got nothing. NapCat exposes
the same value as `qq_level` on `get_stranger_info`; users coming from
NapCat noticed the field was missing on the SnowLuma side.

Cross-checked against LagrangeV2 Internal/Services/System/
FetchStrangerService.cs which explicitly labels key 105 = Level and
uses `numbers[105]` directly.

Changes:
- UserProfileInfo: add `level: number`.
- fetchUserProfile decode: `info.level = numMap.get(105) ?? 0`.
- getStrangerInfo: emit both `qq_level` (NapCat-compat) and `level`.
- Test/manager call sites updated for the new required field.
2026-05-22 19:02:05 +08:00
DrSmoothl ce78a3bbdf fix(oidb): update sequence type in Oidb0x9083Req to uint_64 for compatibility 2026-05-22 08:09:29 +08:00