Compare commits

...
60 Commits
Author SHA1 Message Date
snowluma-bot[bot] 7d90820e19 Merge pull request #100 from SnowLuma/dev
chore: promote dev → main (ee8eb92)
2026-06-14 08:29:02 +00:00
DrSmoothl ee8eb928b3 chore(release): v1.9.10 2026-06-14 16:28:39 +08:00
DrSmoothl 8f61b1486e feat(webui): Apple-style overview pass + roomier stat tiles
- Grid row height 80→108px so a 1-row stat tile's icon + 3 text lines clear
  the padding with real breathing room (the previous fix still clipped ~8px);
  stat tile gets an airier layout (size-10 icon, text-lg value, py-3.5).
- Carry the app's Apple language across the homepage: inner surfaces and
  empty-state containers round to xl, empty-state icons calm to size-8/opacity,
  edit hint + first-run nudge rounded consistently.
2026-06-14 16:20:19 +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 84021a19dc feat(webui): deep-link settings tabs via ?tab= and jump update banner to 关于
The settings sub-tab now lives in the URL (typed `?tab=` search param on the
/settings route, validated against the tab whitelist; default 外观 omits it).
The active tab is derived from the URL and tab clicks navigate (replace), so
tabs are shareable/back-button friendly. The sidebar "有新版本可用" banner now
links to /settings?tab=about, landing directly on 关于 (where 软件更新 lives)
instead of the default settings tab.
2026-06-14 15:45:42 +08:00
DrSmoothl df0b79a87d feat(webui): restyle login page with Apple-style vibrancy
- Frosted "vibrancy" card (bg-card/65 + backdrop-blur-2xl) floating over the
  wavy background, with a centered brand focal point (logo tile, name,
  version, subtitle).
- Larger rounded fields/button (h-12, rounded-xl) for a calmer iOS feel.
- The "我觉得这个界面很卡怎么办?" help line becomes a 灵动岛-style frosted
  capsule (rounded-full, blur, float, spring on hover/tap).
- New entrance/hover motion gated on reduceMotion/disableMotion.
2026-06-14 00:47:56 +08:00
DrSmoothl dc26cc93ba fix(webui): hide native Edge password reveal control on login
The login password field showed two eye icons — our custom show/hide
toggle plus Edge/IE's native ::-ms-reveal. Hide the native reveal/clear
pseudo-elements so only our toggle remains.
2026-06-14 00:46:46 +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 9dd46198cb feat(webui): custom scrollbars + sliders, stat-tile fit, reduce-motion
- Scrollbars: theme native scrollbars (thin, token-colored thumb) for plain
  overflow containers; Radix ScrollArea keeps its own custom bar (it hides
  the native one, so no double bar).
- Sliders: new <Slider> component + `.slider` CSS replaces the native range
  inputs (UI scale / mask opacity / blur). Filled track + ring-bordered
  thumb, themed; input height matches the track so the thumb centers in every
  engine; Firefox fills via ::-moz-range-progress.
- Stat tiles: tighten the h=1 tile (py-2 + mt-0.5) so the three text lines +
  padding fit the 80px cell without hugging the border.
- Reduce motion: gate the always-present sidebar-width + page-transition
  animations to instant when enabled (Framer's reducedMotion only suppresses
  transforms, so these needed an explicit opt-out); kill the slider thumb
  transition too.
2026-06-14 00:16:26 +08:00
DrSmoothl 7d647e0ed7 feat(webui): redesign settings About panel in the Apple style
Split the single centered card into a clean three-section stack consistent
with the rest of settings:

- Brand hero card: logo glow + name + version pill + tagline/description.
- "软件更新" grouped list (reuses Group/SettingRow): current-version row +
  check-update row (status dot/spinner + 重新检查); when an update exists, a
  tinted detail block with version, notes, platform asset hint and 前往下载.
- Support card: refined Star CTA + repo/releases/issues links.

UpdateStatus → UpdateGroup; all update states (checking/disabled/error/
latest) preserved.
2026-06-13 23:50:55 +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 de598242ab feat(webui): apply Apple-style polish to processes + config pages
Carry the logs/settings visual language across the remaining pages:

- Processes: sort control becomes a segmented radiogroup; action banner
  gains a spinner; cards round to xl with a hover tint; calmer empty state.
- Config: save status collapses from bordered pills into one inline
  dot/spinner indicator; node summary rows round to xl with hover and
  fold the three flag badges into a single muted "数组 · 不上报自身 · 已设
  Token" line; empty states round to xl; account rail rounds to xl.

Presentational only — all state wiring and handlers unchanged.
2026-06-13 23:25:11 +08:00
DrSmoothl 3d480fb018 feat(webui): redesign settings page with macOS-style two-pane UX
Rework the settings page around the macOS System Settings layout, reusing
existing UI tokens (no new deps):

- Two-pane: a sticky left nav rail (w-52) on lg, a wrapping tab strip on
  mobile. Active section mirrors the app sidebar's selected style.
- Grouped inset lists: each Card is a header above a hairline-divided list
  of label-left / control-right rows (SettingRow: auto / inline / stack),
  replacing the stacked Field + Separator spam.
- Refined segmented control: recessed track with a raised pill on the
  selected segment (font-semibold + full ring so it survives high-contrast
  / OLED); exposed as a proper radiogroup (role=radio + aria-checked) and
  named via the row label through a small context + useId.
- Per-section fade transition; section heading anchors the detail pane.

Wide controls (时制, 深色强度, fonts, radius scale, poll interval, default
route) stack so they don't crowd their labels; password-saved confirmation
keeps its success color. All settings preserved 1:1.
2026-06-13 23:15:38 +08:00
DrSmoothl 5b253ea1d5 feat(webui): redesign logs page with Apple-style UX
Rework the run-log viewer around progressive disclosure and a calmer,
content-first hierarchy, reusing existing UI tokens (no new deps):

- Toolbar: live status dot (red when disconnected) replaces the badge;
  real search field with inline icon + clear; icon-only actions with
  tooltips, grouped (toggles in a track · divider · data actions).
- One always-visible segmented level filter (iOS-style raised pill +
  colored dot) instead of strikethrough pills.
- Collapse the server-level switch + highlight-rule editor into a single
  animated "选项" panel; server level also surfaced in the subtitle. The
  control area drops from three rows to one.
- Log stream: subtle sticky column header (时间/级别/模块/消息) aligned to
  rows via a sm:contents trick, dot-style level indicators, hairline row
  separators, and distinct empty / no-match states.

a11y: radiogroup on color swatches, aria-pressed on level toggles,
unique remove-button labels, focus rings on all controls.
2026-06-13 23:00:22 +08:00
DrSmoothl a61e0a253d feat(webui): in-place dashboard edit overlays + inline sidebar reorder
Rework the layout edit mode from a separate panel to in-place affordances:
- Each dashboard widget gets a semi-transparent floating overlay in edit mode:
  a "拖动" grip bar (the whole card is the drag target — forgiving +
  discoverable), an eye to show/hide, and a gear that opens the per-widget
  settings in a dialog. Hidden widgets show as re-enableable "已隐藏" ghosts;
  the bottom-right resize grip is now clearly visible.
- The sidebar nav becomes a drag-to-reorder list directly in the sidebar
  (show/hide + locked pinned items + a 完成 button); editing force-expands the
  sidebar (and disables the collapse toggle). Edit mode is a shared
  LayoutContext flag so one "编辑布局" toggle drives both the grid and the nav.
- The separate editor panel (overview-layout-editor) is removed; the gear
  opens config in a dialog instead.

Also: stat-tile typography tightened (leading-tight, smaller value, overflow
clip) so text no longer hugs the edge on small/short tiles. Verified by an
adversarial review round (no MUST-FIX).
2026-06-13 21:45:41 +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 a5335687ec fix(protocol): fetch group-join verify comment regardless of uin cache (#98)
The verify text a user types when requesting to join a group is never in the
push — it lives on the OIDB pending-request queue. The fetch
(resolveGroupJoinRequest) was gated behind the UID→UIN stranger-resolve, so
when the requester's uin was already cached the whole async path (and thus the
comment fetch) was skipped, leaving the OneBot request.group `comment` empty.

Decouple the two: every uid-bearing group_invite now goes through the async
enrich path (needsGroupInviteEnrich → dispatchGroupInvite), which ALWAYS
fetches the comment and resolves the UIN profile only when needed (the
fromUin === groupId cache-pollution self-heal is preserved). Matches
Lagrange's unconditional FetchGroupRequests and NapCat's notify.postscript.

Rewrites the cache-hit test (which had pinned the buggy behavior) into a
regression asserting the comment is fetched + applied on a cache hit.
346/346 protocol tests pass. Verified by adversarial review.
2026-06-13 12:03:04 +08:00
DrSmoothl 69ed8fc722 feat(webui): customizable dashboard + nav layout (phase 3)
The "C" half — reorder + show/hide the overview cards and the sidebar nav,
persisted to config/ui.json's layout section.

- LayoutContext loads the layout (authed GET /api/ui) and persists edits via
  the section-merge POST /api/ui {layout} (debounced). reconcileLayoutItems
  keeps stored order/visibility, appends new catalogue entries (forward-compat),
  and forces pinned items visible.
- Overview is refactored into a block registry (stats/connections/alerts/host/
  sessions). A 「编辑布局」 mode (motion Reorder — zero new deps) edits both the
  cards and the nav in place, with per-item show/hide and a reset; an all-hidden
  dashboard shows an empty state with 恢复默认.
- Anti-self-lock: PINNED_NAV = ['/', '/settings'] can be reordered but never
  hidden — the overview hosts the layout editor and settings hosts
  account/appearance, so the user can never strand themselves.
- api.ui.save now takes Partial<UiConfig> (the section-merge contract).

A late initial GET can't clobber an in-flight edit (dirtyRef); a pending edit
flushes on unmount. Verified across 2 adversarial review rounds.
2026-06-13 01:15:00 +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 043ce779e6 fix(onebot): ignore close events from stale ws-client sockets (#97)
A hot reload that changes the binding signature (url / role / accessToken
/ reconnectIntervalMs) drives `await this.close()` then `await this.open()`
back-to-back. `WsClientAdapter.close()` is synchronous and `WebSocket.close()`
just schedules the close frame, so the OLD socket's `'close'` event fires
AFTER the new socket has already been assigned to `this.socket`.

The close handler did not check the event's origin, so it would null out
`this.socket`, drop `connected`, and schedule an unwanted reconnect against
the freshly-opened connection. Against a single-connection backend that
kicks duplicates this snowballed into a reconnect storm where the bot and
the backend repeatedly kicked each other off; against a permissive backend
it still left the new connection in a degraded state (events couldn't be
sent until the bogus reconnect rebuilt the socket).

Add a one-line identity guard at the top of the close handler — when the
event arrives from a socket that is no longer the current one, do nothing.
The explicitlyClosed / isEnabled checks are kept as the second line of
defence for the normal (current-socket) close path.

Add three regression tests under tests/ws-client-stale-close.test.ts that
mock `@snowluma/websocket` (same approach as adapter-reload-state-machine.
test.ts, which avoids the native addon dependency): the reload race
scenario from the issue, a real-current-socket close that MUST still drive
reconnect, and a close() race against an in-flight close event.
2026-06-12 21:55:32 +08:00
DrSmoothl e9ae2ec751 feat(log): show ARK card title in JSON segment preview (#96)
The JSON segment preview was a fixed "[JSON]" placeholder, hiding both
real card titles and QQ's server-side fallback prompts (e.g. cardId
-896954183 "当前QQ版本不支持此应用,请升级", which is what #96 reported
seeing). Best-effort extract a title from the common ARK fields —
meta.{detail_1,detail,news,mannounce,music,video}.title, single-section
meta, then root.prompt / root.desc — and render as "[卡片:...]"; fall
back to "[JSON]" on parse failure or an unrecognised schema. Title is
truncated at 30 chars so a long prompt cannot blow up the log line.

OneBot segment shape is unchanged: downstream consumers still get the
full payload at data.data; this is purely a log-preview readability fix.
The helper is pure best-effort and never throws — every failure path
falls through to the existing "[JSON]" output.
2026-06-11 20:47:54 +08:00
snowluma-bot[bot] 69195ced93 Merge pull request #95 from SnowLuma/dev
chore: promote dev → main (a3a3671)
2026-06-11 08:42:47 +00:00
DrSmoothl a3a36718d6 chore(release): v1.9.9 2026-06-11 16:42:23 +08:00
游手好闲的言柒 d2a67cb560 fix(onebot): add canonical fields to file segment and fix log rendering (#94)
* fix(onebot): support inline file url/path in send_group/private_msg

* test(onebot): update file segment parser test for inline url/path support

* fix(onebot): add canonical fields to file segment and fix log rendering
2026-06-11 15:40:47 +08:00
dependabot[bot]andsnowluma-bot[bot] d804a3b2e0 build(deps-dev): bump hono from 4.12.18 to 4.12.21 (#91)
Bumps [hono](https://github.com/honojs/hono) from 4.12.18 to 4.12.21.
- [Release notes](https://github.com/honojs/hono/releases)
- [Commits](https://github.com/honojs/hono/compare/v4.12.18...v4.12.21)

---
updated-dependencies:
- dependency-name: hono
  dependency-version: 4.12.21
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: snowluma-bot[bot] <283088347+snowluma-bot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-09 17:04:41 +08:00
DrSmoothl 14e02bce3c fix(events): keep member role cache in sync on group admin change
get_group_member_info serves straight from the in-memory member cache
on its default no_cache=false path — a deliberate choice, since clients
like OlivaDice/MaiBot query it once per inbound message and a per-call
OIDB refetch trips Tencent risk-control. But the group-admin push
decoder only emitted the notice and never updated the cached role, so a
member promoted to admin kept reading back as `member` and permission
gates rejected their commands. Patch the cached role in the decoder on
set/unset, only touching members we already know and never downgrading
the owner.

Also fix promote/demote misdetection: proton materializes an absent
embedded-message field as an empty `{}` rather than undefined, so the
old `extraEnable !== undefined` test was always true — every demote was
reported as a promotion with a fallback userUin. Key off whichever
sub-message actually carries an adminUid instead.

Fixes #93
2026-06-09 16:30:10 +08:00
snowluma-bot[bot] d2c56d565b Merge pull request #92 from SnowLuma/dev
chore: promote dev → main (d508814)
2026-06-09 06:23:12 +00:00
DrSmoothl d508814dfa chore(release): v1.9.8 2026-06-09 14:22:43 +08:00
snowluma-bot[bot] ac049e5cc1 chore(native): replace native artifacts (native-886e60a) (#90)
Source: SnowLuma/nnphook@886e60a271
Build:  https://github.com/SnowLuma/SnowLumaNative/releases/tag/native-886e60a

Co-authored-by: snowluma-bot[bot] <283088347+snowluma-bot[bot]@users.noreply.github.com>
2026-06-08 00:13:38 +08:00
snowluma-bot[bot] cc27cd1f43 Merge pull request #89 from SnowLuma/dev
chore: promote dev → main (515bac4)
2026-06-07 14:30:05 +00:00
DrSmoothl 515bac4b3c chore(release): v1.9.7 2026-06-07 22:29:37 +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
snowluma-bot[bot] 40c65c87bd Merge pull request #88 from SnowLuma/dev
chore: promote dev → main (174150c)
2026-06-07 13:20:48 +00:00
墨梓柒 ac39d04170 Merge branch 'main' into dev 2026-06-07 21:20:39 +08:00
DrSmoothl 174150c5e1 chore(release): v1.9.6 2026-06-07 21:19:00 +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 28db1d1079 fix(onebot): distinguish group disband from kick_me (#87)
group_decrease collapsed GroupChange.decreaseType into a single isKick boolean, so a group disband (decreaseType 129) was indistinguishable from the bot being kicked — both surfaced as kick_me.

Preserve the protocol reason as a leaveType discriminator (leave | kick | disband) on GroupMemberLeave: decreaseType 129 -> disband, 0/130 -> leave, otherwise kick. The OneBot converter emits disband, or splits kick into kick/kick_me by selfId as before. leave/kick/kick_me are unchanged.
2026-06-05 11:49:14 +08:00
DrSmoothl 966855469d ci: run the full test suite on pull requests
The repo had no PR test gate, so broken tests landed on dev unnoticed. Add a
pull_request workflow that runs `pnpm -r --no-bail --if-present test` across all
packages on ubuntu-latest (pnpm 10.28.0, Node 22), with per-PR concurrency.
2026-06-04 23:36:33 +08:00
DrSmoothl 9374b8ac64 fix(protocol): invokeOidb rejects on packet send failure (success=false)
invokeOidb only threw on success=false when an OIDB errorCode was set (the
block added in #69); a send failure with no errorCode silently resolved with an
undecoded result. Surface it — throw errorMessage || 'packet send failed',
matching runOidb and the oidb-service tests that were already red on dev.
2026-06-04 23:36:22 +08:00
ikun两年半 34ea2ce438 refactor(webui): 移除冗余的手动保存按钮喵,通用设置改为 debounce 自动保存喵 (#83)
* refactor(webui): 移除冗余的手动保存按钮喵,通用设置改为 debounce 自动保存喵

* fix(webui): 修复保存按钮状态喵,允许在自动保存时手动触发喵
2026-06-04 18:03:17 +08:00
墨梓柒 9dedcf93a8 Dev (#82)
* test(sdk): remove obsolete actions-sync guard

c49ae1c removed the SDK's hardcoded action-name list (src/actions.ts / SNOWLUMA_ACTIONS) and updated exports, but left the test that guarded it. The test imports SNOWLUMA_ACTIONS from ../src -- now undefined ("not iterable") -- and its registerAction('...') enumeration of onebot is itself stale after the declarative action-kit migration. Nothing else references SNOWLUMA_ACTIONS; the list it kept in sync no longer exists, so the guard is dead. Removing it makes the sdk suite green (16 tests).

* fix(mcp): add repository metadata so the provenance publish validates

npm publish --provenance rejected @snowluma/mcp@1.9.5 with E422 because package.json had no repository.url to match the GitHub repo asserted in the provenance statement. Add repository/homepage/bugs (mirroring @snowluma/sdk and @snowluma/ui, directory packages/mcp) and refresh the now-inaccurate 'read-only' description. 1.9.5 was never successfully published, so re-running the publish workflow will ship it.
2026-06-03 22:19:31 +08:00
DrSmoothl 0cc7ef2f30 fix(mcp): add repository metadata so the provenance publish validates
npm publish --provenance rejected @snowluma/mcp@1.9.5 with E422 because package.json had no repository.url to match the GitHub repo asserted in the provenance statement. Add repository/homepage/bugs (mirroring @snowluma/sdk and @snowluma/ui, directory packages/mcp) and refresh the now-inaccurate 'read-only' description. 1.9.5 was never successfully published, so re-running the publish workflow will ship it.
2026-06-03 22:17:58 +08:00
DrSmoothl d2097f77c8 test(sdk): remove obsolete actions-sync guard
c49ae1c removed the SDK's hardcoded action-name list (src/actions.ts / SNOWLUMA_ACTIONS) and updated exports, but left the test that guarded it. The test imports SNOWLUMA_ACTIONS from ../src -- now undefined ("not iterable") -- and its registerAction('...') enumeration of onebot is itself stale after the declarative action-kit migration. Nothing else references SNOWLUMA_ACTIONS; the list it kept in sync no longer exists, so the guard is dead. Removing it makes the sdk suite green (16 tests).
2026-06-03 22:17:58 +08:00
snowluma-bot[bot] 46cbd29956 Merge pull request #81 from SnowLuma/dev
chore: promote dev → main (4fcaba2)
2026-06-03 13:56:10 +00:00
DrSmoothl 4fcaba2f3e chore(release): v1.9.5 2026-06-03 21:55:37 +08:00
DrSmoothl 4427ecd569 docs(mcp): document execution mode (modes, env, read/write safety)
Covers the docs vs execution split, the four SNOWLUMA_MCP_* env vars, the query_action / invoke_action tools, read/write-mode example client configs, and the per-action safety model (default-write classification, the enforced mode gate, unknown-action rejection, envelope passthrough, and the readOnly/destructive annotations).
2026-06-03 21:55:05 +08:00
DrSmoothl 6d92a28e2b feat(mcp): execution mode — query/invoke OneBot actions with a read/write safety gate
@snowluma/mcp gains execution alongside the read-only catalog: when SNOWLUMA_MCP_ENDPOINT is set it exposes query_action (read-only actions, readOnlyHint) and, in write mode, invoke_action (any known action, destructiveHint), proxied to a running OneBot instance over HTTP. Without an endpoint it degrades to docs-only. SNOWLUMA_MCP_MODE (docs|read|write) gates tool visibility AND is re-checked in execute(), so an unlisted tool cannot be called; unknown/legacy actions are non-invokable.

Read vs write is classified precisely at the source: defineAction/preset gain readOnly (default false = write, the safe default), flowed through describe() into the generated catalog snapshot. 58 actions are marked read-only by what their run() actually does -- name-traps like get_ai_record (publishes to the group), request_decrypt_key (returns a DB key), and download_file (arbitrary URL + disk write) stay writes.

The HTTP call is a ~20-line fetch bridge rather than @snowluma/sdk: the SDK's published dist is bundler-only ESM (extensionless imports) that native node cannot load, and the bin stays a plain tsc build.

onebot 332 tests pass (readOnly is metadata-only, no behavior change); mcp gains 21 tests for mode gating / read-write routing / envelope passthrough / error mapping. Full workspace typecheck clean; native node smoke verified.
2026-06-03 21:53:02 +08:00
DrSmoothl 18f7d847ac refactor(onebot): lift the network adapter reload state machine into the base class
The four NetworkAdapters each carried a byte-identical reload() state machine (sigChanged/wasEnabled -> Reopened/Closed/Opened/Normal). Lift it into IOneBotNetworkAdapter as a template method; per-adapter variation is now expressed via three hooks: bindingSignature(), willEnable() (default enabled!==false; clients add && !!url), and onConfigReplaced() (post-swap side effects).

Also delete four redundant 'override get isActive()' (identical to the base getter), lift the duplicated uin-logger setup into the base ctor, and drop http-post's now-redundant signature_ cache.

NetworkReloadType is a test-observability seam -- the sole production caller (instance.applyConfigDiff) discards it -- so a new base-level test exercises all transitions directly. Behaviour-preserving: +94/-157 in src, full workspace typecheck clean, 332 onebot tests pass.
2026-06-03 20:53:36 +08:00
游手好闲的言柒 d3092a1806 fix(onebot): support inline file url/path in send_group/private_msg (#80)
file 段现接受 file/url/path(无需先 upload_group_file/upload_private_file);群走 groupFile.upload()、私聊走 uploadPrivate()(内部已 publish/sendC2c),file_id 老路径不变。含 parser 与群/私聊文件发送测试。
2026-06-03 20:00:58 +08:00
DrSmoothl 69c8960ea9 feat(mcp): @snowluma/mcp — read-only MCP server for the OneBot action catalog
A new published package that exposes every OneBot action's docs + a ready-to-use
JSON Schema to LLM clients over stdio. Tools: list_actions / get_action /
search_actions / list_categories, plus the whole catalog as a resource.

The catalog is a build-time snapshot generated from @snowluma/onebot's live
action specs (collectActionDocs()) — so it auto-tracks action add/remove and the
published package carries zero runtime dependency on the private onebot package.

action-kit enrichment (the data source):
- Field.toJsonSchema() per coercer (uint→integer/minimum:1, messageId→integer/
  not-const-0, int→min/max, string→minLength/maxLength, array→items, enum→enum).
- describe() composes a per-action inputSchema; ActionDoc gains inputSchema +
  category. action-docs.ts tags each doc with its domain category.

Wiring: onebot exports ./action-kit + ./action-docs; root build:all includes mcp;
mcp-npm-publish.yml mirrors the sdk/ui publish workflows (triggers on changes
under packages/mcp/** or packages/onebot/**, since the catalog derives from it).

onebot typecheck + 318 tests green; mcp typecheck/build/smoke green; the 142
registered OneBot action names are unchanged.
2026-06-02 22:45:30 +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 e036e70acc chore(protocol): temp-dump 0x210 subType-61 ptt-trans push body (#79)
Live testing showed the voice-to-text text is delivered via an async push
Event 0x210 subType 61 (0x3D), not the sync pttTrans.TransC2CPttReq response
(which is a fixed ~137B ack). That push has no static sys_msg_0x210_0x3d
handler — its protobuf is registered dynamically by the ptt-trans subsystem,
so RE through the std::function callback chain is impractical.

Dump the raw subType-61 body (fromUin + len + hex) once so the wire format
can be decoded from ground truth, then implement the real decoder +
request/await correlation. Temporary — to be replaced by the actual decoder.
2026-06-02 21:28:44 +08:00
DrSmoothl 92cfaf24b8 feat(log): trace the inbound receive chain (symmetric to outbound)
Sending got full-chain trace via the api-handler chokepoint; receiving had
none. Wrap convertAndDispatch — the single path every inbound message/notice
takes (decode → convert → dispatch) — as the receive-side mirror:

- When trace is live, run the chain inside a request id so the whole receive
  (incl. any rkey-fetch packets the conversion triggers) is correlated under
  one [req#N]; otherwise skip the wrap entirely (zero overhead).
- trace the raw inbound event on entry (deep render) and the converted
  post_type + elapsed on exit (or "dropped").

Reuses the existing trace/ALS/renderParamsVerbose machinery; no new mechanism.
2026-06-02 21:15:12 +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 9b92f3825d refactor(onebot): declarative action-kit for param coercion + validation
Introduce packages/onebot/src/action-kit.ts — a zero-dependency,
type-inferring declarative layer for OneBot action params. Each action
declares its param contract (f.* coercers + optional cross-field rules)
and a `run` handler that receives typed, already-validated params.
Validation failures now return BAD_REQUEST naming the offending field
instead of falling through to ApiHandler's INTERNAL_ERROR catch.

- 141/142 actions migrated to defineAction/groupAction/groupUserAction
  across info/message/friend/group-*/request/extended; only
  .handle_quick_operation stays legacy (it needs the ApiHandler instance,
  which run() does not receive).
- f.messageId() distinguishes signed/non-zero message ids from positive
  group/user ids (f.uint()); int({min:0}).default(1800) fixes duration=0
  (unmute), which the old `|| 1800` silently swallowed.
- run(p, ctx, raw) exposes the raw params as an escape hatch for the
  irregular tail (alias-key fallbacks, arbitrary objects).
- action-docs.ts renders self-generated API docs from describe().
- ApiHandler dispatch / try-catch / response-wrapping unchanged (narrow seam).

Registered action name set is byte-identical before/after (142, verified
by runtime enumeration). Typecheck clean; onebot suite green (the
pre-existing websocket native-addon test failure is unrelated).
2026-06-02 15:21:46 +08:00
124 changed files with 17405 additions and 3059 deletions

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
# Run the full workspace test suite on every pull request.
#
# The repo previously had no PR test gate, so broken tests could land on `dev`
# unnoticed — and did (protocol's oidb-service rejection path, plus an external
# contributor PR). This gates every PR on the whole suite.
#
# `pnpm -r --no-bail --if-present test` runs each package's `test` script
# (skipping packages without one); --no-bail means one failing package still
# reports the rest, and the run as a whole still fails if any package fails.
name: CI
on:
pull_request:
permissions:
contents: read
# Cancel an in-flight run when the PR gets new commits.
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run all package tests
run: pnpm -r --no-bail --if-present test
+109
View File
@@ -0,0 +1,109 @@
name: Publish MCP to npm
on:
push:
branches: [main]
paths:
- 'packages/mcp/**'
# The action catalog is generated from @snowluma/onebot's specs, so an
# action change must republish the MCP snapshot.
- 'packages/onebot/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: mcp-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build, test, and publish MCP
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check MCP
run: pnpm --filter @snowluma/mcp typecheck
- name: Test MCP (regenerates + validates the action catalog)
run: pnpm --filter @snowluma/mcp test
- name: Build MCP
run: pnpm --filter @snowluma/mcp build
- name: Check npm package version
id: npm
working-directory: packages/mcp
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish MCP to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/mcp
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## MCP npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.9.4",
"version": "1.9.10",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -8,7 +8,8 @@
"build": "pnpm --filter @snowluma/core build",
"build:sdk": "pnpm --filter @snowluma/sdk build",
"build:webui": "pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
"build:mcp": "pnpm --filter @snowluma/mcp build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter webui build",
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/bridge",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
+7
View File
@@ -465,6 +465,12 @@ export class QqHookClient extends EventEmitter {
});
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
// Always attach a handler so a rejection can never become "unhandled" (which
// crashes Node). When the pipe closes, rejectControlPending() rejects every
// pending deferred — but the reply is only `await`ed AFTER the ack, so if the
// ack fails first the reply promise is rejected with NO awaiter. The real
// `await` below still observes the value/rejection (a separate continuation).
ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ });
this.pendingAcks.set(requestId, {
resolve: ackDeferred.resolve,
reject: ackDeferred.reject,
@@ -474,6 +480,7 @@ export class QqHookClient extends EventEmitter {
let replyDeferred: Deferred<QqHookSendReply> | null = null;
if (wantReply) {
replyDeferred = createDeferred<QqHookSendReply>();
replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ });
this.pendingReplies.set(requestId, replyDeferred);
}
+65 -1
View File
@@ -1,8 +1,9 @@
import net from 'net';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client';
let tmpDir: string | null = null;
@@ -42,3 +43,66 @@ describe('listLiveLinuxPipePids', () => {
expect(probe).toHaveBeenCalledTimes(2);
});
});
describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-send', () => {
// Regression: when the control pipe closes while a send() is awaiting its
// ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The
// reply is only `await`ed after the ack, so if the ack rejects first the
// reply promise is rejected with NO awaiter — an UNHANDLED rejection that
// crashes the Node process (Docker: supervisor restarts it ~1s later; on
// Windows it just dies → "connection pipe closed", bot down). The .catch()
// guard on each deferred prevents it; without the guard this test trips the
// unhandledRejection assertion below.
it('does not raise an unhandled rejection', async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-pipe-'));
const prevRuntimeDir = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
process.env.SNOWLUMA_HOOK_RUNTIME_DIR = dir;
const PID = 778899;
const helloFrame = (): Buffer => {
const h = Buffer.alloc(40);
h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC
h.writeUInt16LE(1, 4); // PIPE_VERSION
h.writeUInt16LE(1, 6); // PipeOp.hello
h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid
return h;
};
let controlConn: net.Socket | null = null;
const controlServer = net.createServer((sock) => { controlConn = sock; sock.write(helloFrame()); });
const recvServer = net.createServer((sock) => { sock.write(helloFrame()); });
await new Promise<void>((r) => controlServer.listen(path.join(dir, `mojo.${PID}.control.sock`), () => r()));
await new Promise<void>((r) => recvServer.listen(path.join(dir, `mojo.${PID}.recv.sock`), () => r()));
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
process.on('unhandledRejection', onUnhandled);
const client = new QqHookClient(PID);
client.on('error', () => { /* socket reset on destroy — ignore */ });
try {
await client.connectAll({ recv: true });
// Start a reply-expecting send, let it reach the in-flight (awaiting-ack)
// state, then have the "hook" drop the pipe before it answers.
const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
.then(() => 'resolved' as const, (e: unknown) => e);
await new Promise((r) => setTimeout(r, 30));
controlConn?.destroy();
const outcome = await sent;
await new Promise((r) => setTimeout(r, 50)); // let Node surface any unhandled rejection
expect(outcome).toBeInstanceOf(Error);
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
} finally {
process.off('unhandledRejection', onUnhandled);
client.close();
await new Promise<void>((r) => controlServer.close(() => r()));
await new Promise<void>((r) => recvServer.close(() => r()));
if (prevRuntimeDir === undefined) delete process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
else process.env.SNOWLUMA_HOOK_RUNTIME_DIR = prevRuntimeDir;
await rm(dir, { recursive: true, force: true });
}
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/common",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
+67
View File
@@ -49,3 +49,70 @@ export function summarizeParams(params: unknown): string {
}
return out.join(' ');
}
const VERBOSE_STRING_MAX = 200;
const VERBOSE_TOTAL_MAX = 1500;
// Keys whose values must never be rendered — tokens, passwords, secrets.
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
/**
* Deep, debug-grade render of a params object for the `trace` level: shows the
* full nested structure (message segments, nested objects) so a reproduction
* is legible — unlike {@link summarizeParams}, which collapses nested values.
*
* Three guards keep it safe and bounded:
* - per-string cap (long values like base64 image data become `"…<N B>"`),
* - total output budget (so a giant payload can't flood the buffer),
* - key-based redaction (token / password / secret → `"***"`).
*/
export function renderParamsVerbose(params: unknown): string {
const seen = new WeakSet<object>();
let budget = VERBOSE_TOTAL_MAX;
const walk = (value: unknown, key?: string): string => {
if (budget <= 0) return '…';
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
if (value === null) return 'null';
if (value === undefined) return 'undefined';
switch (typeof value) {
case 'string': {
const truncated =
value.length > VERBOSE_STRING_MAX
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
: value;
const out = JSON.stringify(truncated);
budget -= out.length;
return out;
}
case 'number':
case 'boolean':
case 'bigint': {
const out = String(value);
budget -= out.length;
return out;
}
case 'object': {
if (seen.has(value as object)) return '"[circular]"';
seen.add(value as object);
const parts: string[] = [];
if (Array.isArray(value)) {
for (const item of value) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(walk(item));
}
return `[${parts.join(',')}]`;
}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(`${k}:${walk(v, k)}`);
}
return `{${parts.join(',')}}`;
}
default:
return typeof value;
}
};
return walk(params);
}
+104 -17
View File
@@ -1,7 +1,8 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
import { currentRequestId } from './request-context';
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
export interface LogEntry {
id: number;
@@ -10,6 +11,8 @@ export interface LogEntry {
scope: string;
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
uin?: number;
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
req?: number;
message: string;
line: string;
}
@@ -26,6 +29,7 @@ interface LogOptions {
const UIN_SLOT_WIDTH = 12;
const LEVEL_WEIGHT: Record<LogLevel, number> = {
trace: 5,
debug: 10,
info: 20,
success: 25,
@@ -34,6 +38,7 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
};
const LEVEL_LABEL: Record<LogLevel, string> = {
trace: 'TRACE',
debug: 'DEBUG',
info: 'INFO',
success: 'OK',
@@ -42,6 +47,7 @@ const LEVEL_LABEL: Record<LogLevel, string> = {
};
const COLOR_CODE: Record<LogLevel, number> = {
trace: 90,
debug: 90,
info: 36,
success: 32,
@@ -53,13 +59,55 @@ const COLOR_SCOPE = 35;
const COLOR_DIM = 2;
const COLOR_RESET = '\x1b[0m';
const MAX_LOG_ENTRIES = 1000;
const logEntries: LogEntry[] = [];
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
function resolveTraceBufferMax(): number {
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
}
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
/**
* Fixed-capacity circular buffer. O(1) push + eviction (no array `.shift()`),
* so the high-throughput trace stream never pays an O(n) shift per overflow.
*/
class RingBuffer<T> {
private readonly buf: (T | undefined)[];
private start = 0;
private count = 0;
constructor(private readonly cap: number) {
this.buf = new Array<T | undefined>(cap);
}
push(item: T): void {
const end = (this.start + this.count) % this.cap;
this.buf[end] = item;
if (this.count < this.cap) this.count += 1;
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
}
/** Most recent `n` items, oldest→newest. */
recent(n: number): T[] {
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
const out: T[] = new Array<T>(take);
const first = this.start + (this.count - take);
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
return out;
}
toArray(): T[] {
return this.recent(this.count);
}
get size(): number {
return this.count;
}
}
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
const traceRing = new RingBuffer<LogEntry>(TRACE_BUFFER_MAX);
const logSubscribers = new Set<(entry: LogEntry) => void>();
let nextLogId = 1;
function resolveMinLevel(): LogLevel {
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
return raw;
}
return 'info';
@@ -75,7 +123,7 @@ function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
}
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
export function getLogLevel(): LogLevel {
return currentLevel;
@@ -110,15 +158,16 @@ function currentTime(): string {
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): string {
const message = format(...args);
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
if (!useColor()) {
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
}
const cTs = ansi(COLOR_DIM, ts);
@@ -129,28 +178,46 @@ function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
: ' '.repeat(UIN_SLOT_WIDTH);
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// Console / subscriber level filter. File output is debug-and-up always;
// see log-file-transport.ts.
const passesConsole = shouldLog(level);
const message = format(...args);
const line = render(level, options, args);
// `trace` never touches disk and is the high-volume full-chain stream. When
// it won't reach the console/memory buffer either (level not dialed to
// trace), bail BEFORE format/render AND before evaluating any lazy producer
// — this is what keeps full-chain tracing ~free at the default level even
// with hundreds of groups.
if (level === 'trace' && !passesConsole) return;
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
// (and its expensive deep render) only runs now that trace is confirmed live.
let realArgs = args;
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
realArgs = (args[0] as () => unknown[])();
}
const reqId = currentRequestId();
const message = format(...realArgs);
const line = render(level, options, realArgs, reqId);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
level,
scope: options.scope,
...(options.uin !== undefined ? { uin: options.uin } : {}),
...(reqId !== undefined ? { req: reqId } : {}),
message,
line,
};
if (passesConsole) {
logEntries.push(entry);
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
// Trace gets its own ring so its volume never evicts the normal log buffer.
(level === 'trace' ? traceRing : logRing).push(entry);
for (const subscriber of logSubscribers) subscriber(entry);
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
// Strip ASCII control characters before writing to terminal to prevent
@@ -162,10 +229,11 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// File transport always sees every level (debug-and-up) for post-mortem
// value; ANSI stripping happens inside the transport. UIN routes the
// line to its per-account sub-file in addition to the shared one.
getFileTransport().write(line, options.uin);
// File transport sees debug-and-up for post-mortem value; `trace` is
// memory / WebUI only (omitted here to avoid huge on-disk volume). ANSI
// stripping happens inside the transport. UIN routes the line to its
// per-account sub-file in addition to the shared one.
if (level !== 'trace') getFileTransport().write(line, options.uin);
}
/**
@@ -179,8 +247,14 @@ export function closeLogger(): Promise<void> {
}
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
return logEntries.slice(-n);
const n = Math.max(1, Math.trunc(limit));
// Merge the normal + trace rings by id (ids are monotonic, so id order is
// chronological). The trace ring is empty unless trace level is/was active,
// so the common case is just the normal ring with no sort.
const merged = traceRing.size > 0
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
: logRing.toArray();
return merged.slice(-n);
}
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
@@ -191,6 +265,13 @@ export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
}
export interface Logger {
/**
* High-volume, memory-only diagnostic level (never written to disk). Pass a
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
* arguments (and any costly rendering) are built only when trace is active.
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
*/
trace: (...args: unknown[]) => void;
debug: (...args: unknown[]) => void;
info: (...args: unknown[]) => void;
success: (...args: unknown[]) => void;
@@ -207,6 +288,7 @@ export interface Logger {
function makeLogger(opts: LogOptions): Logger {
return {
trace: (...args: unknown[]) => emit('trace', opts, args),
debug: (...args: unknown[]) => emit('debug', opts, args),
info: (...args: unknown[]) => emit('info', opts, args),
success: (...args: unknown[]) => emit('success', opts, args),
@@ -226,3 +308,8 @@ function makeLogger(opts: LogOptions): Logger {
export function createLogger(scope: string): Logger {
return makeLogger({ scope });
}
// Request-correlation helpers live alongside the logger since `[req#N]`
// stamping is a logging concern. Re-exported here so callers import the
// whole logging surface from one place.
export { nextRequestId, runWithRequestId, currentRequestId } from './request-context';
+35
View File
@@ -0,0 +1,35 @@
import { AsyncLocalStorage } from 'async_hooks';
interface RequestStore {
id: number;
}
const storage = new AsyncLocalStorage<RequestStore>();
let counter = 0;
/**
* Allocate the next per-process request id (monotonic). Wraps via uint32 so
* it never overflows to a non-integer; `0` is skipped so "no id" stays
* unambiguous.
*/
export function nextRequestId(): number {
counter = (counter + 1) >>> 0;
if (counter === 0) counter = 1;
return counter;
}
/**
* Run `fn` with `id` bound as the ambient request id for the entire async
* chain it spawns. Any logger call anywhere in that chain — across packages,
* across awaits — picks it up via {@link currentRequestId} with no signature
* threading. Used by the OneBot action handler to correlate a request's whole
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
*/
export function runWithRequestId<T>(id: number, fn: () => T): T {
return storage.run({ id }, fn);
}
/** The request id bound to the current async context, or undefined outside one. */
export function currentRequestId(): number | undefined {
return storage.getStore()?.id;
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.9.4",
"version": "1.9.10",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -53,7 +53,7 @@
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "^24.12.2",
"cross-env": "^10.1.0",
"hono": "^4.12.18",
"hono": "^4.12.21",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
+69
View File
@@ -5,9 +5,38 @@ import {
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
import type { MediaIndexNode } from './shared';
/** Inputs for a voice-to-text request, gathered from the received `record`
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
* the uins + scene from the message meta. */
export interface PttTransInput {
isGroup: boolean;
msgId: number;
senderUin: number;
/** Receiver uin (c2c) or group uin (group). */
peerUin: number;
uuid: string;
md5Hex: string;
duration: number;
size: number;
format: number;
/** Group ptt numeric file id (group only; optional). */
fileId?: number;
}
function hexToBytes(hex: string): Uint8Array {
const s = (hex || '').trim();
if (!s) return new Uint8Array(0);
const len = s.length >> 1;
const out = new Uint8Array(len);
for (let i = 0; i < len; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
return out;
}
// ─────────────── public types (re-exported from bridge.ts as before) ───
export type StrangerStatus = NamespaceStrangerStatus;
@@ -88,4 +117,44 @@ export class ExtrasApi {
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
/**
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
* return the recognised text IF the response carries it inline (the
* already-transcribed case). For a freshly-received voice the response is an
* empty ack and the text is delivered later via the async Event 0x210
* subType-61 push — callers should treat `''` as "pending" and wait for the
* `ptt_trans_result` event (correlated by msgId). Live-verified end to end.
*/
async translatePttToText(input: PttTransInput): Promise<string> {
const md5 = hexToBytes(input.md5Hex);
const req: PttTransReq = input.isGroup
? {
type: 1,
groupItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
format: input.format, uuid: input.uuid,
},
}
: {
type: 2,
c2cItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
},
};
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'ptt translate request failed');
}
const resp = protobuf_decode<PttTransResp>(result.responseData);
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
}
}
+20 -1
View File
@@ -1,3 +1,4 @@
import { createLogger } from '@snowluma/common/logger';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
@@ -12,6 +13,7 @@ import {
} from './apis/extras';
import type { BridgeInterface } from './bridge-interface';
const log = createLogger('Bridge');
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
@@ -129,12 +131,29 @@ export class Bridge implements BridgeInterface {
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
const startedAt = Date.now();
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
const elapsed = Date.now() - startedAt;
const respLen = result.responseData ? result.responseData.length : 0;
if (!result.success || result.errorCode !== 0) {
// QQ-side rejection or transport failure — the usual root cause when an
// action misbehaves. Warn (persisted) with cmd + code so a user's log
// shows exactly where the chain broke.
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
serviceCmd, result.errorCode, result.gotResponse,
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
} else {
// Happy path — memory-only trace so the full chain shows under the
// request's [req#N] when debugging, without flooding disk.
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
}
return result;
}
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
+16
View File
@@ -7,6 +7,22 @@ import { BridgeManager } from './bridge/manager';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
// can drop at any moment, and a stray rejection on a detached callback (or a
// throw that escapes one) must NOT take the whole process down — otherwise
// Docker restarts it (dropping every session) and a bare Windows run just dies
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
// known paths (e.g. the hook-client send deferreds) — these only catch what
// slips through, and surface its stack so the real source can be fixed.
process.on('unhandledRejection', (reason) => {
log.error('unhandledRejection (kept alive): %s',
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
});
process.on('uncaughtException', (error) => {
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
});
async function main() {
log.info('SnowLuma starting');
+127 -2
View File
@@ -14,6 +14,17 @@ import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { findAvailablePort } from './port';
import {
clearBackgroundImage,
loadUiConfig,
MAX_BACKGROUND_BYTES,
publicAppearance,
readBackgroundImage,
saveUiConfig,
sniffImageMime,
writeBackgroundImage,
} from './ui-config';
import { getUpdateInfo } from './update-check';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -139,7 +150,10 @@ export async function initWebUI(
// ─── Auth middleware ─────────────────────────────────────────────────────
app.use('/api/*', async (c, next) => {
const reqPath = c.req.path;
if (reqPath === '/api/login') return next();
// `/api/ui/public` serves the cosmetic appearance subset to the
// pre-auth login page, so it must skip the bearer check. It exposes
// nothing sensitive (no layout, no secrets) — see ui-config.ts.
if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next();
const authHeader = c.req.header('Authorization');
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
@@ -282,9 +296,38 @@ export async function initWebUI(
});
});
// ─── Background image (unauth, like /avatar) ─────────────────────────────
// The login page needs to render the operator's background before auth, so
// this route is intentionally public. It only serves a file the operator
// themselves uploaded. Cache-busting is via the `?v=` version the client
// appends; the bytes for a given version are immutable.
app.get('/ui-asset/background', (c) => {
const asset = readBackgroundImage();
if (!asset) return c.text('no background', 404);
return new Response(new Uint8Array(asset.bytes), {
headers: {
'Content-Type': asset.mime,
'Cache-Control': 'public, max-age=31536000, immutable',
// Defence-in-depth: never let an uploaded blob be interpreted as
// anything but the sniffed image type.
'X-Content-Type-Options': 'nosniff',
},
});
});
// ─── Read-only API ───────────────────────────────────────────────────────
app.get('/api/status', (c) => c.json({ status: 'running' }));
// Advisory update check — compares the running build against the latest
// GitHub stable release and links the user to it. Read-only: SnowLuma
// never downloads or applies the update itself. `?force=1` bypasses the
// server-side cache (the "立即检查" button). Never errors out — a failed
// check returns `{ hasUpdate: false, error }` and the UI degrades quietly.
app.get('/api/update/check', async (c) => {
const force = c.req.query('force') === 'true' || c.req.query('force') === '1';
return c.json(await getUpdateInfo(force));
});
// Host system info
let lastCpuTimes: { idle: number; total: number }[] | null = null;
function sampleCpuLoad(): number[] {
@@ -500,6 +543,84 @@ export async function initWebUI(
}
});
// ─── WebUI customization config (config/ui.json) ─────────────────────────
// Appearance (A) + layout (C). The full config is bearer-gated; only the
// cosmetic appearance subset is exposed unauthenticated for the login page.
app.get('/api/ui', (c) => c.json({ config: loadUiConfig() }));
app.get('/api/ui/public', (c) => c.json({ appearance: publicAppearance() }));
app.post('/api/ui', async (c) => {
// Reject oversized bodies before buffering — the normalizer caps individual
// fields (customCss 50KB, per-widget config 4KB) but not the whole payload.
const declaredLen = Number(c.req.header('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > 256 * 1024) {
return c.json({ success: false, message: '配置过大' }, 413);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
try {
const config = saveUiConfig(body);
return c.json({ success: true, config });
} catch (err) {
log.warn('save ui.json failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 400);
}
});
app.post('/api/ui/background', async (c) => {
// Early reject by Content-Length BEFORE parseBody() buffers the whole
// multipart body into memory — otherwise a multi-GB upload is fully
// materialized before the post-parse size check fires. The slack covers
// the multipart envelope (boundary + part headers); the exact decoded
// size is still enforced below. A chunked request with no Content-Length
// skips this coarse guard, but the endpoint is bearer-gated to the single
// admin, so that residual is acceptable.
const declaredLen = Number(c.req.header('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > MAX_BACKGROUND_BYTES + 1024 * 1024) {
return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413);
}
let file: unknown;
try {
const form = await c.req.parseBody();
file = form['file'];
} catch {
return c.json({ success: false, message: '上传解析失败' }, 400);
}
if (!(file instanceof File)) {
return c.json({ success: false, message: '缺少图片文件' }, 400);
}
if (file.size > MAX_BACKGROUND_BYTES) {
return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413);
}
const bytes = new Uint8Array(await file.arrayBuffer());
const mime = sniffImageMime(bytes);
if (!mime) {
return c.json({ success: false, message: '仅支持 PNG / JPEG / WebP 图片' }, 415);
}
try {
const config = writeBackgroundImage(bytes, mime);
return c.json({ success: true, config });
} catch (err) {
log.warn('write background image failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '保存图片失败,请检查服务器日志' }, 500);
}
});
app.delete('/api/ui/background', (c) => {
try {
const config = clearBackgroundImage();
return c.json({ success: true, config });
} catch (err) {
log.warn('clear background image failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '删除图片失败' }, 500);
}
});
// ─── Static frontend ─────────────────────────────────────────────────────
// Build path is relative to the bundled / dev __dirname. SPA fallback to
// index.html so client-side routes (if any) keep working.
@@ -509,7 +630,11 @@ export async function initWebUI(
const indexHtmlPath = path.join(staticRoot, 'index.html');
app.get('*', (c) => {
// SPA fallback: only for navigations that didn't hit a static asset.
if (c.req.path.startsWith('/api/') || c.req.path.startsWith('/avatar/')) {
if (
c.req.path.startsWith('/api/') ||
c.req.path.startsWith('/avatar/') ||
c.req.path.startsWith('/ui-asset/')
) {
return c.text('not found', 404);
}
if (existsSync(indexHtmlPath)) {
+658
View File
@@ -0,0 +1,658 @@
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
// Server-side store for the WebUI customization config (`config/ui.json`).
//
// This is the single source of truth for appearance (A) + layout (C). The
// browser caches it in localStorage only to avoid a first-paint flash; the
// canonical copy lives here so a deployer's look + curated layout follow them
// across devices/browsers.
//
// Trust boundaries that this module enforces:
// * `normalizeAppearance` is total — any unknown/corrupt input collapses to
// safe defaults. This matters because the cosmetic subset is served to an
// UNAUTHENTICATED client (the login page) via `GET /api/ui/public`, so it
// must never echo attacker-controlled garbage.
// * The background-IMAGE lifecycle fields (`hasImage` / `imageMime` /
// `imageVersion`) are server-managed: a plain `POST /api/ui` cannot set
// them. Only the dedicated upload/delete endpoints mutate them. A client
// save preserves whatever is currently on disk.
const log = createLogger('WebUI.UiConfig');
const CONFIG_DIR = 'config';
const UI_CONFIG_PATH = path.join(CONFIG_DIR, 'ui.json');
/** Directory for operator-uploaded UI assets (currently just the background). */
export const UI_ASSETS_DIR = path.join(CONFIG_DIR, 'ui-assets');
/** Fixed path of the single background image (overwrite-on-upload). */
export const BACKGROUND_IMAGE_PATH = path.join(UI_ASSETS_DIR, 'background');
/** Reject uploads larger than this (bytes). */
export const MAX_BACKGROUND_BYTES = 5 * 1024 * 1024;
export const UI_CONFIG_VERSION = 1 as const;
// ─── Schema ──────────────────────────────────────────────────────────────
export type ThemeMode = 'light' | 'dark' | 'system';
export type AccentMode = 'preset' | 'custom';
export type AccentScope = 'sidebar' | 'global';
export type DarkIntensity = 'soft' | 'black';
export type SidebarStyle = 'follow' | 'panel' | 'accent';
export type BackgroundType = 'none' | 'solid' | 'gradient' | 'image';
export type Density = 'cozy' | 'compact';
export type TimeFormat = '12h' | '24h';
/** Full color scheme. 'default' keeps the sky theme (driven by `mode`); the
* Catppuccin flavors are complete palettes that also fix light/dark. */
export type Palette =
| 'default'
| 'catppuccin-latte' | 'catppuccin-frappe' | 'catppuccin-macchiato' | 'catppuccin-mocha'
| 'rose-pine' | 'rose-pine-moon' | 'rose-pine-dawn'
| 'nord'
| 'everforest-dark' | 'everforest-light';
export interface UiBackground {
type: BackgroundType;
/** Solid-fill colour (hex). Used when type === 'solid'. */
color: string;
/** Gradient preset id (frontend owns the catalogue). Used when type === 'gradient'. */
gradient: string;
/** Image readability overlay: 0 (image fully visible) … 1 (fully masked). */
imageOpacity: number;
/** Image blur in px (0…40). */
imageBlur: number;
// ── server-managed (upload/delete endpoints only) ──
hasImage: boolean;
imageMime: string;
/** Bumped on each successful upload so the browser can cache-bust. */
imageVersion: number;
}
export interface UiAppearance {
mode: ThemeMode;
accentMode: AccentMode;
/** Preset accent id (frontend catalogue: sky/blue/violet/…). */
accentPreset: string;
/** Custom accent colour (hex). Used when accentMode === 'custom'. */
accentCustom: string;
accentScope: AccentScope;
darkIntensity: DarkIntensity;
/** Full color scheme; 'default' = the built-in sky theme. */
palette: Palette;
sidebarStyle: SidebarStyle;
background: UiBackground;
/** Sans font preset id (frontend catalogue). */
fontSans: string;
/** Mono font preset id (frontend catalogue). */
fontMono: string;
/** Global UI scale, 0.9…1.2. */
uiScale: number;
/** Corner radius in rem, 0…2. */
radius: number;
density: Density;
/** Soften animations (transforms off, shorter durations). */
reduceMotion: boolean;
/** Hard-disable all UI animations (stronger than reduceMotion). */
disableMotion: boolean;
highContrast: boolean;
sidebarDefaultCollapsed: boolean;
timeFormat: TimeFormat;
/** Dashboard poll interval (ms); 0 = paused. */
pollInterval: number;
/**
* Operator custom CSS, applied AFTER auth only (never on the login page —
* `publicAppearance` strips it). Capped at 50 KB. The client injects it as
* the last <style> and skips it under `?safe-mode=1` so a broken rule can't
* lock the operator out.
*/
customCss: string;
}
export interface UiLayoutItem {
id: string;
visible: boolean;
/**
* Grid position/size (overview blocks only; nav items omit them). The
* client owns the widget catalogue, per-widget min sizes, and the
* `stats`→tiles migration — the server just preserves + clamps these to
* sane integer bounds so a corrupt file can't store absurd coords.
*/
x?: number;
y?: number;
w?: number;
h?: number;
/**
* Per-widget settings (overview blocks only) — an opaque object the client
* interprets by widget type (e.g. alerts: count + levels). The server only
* checks it's a plain object within a size bound; it never reads the keys.
*/
config?: Record<string, unknown>;
}
export interface UiLayout {
/** Ordered overview blocks. Frontend reconciles against its known set. */
overviewBlocks: UiLayoutItem[];
/** Ordered sidebar nav items, keyed by route path. */
navItems: UiLayoutItem[];
}
export interface UiHighlightRule {
keyword: string;
color: string;
}
export interface UiLogsPrefs {
/** Log levels shown by default (client display filter). */
visibleLevels: string[];
/** Ring-buffer cap for the live view (100…5000). */
maxLines: number;
autoScroll: boolean;
wrap: boolean;
/** Keyword → colour row highlights. */
highlightRules: UiHighlightRule[];
}
export interface UiPages {
/** Route the operator lands on after login (a nav path; '/' if unset). */
defaultRoute: string;
logs: UiLogsPrefs;
/** Default sort key for the processes page. */
processesSort: string;
/** Default tab id for the node-config page ('' = first). */
configTab: string;
}
export interface UiConfig {
version: typeof UI_CONFIG_VERSION;
appearance: UiAppearance;
layout: UiLayout;
pages: UiPages;
}
// ─── Defaults ────────────────────────────────────────────────────────────
// Mirror the pre-existing ThemeContext defaults so an upgrade is a no-op
// visually until the operator changes something.
const DEFAULT_BACKGROUND: UiBackground = {
type: 'none',
color: '#0ea5e9',
gradient: 'none',
imageOpacity: 0.15,
imageBlur: 0,
hasImage: false,
imageMime: '',
imageVersion: 0,
};
const DEFAULT_APPEARANCE: UiAppearance = {
mode: 'system',
accentMode: 'preset',
accentPreset: 'sky',
accentCustom: '#38bdf8',
accentScope: 'global',
darkIntensity: 'soft',
palette: 'default',
sidebarStyle: 'follow',
background: DEFAULT_BACKGROUND,
fontSans: 'default',
fontMono: 'default',
uiScale: 1,
radius: 0.75,
density: 'cozy',
reduceMotion: false,
disableMotion: false,
highContrast: false,
sidebarDefaultCollapsed: false,
timeFormat: '24h',
pollInterval: 3000,
customCss: '',
};
const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [
{ id: 'stats', visible: true },
{ id: 'connections', visible: true },
{ id: 'alerts', visible: true },
{ id: 'host', visible: true },
{ id: 'sessions', visible: true },
];
const DEFAULT_NAV_ITEMS: UiLayoutItem[] = [
{ id: '/', visible: true },
{ id: '/processes', visible: true },
{ id: '/config', visible: true },
{ id: '/logs', visible: true },
{ id: '/settings', visible: true },
];
const LOG_LEVELS = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
const DEFAULT_PAGES: UiPages = {
defaultRoute: '/',
logs: {
visibleLevels: [...LOG_LEVELS],
maxLines: 1000,
autoScroll: true,
wrap: true,
highlightRules: [],
},
processesSort: 'pid',
configTab: '',
};
export function defaultUiConfig(): UiConfig {
return {
version: UI_CONFIG_VERSION,
appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND } },
layout: {
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })),
navItems: DEFAULT_NAV_ITEMS.map((b) => ({ ...b })),
},
pages: defaultPages(),
};
}
function defaultPages(): UiPages {
return { ...DEFAULT_PAGES, logs: { ...DEFAULT_PAGES.logs, visibleLevels: [...LOG_LEVELS], highlightRules: [] } };
}
// ─── Normalization helpers ─────────────────────────────────────────────────
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
? (value as T)
: fallback;
}
function clampNum(value: unknown, min: number, max: number, fallback: number): number {
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
if (!Number.isFinite(n)) return fallback;
return Math.min(max, Math.max(min, n));
}
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
return Math.trunc(clampNum(value, min, max, fallback));
}
function isFiniteNum(value: unknown): boolean {
if (typeof value === 'number') return Number.isFinite(value);
return typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value));
}
function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
function hexOr(value: unknown, fallback: string): string {
return typeof value === 'string' && HEX_RE.test(value.trim()) ? value.trim() : fallback;
}
/** Bounded free-form id (frontend owns the actual catalogue). */
function idOr(value: unknown, fallback: string, maxLen = 64): string {
if (typeof value !== 'string') return fallback;
const v = value.trim();
if (v.length === 0 || v.length > maxLen) return fallback;
// Ids are slugs / route paths — refuse control chars and anything exotic.
if (!/^[\w./:-]+$/.test(v)) return fallback;
return v;
}
function normalizeLayoutItems(value: unknown, fallback: UiLayoutItem[]): UiLayoutItem[] {
if (!Array.isArray(value)) return fallback.map((i) => ({ ...i }));
const seen = new Set<string>();
const out: UiLayoutItem[] = [];
for (const raw of value) {
if (!isObject(raw)) continue;
const id = idOr(raw.id, '');
if (!id || seen.has(id)) continue;
seen.add(id);
const item: UiLayoutItem = { id, visible: boolOr(raw.visible, true) };
// Grid coords are optional (overview blocks carry them; nav items don't).
// Preserve + clamp when any are present; missing ones get safe defaults
// and the client re-applies per-widget min sizes on load.
if (isFiniteNum(raw.x) || isFiniteNum(raw.y) || isFiniteNum(raw.w) || isFiniteNum(raw.h)) {
item.x = clampInt(raw.x, 0, 50, 0);
item.y = clampInt(raw.y, 0, 1000, 0);
item.w = clampInt(raw.w, 1, 12, 1);
item.h = clampInt(raw.h, 1, 100, 1);
}
// Opaque per-widget config: keep only a plain object within a size bound;
// the server never interprets the keys (the client does, per widget type).
if (isObject(raw.config)) {
try {
if (JSON.stringify(raw.config).length <= 4096) item.config = raw.config;
} catch { /* unserializable (cycles) → drop */ }
}
out.push(item);
}
// An array that parsed to nothing usable is indistinguishable from corrupt;
// fall back so the frontend always has a baseline to reconcile against.
return out.length > 0 ? out : fallback.map((i) => ({ ...i }));
}
/**
* The background-image fields are server-managed (only the upload/delete
* endpoints mutate them). Normalization NEVER derives them from the value
* being normalized — the caller supplies the trusted source:
* * LOAD path → the parsed-from-disk file IS the truth (`imageStateFromParsed`).
* * SAVE path → the current on-disk config is the truth (a client payload
* cannot forge `hasImage`).
*/
export interface ServerImageState {
hasImage: boolean;
imageMime: string;
imageVersion: number;
}
const DEFAULT_IMAGE_STATE: ServerImageState = { hasImage: false, imageMime: '', imageVersion: 0 };
const KNOWN_IMAGE_MIMES = ['image/png', 'image/jpeg', 'image/webp'];
/** Coerce a raw background-ish object into a coherent, trusted image state. */
function sanitizeImageState(value: unknown): ServerImageState {
const v = isObject(value) ? value : {};
const version = Math.trunc(clampNum(v.imageVersion, 0, Number.MAX_SAFE_INTEGER, 0));
if (!boolOr(v.hasImage, false)) return { hasImage: false, imageMime: '', imageVersion: version };
const mime = typeof v.imageMime === 'string' && KNOWN_IMAGE_MIMES.includes(v.imageMime) ? v.imageMime : '';
// "Has image" with no recognizable mime is incoherent on-disk state; treat
// it as no image so the serve path and the UI stay consistent.
if (!mime) return { hasImage: false, imageMime: '', imageVersion: version };
return { hasImage: true, imageMime: mime, imageVersion: version };
}
/** Trusted image state read FROM a parsed-from-disk config blob. */
function imageStateFromParsed(parsed: unknown): ServerImageState {
if (!isObject(parsed) || !isObject(parsed.appearance)) return DEFAULT_IMAGE_STATE;
return sanitizeImageState(parsed.appearance.background);
}
function normalizeBackground(value: unknown, imageState: ServerImageState): UiBackground {
const v = isObject(value) ? value : {};
let type = oneOf<BackgroundType>(v.type, ['none', 'solid', 'gradient', 'image'], DEFAULT_BACKGROUND.type);
// An image background is only valid when an image is actually stored —
// otherwise the serve route 404s and the UI shows a broken wallpaper.
if (type === 'image' && !imageState.hasImage) type = 'none';
return {
type,
color: hexOr(v.color, DEFAULT_BACKGROUND.color),
gradient: idOr(v.gradient, DEFAULT_BACKGROUND.gradient),
imageOpacity: clampNum(v.imageOpacity, 0, 1, DEFAULT_BACKGROUND.imageOpacity),
imageBlur: clampNum(v.imageBlur, 0, 40, DEFAULT_BACKGROUND.imageBlur),
// Server-managed — taken from the caller-supplied trusted source, never
// from the value being normalized.
hasImage: imageState.hasImage,
imageMime: imageState.imageMime,
imageVersion: imageState.imageVersion,
};
}
export function normalizeAppearance(value: unknown, imageState: ServerImageState = DEFAULT_IMAGE_STATE): UiAppearance {
const v = isObject(value) ? value : {};
return {
mode: oneOf<ThemeMode>(v.mode, ['light', 'dark', 'system'], DEFAULT_APPEARANCE.mode),
accentMode: oneOf<AccentMode>(v.accentMode, ['preset', 'custom'], DEFAULT_APPEARANCE.accentMode),
accentPreset: idOr(v.accentPreset, DEFAULT_APPEARANCE.accentPreset, 32),
accentCustom: hexOr(v.accentCustom, DEFAULT_APPEARANCE.accentCustom),
accentScope: oneOf<AccentScope>(v.accentScope, ['sidebar', 'global'], DEFAULT_APPEARANCE.accentScope),
darkIntensity: oneOf<DarkIntensity>(v.darkIntensity, ['soft', 'black'], DEFAULT_APPEARANCE.darkIntensity),
palette: oneOf<Palette>(v.palette, ['default', 'catppuccin-latte', 'catppuccin-frappe', 'catppuccin-macchiato', 'catppuccin-mocha', 'rose-pine', 'rose-pine-moon', 'rose-pine-dawn', 'nord', 'everforest-dark', 'everforest-light'], DEFAULT_APPEARANCE.palette),
sidebarStyle: oneOf<SidebarStyle>(v.sidebarStyle, ['follow', 'panel', 'accent'], DEFAULT_APPEARANCE.sidebarStyle),
background: normalizeBackground(v.background, imageState),
fontSans: idOr(v.fontSans, DEFAULT_APPEARANCE.fontSans),
fontMono: idOr(v.fontMono, DEFAULT_APPEARANCE.fontMono),
uiScale: clampNum(v.uiScale, 0.9, 1.2, DEFAULT_APPEARANCE.uiScale),
radius: clampNum(v.radius, 0, 2, DEFAULT_APPEARANCE.radius),
density: oneOf<Density>(v.density, ['cozy', 'compact'], DEFAULT_APPEARANCE.density),
reduceMotion: boolOr(v.reduceMotion, DEFAULT_APPEARANCE.reduceMotion),
disableMotion: boolOr(v.disableMotion, DEFAULT_APPEARANCE.disableMotion),
highContrast: boolOr(v.highContrast, DEFAULT_APPEARANCE.highContrast),
sidebarDefaultCollapsed: boolOr(v.sidebarDefaultCollapsed, DEFAULT_APPEARANCE.sidebarDefaultCollapsed),
timeFormat: oneOf<TimeFormat>(v.timeFormat, ['12h', '24h'], DEFAULT_APPEARANCE.timeFormat),
pollInterval: clampNum(v.pollInterval, 0, 60_000, DEFAULT_APPEARANCE.pollInterval),
customCss: typeof v.customCss === 'string' ? v.customCss.slice(0, 50_000) : DEFAULT_APPEARANCE.customCss,
};
}
export function normalizeLayout(value: unknown): UiLayout {
const layout = isObject(value) ? value : {};
return {
overviewBlocks: normalizeLayoutItems(layout.overviewBlocks, DEFAULT_OVERVIEW_BLOCKS),
navItems: normalizeLayoutItems(layout.navItems, DEFAULT_NAV_ITEMS),
};
}
function normalizeHighlightRules(value: unknown): UiHighlightRule[] {
if (!Array.isArray(value)) return [];
const out: UiHighlightRule[] = [];
for (const raw of value) {
if (!isObject(raw) || typeof raw.keyword !== 'string') continue;
const keyword = raw.keyword.trim().slice(0, 50);
if (!keyword) continue; // drop empty / whitespace-only (would match every row)
const color = typeof raw.color === 'string' ? raw.color.slice(0, 32) : '';
out.push({ keyword, color });
if (out.length >= 20) break; // cap the rule count
}
return out;
}
export function normalizePages(value: unknown): UiPages {
const v = isObject(value) ? value : {};
const logs = isObject(v.logs) ? v.logs : {};
const levels = Array.isArray(logs.visibleLevels)
? LOG_LEVELS.filter((l) => (logs.visibleLevels as unknown[]).includes(l))
: DEFAULT_PAGES.logs.visibleLevels;
return {
defaultRoute: idOr(v.defaultRoute, DEFAULT_PAGES.defaultRoute),
logs: {
visibleLevels: levels.length > 0 ? levels : [...LOG_LEVELS],
maxLines: clampInt(logs.maxLines, 100, 5000, DEFAULT_PAGES.logs.maxLines),
autoScroll: boolOr(logs.autoScroll, DEFAULT_PAGES.logs.autoScroll),
wrap: boolOr(logs.wrap, DEFAULT_PAGES.logs.wrap),
highlightRules: normalizeHighlightRules(logs.highlightRules),
},
processesSort: idOr(v.processesSort, DEFAULT_PAGES.processesSort),
configTab: typeof v.configTab === 'string' ? v.configTab.slice(0, 64) : DEFAULT_PAGES.configTab,
};
}
export function normalizeUiConfig(value: unknown, imageState: ServerImageState = DEFAULT_IMAGE_STATE): UiConfig {
const v = isObject(value) ? value : {};
return {
version: UI_CONFIG_VERSION,
appearance: normalizeAppearance(v.appearance, imageState),
layout: normalizeLayout(v.layout),
pages: normalizePages(v.pages),
};
}
// ─── Persistence ────────────────────────────────────────────────────────────
function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function atomicWrite(config: UiConfig): void {
ensureConfigDir();
const tmp = UI_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
fs.renameSync(tmp, UI_CONFIG_PATH);
}
let cached: UiConfig | null = null;
/** Load + normalize the UI config, creating it from defaults if absent. */
export function loadUiConfig(): UiConfig {
if (cached) return cached;
ensureConfigDir();
if (!fs.existsSync(UI_CONFIG_PATH)) {
const fresh = defaultUiConfig();
try {
atomicWrite(fresh);
} catch (err) {
log.warn('failed to write initial ui.json: %s', err instanceof Error ? err.message : String(err));
}
cached = fresh;
return fresh;
}
try {
const raw = fs.readFileSync(UI_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
// On load, the file itself is the source of truth for the server-managed
// image fields — so they survive restarts (don't reset to defaults).
const normalized = normalizeUiConfig(parsed, imageStateFromParsed(parsed));
// Re-persist only if normalization changed something (corrupt/old file),
// so we self-heal on disk without rewriting on every boot.
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
try {
atomicWrite(normalized);
} catch {
/* best-effort self-heal */
}
}
cached = normalized;
return normalized;
} catch (err) {
log.warn('ui.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
const fresh = defaultUiConfig();
cached = fresh;
return fresh;
}
}
/**
* Persist a client-supplied config. The incoming appearance is normalized and
* its server-managed background-image fields are forced to the current on-disk
* truth (the client cannot fake `hasImage`). Returns the stored config.
*/
export function saveUiConfig(incoming: unknown): UiConfig {
const current = loadUiConfig();
const v = isObject(incoming) ? incoming : {};
// Section-level merge: a payload may carry just `appearance` (the theme
// editor) or just `layout` (the layout editor) without clobbering the
// other. A missing/non-object section keeps the current on-disk value.
// The current on-disk state is the truth for the server-managed image
// fields — a client payload cannot forge `hasImage` etc.
const next: UiConfig = {
version: UI_CONFIG_VERSION,
appearance: isObject(v.appearance)
? normalizeAppearance(v.appearance, current.appearance.background)
: current.appearance,
layout: isObject(v.layout) ? normalizeLayout(v.layout) : current.layout,
pages: isObject(v.pages) ? normalizePages(v.pages) : (current.pages ?? defaultPages()),
};
atomicWrite(next);
cached = next;
return next;
}
/** The appearance subset served unauthenticated to the login page. Strips
* `customCss` so a broken/hostile rule can never reach the pre-auth page
* (and so the operator can always log in to fix it). */
export function publicAppearance(): UiAppearance {
return { ...loadUiConfig().appearance, customCss: '' };
}
// ─── Background image lifecycle ─────────────────────────────────────────────
const IMAGE_MIME: Record<string, string> = {
png: 'image/png',
jpeg: 'image/jpeg',
webp: 'image/webp',
};
/**
* Identify an image by its magic bytes (never by a client-supplied filename or
* Content-Type). Returns the canonical MIME, or null if it isn't a supported
* image. Supported: PNG, JPEG, WebP.
*/
export function sniffImageMime(bytes: Uint8Array): string | null {
if (bytes.length >= 8 &&
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 &&
bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) {
return IMAGE_MIME.png;
}
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
return IMAGE_MIME.jpeg;
}
if (bytes.length >= 12 &&
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
return IMAGE_MIME.webp;
}
return null;
}
/** Write the uploaded image to disk and record its metadata. Returns the config. */
export function writeBackgroundImage(bytes: Uint8Array, mime: string): UiConfig {
fs.mkdirSync(UI_ASSETS_DIR, { recursive: true });
const tmp = BACKGROUND_IMAGE_PATH + '.tmp';
fs.writeFileSync(tmp, bytes);
fs.renameSync(tmp, BACKGROUND_IMAGE_PATH);
const current = loadUiConfig();
const next: UiConfig = {
...current,
appearance: {
...current.appearance,
background: {
...current.appearance.background,
// Default to showing the freshly-uploaded image unless the operator
// explicitly had a non-image background selected and we respect it;
// switching to 'image' here matches the natural "I just set a wallpaper"
// expectation.
type: 'image',
hasImage: true,
imageMime: mime,
imageVersion: current.appearance.background.imageVersion + 1,
},
},
};
atomicWrite(next);
cached = next;
return next;
}
/** Remove the background image (if any) and clear its metadata. Returns the config. */
export function clearBackgroundImage(): UiConfig {
try {
if (fs.existsSync(BACKGROUND_IMAGE_PATH)) fs.unlinkSync(BACKGROUND_IMAGE_PATH);
} catch (err) {
log.warn('failed to remove background image: %s', err instanceof Error ? err.message : String(err));
}
const current = loadUiConfig();
const next: UiConfig = {
...current,
appearance: {
...current.appearance,
background: {
...current.appearance.background,
// Fall back to 'none' if the image was the active background.
type: current.appearance.background.type === 'image' ? 'none' : current.appearance.background.type,
hasImage: false,
imageMime: '',
},
},
};
atomicWrite(next);
cached = next;
return next;
}
/** Read the background image bytes + MIME, or null if none is stored. */
export function readBackgroundImage(): { bytes: Buffer; mime: string } | null {
const { background } = loadUiConfig().appearance;
if (!background.hasImage) return null;
try {
const bytes = fs.readFileSync(BACKGROUND_IMAGE_PATH);
return { bytes, mime: background.imageMime || 'application/octet-stream' };
} catch {
return null;
}
}
+163
View File
@@ -0,0 +1,163 @@
// Advisory update check against the public GitHub Releases API.
//
// Strictly read-only (T0): SnowLuma never downloads or applies anything
// itself — cross-platform self-update is a minefield (Windows locks loaded
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
// have no supervisor). We only tell the WebUI that a newer *stable* release
// exists and link the user to it; they download and apply manually.
//
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
// rate limit, and every failure degrades silently (the UI just shows
// "无法检查更新" rather than nagging).
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('Update');
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
const FETCH_TIMEOUT_MS = 8_000;
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
export interface UpdateCheckResult {
/** The running build's version (no `v` prefix). */
current: string;
/** Latest stable release version, or null when the check did not complete. */
latest: string | null;
/** True only when `latest` is strictly newer than `current`. */
hasUpdate: boolean;
/** GitHub release page URL for the latest release. */
htmlUrl: string | null;
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
notes: string | null;
/** ISO timestamp the latest release was published. */
publishedAt: string | null;
/** When this result was produced (epoch ms). */
checkedAt: number;
/** Set when the check was skipped or failed; the UI degrades silently. */
error?: string;
}
interface GithubRelease {
tag_name?: string;
html_url?: string;
body?: string;
published_at?: string;
}
function currentVersion(): string {
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
}
/**
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
* older, 0 if equal. The numeric core (major.minor.patch) compares
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
* for "is the latest stable strictly newer than what we run" — and avoids
* pulling in a `semver` runtime dependency (the dist bundle ships none).
*/
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) nums.push(0);
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) return pa.nums[i] - pb.nums[i];
}
if (pa.pre === pb.pre) return 0;
if (!pa.pre) return 1; // release > prerelease
if (!pb.pre) return -1;
return pa.pre < pb.pre ? -1 : 1;
}
let cache: UpdateCheckResult | null = null;
let inflight: Promise<UpdateCheckResult> | null = null;
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
try {
// `/releases/latest` already excludes drafts and prereleases, so this is
// stable-channel by construction.
const res = await fetch(LATEST_RELEASE_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': `SnowLuma/${current}`,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) return { ...base, error: `github ${res.status}` };
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) return { ...base, error: 'no tag' };
const latest = tag.replace(/^v/, '');
return {
current,
latest,
hasUpdate: compareVersions(latest, current) > 0,
htmlUrl: rel.html_url ?? null,
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
publishedAt: rel.published_at ?? null,
checkedAt: Date.now(),
};
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : 'network error' };
}
}
/**
* Get the update-availability result. Cached for {@link CACHE_TTL_MS}; pass
* `force` to bypass the cache (the WebUI's "立即检查" button). Never throws —
* failures come back as a result with `error` set and `hasUpdate: false`, and
* are not cached so the next check retries.
*/
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = currentVersion();
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache;
if (inflight) return inflight;
inflight = (async () => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else {
cache = result; // only cache good results so transient errors retry
if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
})().finally(() => {
inflight = null;
});
return inflight;
}
function emptyResult(current: string): UpdateCheckResult {
return {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
}
+58
View File
@@ -110,6 +110,64 @@ describe('formatMessageSegments', () => {
expect(out).toBe('hi [图片] @12345 @全体成员 [回复:999] [表情] [视频] [语音]');
});
it('renders file segments using data.name (the OneBot field), with data.file fallback', () => {
expect(formatMessageSegments([{ type: 'file', data: { name: '20260606_151113.wav' } }]))
.toBe('[文件:20260606_151113.wav]');
expect(formatMessageSegments([{ type: 'file', data: { file: 'legacy.bin' } }]))
.toBe('[文件:legacy.bin]');
expect(formatMessageSegments([{ type: 'file', data: {} }]))
.toBe('[文件]');
});
it('renders json card segments by extracting the card title from common ARK fields', () => {
// mini-program share: meta.detail_1.title
const miniApp = JSON.stringify({
app: 'com.tencent.miniapp_01',
meta: { detail_1: { title: '哔哩哔哩', desc: '某个视频标题' } },
});
expect(formatMessageSegments([{ type: 'json', data: { data: miniApp } }]))
.toBe('[卡片:哔哩哔哩]');
// news share: meta.news.title
const news = JSON.stringify({ meta: { news: { title: '新闻标题' } } });
expect(formatMessageSegments([{ type: 'json', data: { data: news } }]))
.toBe('[卡片:新闻标题]');
// QQ server-side fallback (cardId -896954183): only `prompt` is present
const fallback = JSON.stringify({
app: 'com.tencent.structmsg',
prompt: '当前QQ版本不支持此应用,请升级',
});
expect(formatMessageSegments([{ type: 'json', data: { data: fallback } }]))
.toBe('[卡片:当前QQ版本不支持此应用,请升级]');
// generic single-section meta (no recognised key, but only one section)
const generic = JSON.stringify({ meta: { custom_section: { title: '通用卡片' } } });
expect(formatMessageSegments([{ type: 'json', data: { data: generic } }]))
.toBe('[卡片:通用卡片]');
// long titles are truncated
const long = JSON.stringify({ prompt: 'a'.repeat(100) });
expect(formatMessageSegments([{ type: 'json', data: { data: long } }]))
.toBe(`[卡片:${'a'.repeat(30)}...]`);
});
it('falls back to [JSON] when the card payload is unparseable or empty', () => {
// non-string data.data
expect(formatMessageSegments([{ type: 'json', data: {} }])).toBe('[JSON]');
// invalid JSON
expect(formatMessageSegments([{ type: 'json', data: { data: 'not-json{' } }]))
.toBe('[JSON]');
// JSON without any recognised title field
expect(formatMessageSegments([{ type: 'json', data: { data: '{"foo":1}' } }]))
.toBe('[JSON]');
// empty string
expect(formatMessageSegments([{ type: 'json', data: { data: '' } }])).toBe('[JSON]');
// JSON array (not an object)
expect(formatMessageSegments([{ type: 'json', data: { data: '[1,2,3]' } }]))
.toBe('[JSON]');
});
it('renders unknown segment types as [type]', () => {
expect(formatMessageSegments([{ type: 'something_new', data: {} }]))
.toBe('[something_new]');
+71 -1
View File
@@ -13,7 +13,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
// name) — we don't need to import it directly since assertions can
// inline-extract the kind.
import type {
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup,
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin,
} from '@snowluma/proto-defs/notify';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type {
@@ -24,6 +24,7 @@ import type {
// we avoid an `import { FriendRecall as X }` that collides with the
// proton import above.
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
type GroupAdminEvent = Extract<QQEventVariant, { kind: 'group_admin' }>;
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { subscribeLogs } from '@snowluma/common/logger';
@@ -347,3 +348,72 @@ describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => {
expect(event.operatorUid).toBe(admin.uid);
});
});
describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache fresh', () => {
// Regression for #93: a member promoted to admin kept reading back as
// `member` via get_group_member_info because the admin-change push only
// emitted the notice and never patched the cached role — and that API
// serves straight from the cache (no per-read refetch, on purpose, to
// dodge risk-control). The decoder now mirrors the role into the cache.
function makeGroupAdminPacket(adminUid: string, set: boolean, fromUin = GROUP_ID): PacketInfo {
const extra = { adminUid };
const content = protobuf_encode<GroupAdmin>({
groupUin: GROUP_ID,
body: set ? { extraEnable: extra } : { extraDisable: extra },
});
const body = protobuf_encode<PushMsg>({
message: {
responseHead: { fromUin },
contentHead: { msgType: 44, timestamp: 1710000000 },
body: { msgContent: content },
},
status: 0,
});
return {
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1,
retCode: 0, fromClient: false, body,
};
}
it('promotes a cached member to admin in the identity cache (and emits set=true)', () => {
const member = makeGroupMember(22222, 'u_member');
const identity = makeIdentity([member]);
const [event] = parseMsgPush(makeGroupAdminPacket(member.uid, true), identity) as GroupAdminEvent[];
expect(event.kind).toBe('group_admin');
expect(event.userUin).toBe(member.uin);
expect(event.set).toBe(true);
expect(identity.findGroupMember(GROUP_ID, member.uin)?.role).toBe('admin');
});
it('demotes a cached admin back to member on an unset push', () => {
const admin = { ...makeGroupMember(22222, 'u_admin'), role: 'admin' };
const identity = makeIdentity([admin]);
const [event] = parseMsgPush(makeGroupAdminPacket(admin.uid, false), identity) as GroupAdminEvent[];
expect(event.set).toBe(false);
expect(identity.findGroupMember(GROUP_ID, admin.uin)?.role).toBe('member');
});
it('never downgrades the owner', () => {
const owner = { ...makeGroupMember(22222, 'u_owner'), role: 'owner' };
const identity = makeIdentity([owner]);
parseMsgPush(makeGroupAdminPacket(owner.uid, false), identity);
expect(identity.findGroupMember(GROUP_ID, owner.uin)?.role).toBe('owner');
});
it('is a no-op (no throw, no phantom member) when the target is not cached', () => {
const identity = makeIdentity();
const [event] = parseMsgPush(makeGroupAdminPacket('u_unknown', true), identity) as GroupAdminEvent[];
expect(event.kind).toBe('group_admin');
// fromUin (the group id) is the resolve fallback — it must not be
// confused for a real, promotable member.
expect(identity.findGroupMember(GROUP_ID, GROUP_ID)).toBeNull();
});
});
+1
View File
@@ -0,0 +1 @@
dist/
+113
View File
@@ -0,0 +1,113 @@
# @snowluma/mcp
An [MCP](https://modelcontextprotocol.io) server for the **SnowLuma OneBot action
catalog**. It runs in two modes from one binary:
- **docs** (default) — read-only: every action's docs, parameters, cross-field
constraints, and a ready-to-use **JSON Schema**, so an LLM can answer "what
params does `set_group_ban` take?" without holding the whole catalog in context.
- **execution** (opt-in) — when pointed at a running OneBot HTTP endpoint, the LLM
can also *call* actions: read-only ones freely, write ones behind a gate.
## Docs only (default)
Add to your MCP client (Claude Desktop, Cline, …) — no endpoint, no execution:
```json
{
"mcpServers": {
"snowluma": { "command": "npx", "args": ["-y", "@snowluma/mcp"] }
}
}
```
### Docs tools
- `list_actions({ category? })` — lightweight index (name / category / summary / aliases / `readOnly`).
- `get_action({ name })` — full doc for one action incl. `inputSchema` and `readOnly` (accepts aliases).
- `search_actions({ query })` — fuzzy match over name / summary / aliases.
- `list_categories()` — categories and their action counts.
Also exposes the whole catalog as a resource: `snowluma://onebot/actions`.
## Execution (opt-in)
Point the server at a running SnowLuma instance's **OneBot HTTP endpoint** (the
`httpServer` network adapter) and it gains two execution tools:
- `query_action({ action, params? })` — calls a **read-only** action (e.g. `get_*`,
`can_*`) and returns the full OneBot response. Annotated `readOnlyHint`. Refuses
write actions (points you to `invoke_action`).
- `invoke_action({ action, params? })` — calls **any known** action, including ones
with side effects (send a message, change a group, …). Annotated `destructiveHint`
+ `openWorldHint`. **Only available in write mode.**
Both pass the OneBot envelope through verbatim — a logical failure (`retcode≠0`)
comes back as data with its `wording`; only a transport failure is an error.
### Configuration (env)
| Variable | Meaning |
| --- | --- |
| `SNOWLUMA_MCP_ENDPOINT` | OneBot HTTP endpoint, e.g. `http://127.0.0.1:3000/`. **Absent → docs-only** (execution tools hidden). |
| `SNOWLUMA_MCP_TOKEN` | Access token (sent as `Authorization: Bearer …`), if the endpoint requires one. |
| `SNOWLUMA_MCP_TIMEOUT_MS` | Per-request timeout (default `30000`). |
| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. |
**Read mode** — the LLM can query read-only actions, but cannot perform any write:
```json
{
"mcpServers": {
"snowluma": {
"command": "npx",
"args": ["-y", "@snowluma/mcp"],
"env": {
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
"SNOWLUMA_MCP_TOKEN": "your-access-token"
}
}
}
}
```
**Write mode** — also enables `invoke_action` (the bot can send messages, manage
groups, etc.). Enable deliberately:
```json
{
"mcpServers": {
"snowluma": {
"command": "npx",
"args": ["-y", "@snowluma/mcp"],
"env": {
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
"SNOWLUMA_MCP_TOKEN": "your-access-token",
"SNOWLUMA_MCP_MODE": "write"
}
}
}
}
```
### Safety model
- **Read/write is classified per action** in the source specs (by what the action
actually does, not its name) and baked into the catalog. The default is *write*:
an action is callable via `query_action` **only** if it is explicitly read-only.
- **The mode gate is enforced on every call**, not just by hiding tools — calling
`invoke_action` outside write mode is refused even if a client sends it directly.
- **Unknown actions are rejected** by both tools (only catalog actions are callable),
so typos and non-catalog internal actions can't be driven.
- A well-behaved client can auto-approve `query_action` (read-only) and prompt for
`invoke_action` (destructive) using the MCP tool annotations.
## How it stays in sync
The catalog — including each action's `readOnly` flag — is a **build-time snapshot**
generated from `@snowluma/onebot`'s live action specs (`collectActionDocs()`) on
every build, so it auto-tracks action add/remove and read/write reclassification.
The snapshot is pinned to the SnowLuma version it was built from; a new SnowLuma
release republishes a fresh catalog.
This package is generated; do not hand-edit `src/generated/catalog.ts`.
+58
View File
@@ -0,0 +1,58 @@
{
"name": "@snowluma/mcp",
"version": "1.9.10",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
"url": "git+https://github.com/SnowLuma/SnowLuma.git",
"directory": "packages/mcp"
},
"homepage": "https://github.com/SnowLuma/SnowLuma#readme",
"bugs": {
"url": "https://github.com/SnowLuma/SnowLuma/issues"
},
"type": "module",
"bin": {
"snowluma-mcp": "./dist/server.js"
},
"main": "./dist/server.js",
"types": "./dist/server.d.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true})\"",
"gen": "vitest run scripts/gen-catalog.test.ts",
"prebuild": "pnpm run clean && pnpm run gen",
"build": "tsc -p tsconfig.json",
"prepack": "pnpm run build",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"start": "node dist/server.js"
},
"keywords": [
"mcp",
"model-context-protocol",
"onebot",
"snowluma",
"qq"
],
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
},
"devDependencies": {
"@snowluma/onebot": "workspace:*",
"@snowluma/proton": "workspace:*",
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
},
"engines": {
"node": ">=22"
},
"publishConfig": {
"access": "public"
}
}
+32
View File
@@ -0,0 +1,32 @@
// Catalog generator. Runs under vitest (so @snowluma/onebot/action-docs resolves
// via the proton plugin, exactly as onebot's own tests do) and writes a build-time
// snapshot of the OneBot action catalog into src/generated/catalog.ts.
//
// This is the whole "auto-track Action 增减" mechanic: the snapshot is regenerated
// from the live specs on every build, so it can never describe a stale action set.
import { mkdirSync, writeFileSync } from 'node:fs';
import { it, expect } from 'vitest';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
it('generates src/generated/catalog.ts from the live action specs', () => {
const actions = collectActionDocs();
const categories = collectCategories();
expect(actions.length).toBeGreaterThan(100);
// every action must carry a composed input schema (the MCP's payoff)
for (const a of actions) {
expect(a.inputSchema).toBeTypeOf('object');
expect(a.name).toBeTruthy();
}
const body =
'// GENERATED by scripts/gen-catalog.test.ts — do not edit. Run `pnpm gen`.\n' +
'/* eslint-disable */\n' +
"import type { CatalogAction, CatalogCategory } from '../types.js';\n\n" +
`export const ACTIONS: CatalogAction[] = ${JSON.stringify(actions, null, 2)};\n\n` +
`export const CATEGORIES: CatalogCategory[] = ${JSON.stringify(categories, null, 2)};\n`;
const dir = new URL('../src/generated/', import.meta.url);
mkdirSync(dir, { recursive: true });
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
});
+69
View File
@@ -0,0 +1,69 @@
// Thin HTTP bridge to a running OneBot instance.
//
// The OneBot v11 HTTP action protocol is trivial — POST `{ action, params }` to
// the endpoint, read back the JSON envelope — so the MCP talks to it directly
// with `fetch`. We deliberately do NOT depend on @snowluma/sdk here: its
// published dist is bundler-targeted ESM (extensionless relative imports) that
// native `node` cannot resolve without a bundler, and this package is a plain
// `tsc`-built stdio bin. The wire shape — not a shared client type — is the seam
// (ADR-0005); tests inject a fake `ActionClient` (or a fake `fetch`).
const DEFAULT_TIMEOUT_MS = 30_000;
/** OneBot v11 response envelope, passed through to the LLM verbatim. */
export interface OneBotEnvelope {
status: string;
retcode: number;
data?: unknown;
message?: string;
wording?: string;
echo?: unknown;
[k: string]: unknown;
}
export interface ActionClient {
/** Send one OneBot action; resolves the full envelope (even on retcode≠0),
* rejects only on transport-level failure (timeout / connection / bad body). */
call(action: string, params: Record<string, unknown>): Promise<OneBotEnvelope>;
}
export interface HttpClientOptions {
/** OneBot HTTP endpoint, e.g. http://127.0.0.1:3000/. */
endpoint: string;
accessToken?: string;
timeoutMs?: number;
/** Injectable fetch for tests; defaults to the global fetch. */
fetch?: typeof fetch;
}
export function makeHttpClient(opts: HttpClientOptions): ActionClient {
const fetchImpl = opts.fetch ?? globalThis.fetch;
const timeoutMs = opts.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (opts.accessToken) headers.Authorization = `Bearer ${opts.accessToken}`;
return {
async call(action, params) {
const res = await fetchImpl(opts.endpoint, {
method: 'POST',
headers,
body: JSON.stringify({ action, params }),
signal: AbortSignal.timeout(timeoutMs),
});
const text = await res.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
throw new Error(`OneBot returned non-JSON (HTTP ${res.status})`);
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error(`OneBot returned an unexpected response (HTTP ${res.status})`);
}
return parsed as OneBotEnvelope;
},
};
}
File diff suppressed because it is too large. Load diff
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env node
// @snowluma/mcp — an MCP server for the SnowLuma OneBot action catalog.
//
// Two modes in one binary:
// • docs (default, no endpoint): read-only catalog tools (list/get/search/
// categories) + a catalog resource. Zero contact with any live instance.
// • read / write (when SNOWLUMA_MCP_ENDPOINT is set): the catalog tools PLUS
// execution — query_action (read-only actions) and, in write mode,
// invoke_action (any known action) — proxied to a running OneBot instance
// over HTTP.
//
// Env:
// SNOWLUMA_MCP_ENDPOINT OneBot HTTP endpoint (e.g. http://127.0.0.1:3000/).
// Absent → docs-only (execution tools hidden).
// SNOWLUMA_MCP_TOKEN access token (Bearer) for the endpoint.
// SNOWLUMA_MCP_TIMEOUT_MS per-request timeout (default SDK 30s).
// SNOWLUMA_MCP_MODE docs | read | write. Default: read when an
// endpoint is set, else docs.
//
// NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr.
import { readFileSync } from 'node:fs';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import { makeHttpClient, type ActionClient } from './client.js';
import { callTool, computeTools, type Mode } from './tools.js';
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };
const VERSION = pkg.version;
const RESOURCE_URI = 'snowluma://onebot/actions';
// ── resolve mode + client from the environment ────────────────────────────
function resolveRuntime(): { mode: Mode; client?: ActionClient } {
const endpoint = process.env.SNOWLUMA_MCP_ENDPOINT?.trim();
const token = process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined;
const timeoutRaw = Number(process.env.SNOWLUMA_MCP_TIMEOUT_MS);
const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined;
const requested = process.env.SNOWLUMA_MCP_MODE?.trim().toLowerCase();
const validRequest = requested === 'docs' || requested === 'read' || requested === 'write' ? requested : undefined;
if (!endpoint) {
if (validRequest && validRequest !== 'docs') {
console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${validRequest} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`);
}
return { mode: 'docs' };
}
const mode: Mode = validRequest ?? 'read';
if (mode === 'docs') {
// Endpoint set but operator explicitly wants docs-only — honor it.
return { mode: 'docs' };
}
const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs });
return { mode, client };
}
const { mode, client } = resolveRuntime();
const server = new Server(
{ name: 'snowluma-mcp', version: VERSION },
{ capabilities: { tools: {}, resources: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) }));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
const args = (req.params.arguments ?? {}) as Record<string, unknown>;
return callTool(req.params.name, args, { mode, client });
});
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: [
{
uri: RESOURCE_URI,
name: 'SnowLuma OneBot action catalog',
mimeType: 'application/json',
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
},
],
}));
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
if (req.params.uri !== RESOURCE_URI) throw new Error(`unknown resource: ${req.params.uri}`);
return {
contents: [
{
uri: RESOURCE_URI,
mimeType: 'application/json',
text: JSON.stringify({ version: VERSION, categories: CATEGORIES, actions: ACTIONS }, null, 2),
},
],
};
});
const transport = new StdioServerTransport();
await server.connect(transport);
const where = client ? ` → ${process.env.SNOWLUMA_MCP_ENDPOINT?.trim()}` : '';
console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}${where}`);
+182
View File
@@ -0,0 +1,182 @@
// Tool surface for the MCP — kept free of any stdio / transport / env concerns
// so it is directly unit-testable. `server.ts` reads the environment, builds a
// client, and wires `computeTools` / `callTool` into the MCP request handlers.
//
// Two execution tools partition the action space by side-effect:
// • query_action — read-only actions only (readOnlyHint)
// • invoke_action — any known action (destructiveHint, write mode)
// Visibility is gated by `mode`, and `callTool` RE-checks every permission
// (defense in depth: a client may call a tool that was never listed).
import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import type { CatalogAction } from './types.js';
import type { ActionClient } from './client.js';
export type Mode = 'docs' | 'read' | 'write';
// name + every alias → action, so lookups accept aliases too.
const byName = new Map<string, CatalogAction>();
for (const a of ACTIONS) {
for (const n of [a.name, ...a.aliases]) byName.set(n, a);
}
/** Lightweight index entry (keeps list/search payloads small). */
function lite(a: CatalogAction) {
return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases, readOnly: a.readOnly };
}
const DOCS_TOOLS: Tool[] = [
{
name: 'list_actions',
description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读)。',
inputSchema: {
type: 'object',
properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } },
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'get_action',
description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回、是否只读,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。',
inputSchema: {
type: 'object',
properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
required: ['name'],
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'search_actions',
description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。',
inputSchema: {
type: 'object',
properties: { query: { type: 'string', description: '关键字' } },
required: ['query'],
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'list_categories',
description: '列出所有分类及其 action 数量。',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { readOnlyHint: true, openWorldHint: false },
},
];
const EXEC_INPUT_SCHEMA = {
type: 'object' as const,
properties: {
action: { type: 'string', description: 'action 名(接受别名)。先用 get_action 查它的参数 inputSchema。' },
params: { type: 'object', description: '该 action 的参数对象', additionalProperties: true },
},
required: ['action'],
additionalProperties: false,
};
function queryTool(): Tool {
return {
name: 'query_action',
description: '调用一个【只读】OneBot action(如 get_*/can_*)并返回完整响应。仅接受只读 action;写操作请用 invoke_action。',
inputSchema: EXEC_INPUT_SCHEMA,
annotations: { readOnlyHint: true, openWorldHint: true },
};
}
function invokeTool(): Tool {
return {
name: 'invoke_action',
description: '调用一个 OneBot action(可产生副作用:发消息、改群、改资料等)并返回完整响应。仅在写模式可用。',
inputSchema: EXEC_INPUT_SCHEMA,
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
};
}
/** Tools visible for a given mode: docs always; +query in read/write; +invoke in write. */
export function computeTools(mode: Mode): Tool[] {
const tools: Tool[] = [...DOCS_TOOLS];
if (mode === 'read' || mode === 'write') tools.push(queryTool());
if (mode === 'write') tools.push(invokeTool());
return tools;
}
export type ToolResult = CallToolResult;
function asText(data: unknown): ToolResult {
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
}
function asError(message: string): ToolResult {
return { content: [{ type: 'text', text: message }], isError: true };
}
export interface CallCtx {
mode: Mode;
client?: ActionClient;
}
export async function callTool(name: string, args: Record<string, unknown>, ctx: CallCtx): Promise<ToolResult> {
switch (name) {
case 'list_actions': {
const category = typeof args.category === 'string' ? args.category : undefined;
const list = ACTIONS.filter((a) => !category || a.category === category).map(lite);
return asText({ count: list.length, actions: list });
}
case 'get_action': {
const q = typeof args.name === 'string' ? args.name : '';
const action = byName.get(q);
if (!action) return asError(`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`);
return asText(action);
}
case 'search_actions': {
const q = (typeof args.query === 'string' ? args.query : '').toLowerCase();
const list = ACTIONS.filter(
(a) =>
a.name.toLowerCase().includes(q) ||
(a.summary ?? '').toLowerCase().includes(q) ||
a.aliases.some((al) => al.toLowerCase().includes(q)),
).map(lite);
return asText({ count: list.length, actions: list });
}
case 'list_categories':
return asText(CATEGORIES);
case 'query_action':
return execute(args, ctx, 'read');
case 'invoke_action':
return execute(args, ctx, 'write');
default:
return asError(`未知工具: ${name}`);
}
}
/** Shared execution path for query_action (read) / invoke_action (write).
* Re-checks mode + readOnly routing regardless of which tools were listed. */
async function execute(args: Record<string, unknown>, ctx: CallCtx, kind: 'read' | 'write'): Promise<ToolResult> {
if (kind === 'write' && ctx.mode !== 'write') {
return asError('写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。');
}
if (kind === 'read' && ctx.mode !== 'read' && ctx.mode !== 'write') {
return asError('执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。');
}
if (!ctx.client) return asError('未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。');
const action = typeof args.action === 'string' ? args.action : '';
const cat = byName.get(action);
if (!cat) return asError(`未知 action: ${JSON.stringify(action)}。用 list_actions / search_actions 查可用项。`);
if (kind === 'read' && !cat.readOnly) {
return asError(`${action} 是写操作,不能用 query_action;请用 invoke_action(需 SNOWLUMA_MCP_MODE=write)。`);
}
const params =
args.params && typeof args.params === 'object' && !Array.isArray(args.params)
? (args.params as Record<string, unknown>)
: {};
try {
const envelope = await ctx.client.call(action, params);
return asText(envelope);
} catch (err) {
return asError(`调用失败: ${err instanceof Error ? err.message : String(err)}`);
}
}
+38
View File
@@ -0,0 +1,38 @@
// The MCP's own view of the OneBot action catalog. Mirrors @snowluma/onebot's
// ActionDoc, but is defined HERE so the published package does not couple to
// onebot's internals — the generated `catalog.ts` (a build-time snapshot) is the
// only contract (ADR-0005: the wire/data shape is the seam, not a shared type).
export interface CatalogParam {
name: string;
/** Display type ('uint' | 'int' | 'messageId' | 'string' | 'bool' | 'message' | 'enum' | 'X[]' | 'raw'). */
type: string;
required: boolean;
default?: unknown;
desc?: string;
values?: ReadonlyArray<string | number>;
/** JSON Schema fragment for this single field. */
schema?: Record<string, unknown>;
}
export interface CatalogAction {
name: string;
aliases: string[];
category?: string;
summary?: string;
returns?: string;
/** True only for pure data-fetch actions (no side effects). Drives the
* read/write tool routing: read-only → query_action, else → invoke_action.
* Classified at the source spec by what the action's `run` actually does. */
readOnly: boolean;
params: CatalogParam[];
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
invariants: string[];
/** Composed JSON Schema for the whole params object. */
inputSchema: Record<string, unknown>;
}
export interface CatalogCategory {
category: string;
count: number;
}
+39
View File
@@ -0,0 +1,39 @@
import { describe, it, expect } from 'vitest';
import { makeHttpClient } from '../src/client';
// Verifies the HTTP bridge: a OneBot action becomes a POST of `{ action, params }`
// to the endpoint (with Bearer auth), and the JSON envelope comes back verbatim.
// A fake fetch stands in for the network.
describe('makeHttpClient — OneBot HTTP wiring', () => {
it('POSTs {action, params} to the endpoint and returns the parsed envelope', async () => {
const calls: Array<{ url: string; body: any; auth?: string }> = [];
const fakeFetch = (async (url: unknown, init: any) => {
calls.push({
url: String(url),
body: JSON.parse(init.body as string),
auth: (init.headers as Record<string, string>)?.Authorization,
});
return new Response(JSON.stringify({ status: 'ok', retcode: 0, data: { ok: true } }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}) as unknown as typeof fetch;
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', accessToken: 'tok', fetch: fakeFetch });
const env = await client.call('get_status', { x: 1 });
expect(env.status).toBe('ok');
expect(env.retcode).toBe(0);
expect(calls).toHaveLength(1);
expect(calls[0].url).toBe('http://127.0.0.1:9999/');
expect(calls[0].body.action).toBe('get_status');
expect(calls[0].body.params).toEqual({ x: 1 });
expect(calls[0].auth).toBe('Bearer tok');
});
it('propagates a transport failure as a rejection (so the tool layer can map it)', async () => {
const fakeFetch = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch;
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch });
await expect(client.call('get_status', {})).rejects.toThrow();
});
});
+138
View File
@@ -0,0 +1,138 @@
import { describe, it, expect } from 'vitest';
import { computeTools, callTool } from '../src/tools';
import type { ActionClient, OneBotEnvelope } from '../src/client';
type Res = Awaited<ReturnType<typeof callTool>>;
function text(res: Res): string {
const block = res.content?.[0];
return block && block.type === 'text' ? block.text : '';
}
function parsed(res: Res): any {
return JSON.parse(text(res));
}
/** A fake ActionClient — no transport. Records the last call and returns a
* canned envelope (overridable per test). */
function fakeClient(impl?: (action: string, params: Record<string, unknown>) => OneBotEnvelope): ActionClient {
return {
call: async (action, params) => impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } },
};
}
describe('computeTools — mode gating', () => {
it('docs mode exposes only the 4 catalog tools', () => {
expect(computeTools('docs').map((t) => t.name)).toEqual([
'list_actions', 'get_action', 'search_actions', 'list_categories',
]);
});
it('read mode adds query_action only (no invoke_action)', () => {
const names = computeTools('read').map((t) => t.name);
expect(names).toContain('query_action');
expect(names).not.toContain('invoke_action');
});
it('write mode adds both query_action and invoke_action', () => {
const names = computeTools('write').map((t) => t.name);
expect(names).toContain('query_action');
expect(names).toContain('invoke_action');
});
it('annotations are honest: query=readOnly, invoke=destructive', () => {
const q = computeTools('write').find((t) => t.name === 'query_action');
const inv = computeTools('write').find((t) => t.name === 'invoke_action');
expect(q?.annotations?.readOnlyHint).toBe(true);
expect(inv?.annotations?.readOnlyHint).toBe(false);
expect(inv?.annotations?.destructiveHint).toBe(true);
});
});
describe('callTool — docs tools (no client needed)', () => {
it('list_actions returns entries that carry readOnly', async () => {
const data = parsed(await callTool('list_actions', {}, { mode: 'docs' }));
expect(data.count).toBeGreaterThan(100);
expect(typeof data.actions[0].readOnly).toBe('boolean');
});
it('get_action resolves a known read-only action', async () => {
const a = parsed(await callTool('get_action', { name: 'get_status' }, { mode: 'docs' }));
expect(a.name).toBe('get_status');
expect(a.readOnly).toBe(true);
});
it('get_action on a write action reports readOnly=false', async () => {
expect(parsed(await callTool('get_action', { name: 'send_group_msg' }, { mode: 'docs' })).readOnly).toBe(false);
});
it('get_action accepts an alias', async () => {
// nc_get_rkey is an alias of get_rkey (read-only).
const a = parsed(await callTool('get_action', { name: 'nc_get_rkey' }, { mode: 'docs' }));
expect(a.name).toBe('get_rkey');
});
});
describe('callTool — query_action (read)', () => {
it('executes a read-only action and passes the envelope through', async () => {
const res = await callTool('query_action', { action: 'get_status', params: {} }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBeFalsy();
expect(parsed(res).retcode).toBe(0);
});
it('refuses a write action and points to invoke_action', async () => {
const res = await callTool('query_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('invoke_action');
});
it('refuses an unknown action', async () => {
const res = await callTool('query_action', { action: 'no_such_action' }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('未知 action');
});
it('is blocked in docs mode even when called directly (defense in depth)', async () => {
const res = await callTool('query_action', { action: 'get_status' }, { mode: 'docs' });
expect(res.isError).toBe(true);
});
it('errors clearly when no client is wired', async () => {
const res = await callTool('query_action', { action: 'get_status' }, { mode: 'read' });
expect(res.isError).toBe(true);
expect(text(res)).toContain('未配置');
});
});
describe('callTool — invoke_action (write)', () => {
it('executes a write action in write mode and forwards action+params', async () => {
let seen: { action: string; params: Record<string, unknown> } | null = null;
const client: ActionClient = {
call: async (action, params) => {
seen = { action, params };
return { status: 'ok', retcode: 0, data: { message_id: 42 } };
},
};
const res = await callTool('invoke_action', { action: 'send_group_msg', params: { group_id: 1, message: 'hi' } }, { mode: 'write', client });
expect(res.isError).toBeFalsy();
expect(seen!.action).toBe('send_group_msg');
expect(seen!.params).toEqual({ group_id: 1, message: 'hi' });
expect(parsed(res).data.message_id).toBe(42);
});
it('is blocked in read mode (write gate cannot be bypassed)', async () => {
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('写操作未启用');
});
it('passes a retcode≠0 envelope through as data, NOT isError', async () => {
const client = fakeClient(() => ({ status: 'failed', retcode: 1404, message: 'not found', wording: '未找到' }));
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client });
expect(res.isError).toBeFalsy();
expect(parsed(res).retcode).toBe(1404);
expect(parsed(res).wording).toBe('未找到');
});
it('maps a transport-level throw to isError', async () => {
const client: ActionClient = { call: async () => { throw new Error('connection refused'); } };
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client });
expect(res.isError).toBe(true);
expect(text(res)).toContain('调用失败');
expect(text(res)).toContain('connection refused');
});
it('accepts a read-only action too (invoke is a superset)', async () => {
const res = await callTool('invoke_action', { action: 'get_status', params: {} }, { mode: 'write', client: fakeClient() });
expect(res.isError).toBeFalsy();
});
it('refuses an unknown action (typo safety)', async () => {
const res = await callTool('invoke_action', { action: 'frobnicate' }, { mode: 'write', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('未知 action');
});
});
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"noEmit": false,
"types": ["node"]
},
"include": ["src/**/*"]
}
+17
View File
@@ -0,0 +1,17 @@
// Vitest config — used only to RUN the catalog generator (scripts/gen-catalog.test.ts)
// in an environment where `@snowluma/onebot/action-docs` resolves. The proton
// plugin provides the same bare-specifier resolver @snowluma/onebot's own tests
// use, so importing the action specs works identically here.
import protobufVitePlugin from '@snowluma/proton/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [protobufVitePlugin()],
test: {
include: ['scripts/**/*.test.ts', 'tests/**/*.test.ts'],
environment: 'node',
env: {
SNOWLUMA_LOG_FILE: '0',
},
},
});
+9 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/onebot",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
@@ -11,6 +11,14 @@
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./action-kit": {
"types": "./src/action-kit.ts",
"default": "./src/action-kit.ts"
},
"./action-docs": {
"types": "./src/action-docs.ts",
"default": "./src/action-docs.ts"
},
"./manager": {
"types": "./src/manager.ts",
"default": "./src/manager.ts"
+89
View File
@@ -0,0 +1,89 @@
// action-docs — self-generated OneBot API docs (D4).
//
// Walks `ActionSpec.describe()` over every declarative action and renders a
// structured doc list + a Markdown view. The metadata is carried on the same
// values that drive runtime validation, so docs cannot drift from behavior.
//
// Coverage note: the ~15 genuinely irregular actions in `actions/extended.ts`
// that remain on the legacy `h.registerAction(...)` path are NOT ActionSpecs
// and so do not appear here — that is the documented irregular tail.
//
// The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a
// deferred product decision; this module produces format-agnostic data plus a
// Markdown default. Point any renderer at `collectActionDocs()`.
import type { ActionDoc, ActionSpec, Field } from './action-kit';
import { actions as infoActions } from './actions/info';
import { actions as messageActions } from './actions/message';
import { actions as friendActions } from './actions/friend';
import { actions as groupInfoActions } from './actions/group-info';
import { actions as groupAdminActions } from './actions/group-admin';
import { actions as groupFileActions } from './actions/group-file';
import { actions as requestActions } from './actions/request';
import { actions as extendedActions } from './actions/extended';
import { actions as groupAlbumActions } from './actions/group-album';
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
{ category: '信息', specs: infoActions },
{ category: '消息', specs: messageActions },
{ category: '好友', specs: friendActions },
{ category: '群信息', specs: groupInfoActions },
{ category: '群管理', specs: groupAdminActions },
{ category: '群文件', specs: groupFileActions },
{ category: '请求', specs: requestActions },
{ category: '扩展', specs: extendedActions },
{ category: '群相册', specs: groupAlbumActions },
];
/** Every declarative action's doc (with category), sorted by name. */
export function collectActionDocs(): ActionDoc[] {
return GROUPS
.flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category })))
.sort((a, b) => a.name.localeCompare(b.name));
}
/** Distinct categories with action counts. */
export function collectCategories(): Array<{ category: string; count: number }> {
return GROUPS.map(({ category, specs }) => ({ category, count: specs.length }));
}
function paramRow(p: ActionDoc['params'][number]): string {
const type = p.values ? p.values.map((v) => JSON.stringify(v)).join(' \\| ') : p.type;
const required = p.required ? '✓' : '–';
const def = !p.required && p.default !== undefined ? `\`${JSON.stringify(p.default)}\`` : '';
return `| \`${p.name}\` | ${type} | ${required} | ${def} | ${p.desc ?? ''} |`;
}
function renderAction(doc: ActionDoc): string {
const lines: string[] = [];
const alias = doc.aliases.length ? ` _(别名: ${doc.aliases.map((a) => `\`${a}\``).join(', ')})_` : '';
const cat = doc.category ? ` · ${doc.category}` : '';
lines.push(`### \`${doc.name}\`${cat}${alias}`);
if (doc.summary) lines.push('', doc.summary);
if (doc.params.length) {
lines.push('', '| 参数 | 类型 | 必填 | 默认 | 说明 |', '| --- | --- | --- | --- | --- |');
for (const p of doc.params) lines.push(paramRow(p));
} else {
lines.push('', '_无参数_');
}
if (doc.invariants.length) lines.push('', `**约束:** ${doc.invariants.map((i) => `\`${i}\``).join(';')}`);
if (doc.returns) lines.push('', `**返回:** \`${doc.returns}\``);
return lines.join('\n');
}
/** Render the full Markdown doc. */
export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectActionDocs()): string {
const header = [
'# OneBot Actions',
'',
'> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。',
'> 仅覆盖声明式 action;`extended.ts` 中少量走 legacy `registerAction` 的不规则 action 不在此列。',
'',
`共 ${docs.length} 个声明式 action。`,
'',
];
return header.concat(docs.map(renderAction)).join('\n') + '\n';
}
+483
View File
@@ -0,0 +1,483 @@
// action-kit — declarative OneBot Action definitions.
//
// One Action declares its param contract once (a record of `Field`s + optional
// cross-field `rules`) and a `run` handler. The kit owns param coercion +
// validation + the `BAD_REQUEST` shaping (naming the offending field) +
// doc metadata. The handler receives typed, already-validated params.
//
// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response
// wrapping. `defineAction(...).register(h, ctx)` ultimately registers a plain
// `(params) => Promise<ApiResponse>` via `ApiHandler.registerAction`, exactly
// like the legacy style — so old and new actions coexist during migration.
//
// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no
// hand-written param interface. Param contract is intentionally a second
// definition from the SDK's client-side types (ADR-0005).
//
// Guard-rail (ADR-0007): the built-in coercers below are strict. Do NOT add a
// lenient `union`/`refine` escape that re-introduces the silent coercion this
// module exists to remove.
import { RETCODE, failedResponse } from './types';
import type { ApiResponse, JsonObject, JsonValue } from './types';
import type { ApiActionContext, ApiHandler } from './api-handler';
// ─────────────────────────── result currency ───────────────────────────
export type Ok<T> = { ok: true; value: T };
/** `field` is the offending param ('' for a cross-field rule). */
export type Err = { ok: false; field: string; reason: string };
export type CoerceResult<T> = Ok<T> | Err;
const ok = <T>(value: T): Ok<T> => ({ ok: true, value });
const err = (field: string, reason: string): Err => ({ ok: false, field, reason });
/** Only an absent key produces MISSING — this is what lets a present `0` /
* `''` / `false` be distinguished from "not provided". */
const MISSING = Symbol('missing');
type Raw = JsonValue | typeof MISSING;
// ─────────────────────────── Field (param coercer) ───────────────────────────
/** A JSON Schema fragment (loose). Each coercer emits one; `describe()` composes
* them into an action's `inputSchema` (consumed by docs / the MCP). */
export type JsonSchema = Record<string, unknown>;
export interface FieldDoc {
type: string;
required: boolean;
default?: JsonValue;
desc?: string;
values?: readonly (string | number)[];
/** JSON Schema fragment for this field's value (constraints only; presence
* and default are applied at the object level by `describe()`). */
schema?: JsonSchema;
}
export interface Field<T> {
readonly doc: FieldDoc;
/** Coerce the raw value at this field's key (MISSING when the key is absent). */
coerce(raw: Raw, field: string): CoerceResult<T>;
/** Absent ⇒ value is `undefined`; a present value still must coerce. */
optional(): Field<T | undefined>;
/** Absent ⇒ `value`; a present value still must coerce (so `"abc"` for a
* numeric field is an error, not a silent fallback). */
default(value: T): Field<T>;
describe(text: string): Field<T>;
/** Complete JSON Schema for this field's value (constraints + description +
* default). Object-level required-ness is handled by `describe()`. */
toJsonSchema(): JsonSchema;
}
/** Core coerces a PRESENT value (never MISSING). Presence policy is applied
* by the wrapping Field. */
type Core<T> = (raw: JsonValue, field: string) => CoerceResult<T>;
class FieldImpl<T> implements Field<T> {
constructor(
private readonly core: Core<T>,
readonly doc: FieldDoc,
) {}
coerce(raw: Raw, field: string): CoerceResult<T> {
if (raw === MISSING) {
if (this.doc.required) return err(field, 'is required');
return ok(this.doc.default as T); // default value, or undefined when optional
}
return this.core(raw, field);
}
optional(): Field<T | undefined> {
return new FieldImpl<T | undefined>(this.core as Core<T | undefined>, {
...this.doc,
required: false,
default: undefined,
});
}
default(value: T): Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, required: false, default: value as JsonValue });
}
describe(text: string): Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
}
toJsonSchema(): JsonSchema {
const out: JsonSchema = { ...(this.doc.schema ?? {}) };
if (this.doc.desc) out.description = this.doc.desc;
if (this.doc.default !== undefined) out.default = this.doc.default;
return out;
}
}
// ─────────────────────────── coercer vocabulary `f` ───────────────────────────
interface IntOpts { min?: number; max?: number; nonZero?: boolean }
/** Accept a number or numeric string, truncate to integer (matches the legacy
* `asNumber`), then apply bounds. Non-numeric / blank ⇒ Err. */
function intCore(typeName: string, opts: IntOpts): Core<number> {
return (raw, field) => {
let n: number;
if (typeof raw === 'number' && Number.isFinite(raw)) n = Math.trunc(raw);
else if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) n = Math.trunc(Number(raw));
else return err(field, `expected ${typeName}`);
if (opts.nonZero && n === 0) return err(field, 'must not be 0');
if (opts.min !== undefined && n < opts.min) return err(field, `must be >= ${opts.min}`);
if (opts.max !== undefined && n > opts.max) return err(field, `must be <= ${opts.max}`);
return ok(n);
};
}
function intSchema(opts: IntOpts): JsonSchema {
const s: JsonSchema = { type: 'integer' };
if (opts.min !== undefined) s.minimum = opts.min;
if (opts.max !== undefined) s.maximum = opts.max;
if (opts.nonZero) s.not = { const: 0 };
return s;
}
interface StrOpts { allowEmpty?: boolean; maxLen?: number }
function strSchema(opts: StrOpts): JsonSchema {
const s: JsonSchema = { type: 'string' };
if (opts.allowEmpty === false) s.minLength = 1;
if (opts.maxLen !== undefined) s.maxLength = opts.maxLen;
return s;
}
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
const core: Core<E[]> = (raw, field) => {
if (!Array.isArray(raw)) return err(field, 'expected an array');
const out: E[] = [];
for (let i = 0; i < raw.length; i++) {
const r = el.coerce(raw[i] as JsonValue, `${field}[${i}]`);
if (!r.ok) return r;
out.push(r.value);
}
if (mustBeNonEmpty && out.length === 0) return err(field, 'must not be empty');
return ok(out);
};
const base = new FieldImpl<E[]>(core, {
type: `${el.doc.type}[]`,
required: true,
schema: { type: 'array', items: el.toJsonSchema(), ...(mustBeNonEmpty ? { minItems: 1 } : {}) },
});
return Object.assign(base, { nonEmpty: () => arrayField(el, true) });
}
export const f = {
/** Positive integer (>0): group_id / user_id / message_id. */
uint(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, schema: intSchema({ min: 1 }) });
},
/** Integer with optional bounds; allows 0 / negatives unless bounded.
* e.g. a duration where 0 is meaningful: `f.int({ min: 0 })`. */
int(opts: IntOpts = {}): Field<number> {
return new FieldImpl<number>(intCore('an integer', opts), { type: 'int', required: true, schema: intSchema(opts) });
},
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
* signed int32 hash) — do NOT use `uint()` for message_id. */
messageId(): Field<number> {
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) });
},
/** Finite number (fractions allowed). */
number(): Field<number> {
return new FieldImpl<number>((raw, field) => {
if (typeof raw === 'number' && Number.isFinite(raw)) return ok(raw);
if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return ok(Number(raw));
return err(field, 'expected a number');
}, { type: 'number', required: true, schema: { type: 'number' } });
},
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
* allowed by default; `{ allowEmpty: false }` rejects ''. */
string(opts: StrOpts = {}): Field<string> {
return new FieldImpl<string>((raw, field) => {
let s: string;
if (typeof raw === 'string') s = raw;
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
else return err(field, 'expected a string');
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
return ok(s);
}, { type: 'string', required: true, schema: strSchema(opts) });
},
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
bool(): Field<boolean> {
return new FieldImpl<boolean>((raw, field) => {
if (typeof raw === 'boolean') return ok(raw);
if (typeof raw === 'number') return ok(raw !== 0);
if (typeof raw === 'string') {
const t = raw.trim().toLowerCase();
if (t === 'true' || t === '1' || t === 'yes' || t === 'on') return ok(true);
if (t === 'false' || t === '0' || t === 'no' || t === 'off') return ok(false);
}
return err(field, 'expected a boolean');
}, { type: 'bool', required: true, schema: { type: 'boolean' } });
},
/** OneBot message union: string | segment[] | object. A string that looks
* like a JSON array is parsed (matches legacy `asMessage`); otherwise the
* value passes through. Output stays `JsonValue` — downstream ctx.* accept it. */
message(): Field<JsonValue> {
return new FieldImpl<JsonValue>((raw, _field) => {
if (typeof raw === 'string') {
const t = raw.trim();
if (t.startsWith('[') && t.endsWith(']')) {
try {
const parsed: unknown = JSON.parse(t);
if (Array.isArray(parsed)) return ok(parsed as JsonValue);
} catch {
// fall through to literal text
}
}
}
return ok(raw);
}, { type: 'message', required: true, schema: { description: 'OneBot message: string | segment[] | object' } });
},
/** Homogeneous array; `.nonEmpty()` rejects []. */
array<E>(el: Field<E>): Field<E[]> & { nonEmpty(): Field<E[]> } {
return arrayField(el, false);
},
/** Constrained literal set. */
enum<const V extends readonly (string | number)[]>(...values: V): Field<V[number]> {
return new FieldImpl<V[number]>((raw, field) => {
if ((typeof raw === 'string' || typeof raw === 'number') && (values as readonly (string | number)[]).includes(raw)) {
return ok(raw as V[number]);
}
return err(field, `expected one of: ${values.join(', ')}`);
}, { type: 'enum', required: true, values, schema: { enum: [...values] } });
},
/** Escape hatch — pass the raw value (or undefined) through, validate nothing. */
raw(): Field<JsonValue | undefined> {
return new FieldImpl<JsonValue | undefined>((raw) => ok(raw), { type: 'raw', required: false, default: undefined, schema: {} });
},
};
// ─────────────────────────── type inference ───────────────────────────
type Spec = Record<string, Field<unknown>>;
type FieldType<F> = F extends Field<infer T> ? T : never;
/** Post-validation every key is present; optional/raw fields carry `undefined`
* in their value type. */
export type InferParams<S extends Spec> = { [K in keyof S]: FieldType<S[K]> };
// ─────────────────────────── cross-field rules ───────────────────────────
export interface CrossFieldRule {
readonly doc: string;
check(params: Record<string, unknown>): Err | null;
}
type Key<P> = Extract<keyof P, string>;
type Group<P> = Key<P> | Key<P>[];
export interface RuleBuilders<P> {
/** Exactly one group satisfied. A group is a key, or an array of keys that
* must ALL be present. e.g. `exactlyOneOf('message_id', ['group_id','user_id'])`. */
exactlyOneOf(...groups: Group<P>[]): CrossFieldRule;
atLeastOneOf(...keys: Key<P>[]): CrossFieldRule;
requiredTogether(...keys: Key<P>[]): CrossFieldRule;
mutuallyExclusive(...keys: Key<P>[]): CrossFieldRule;
/** Arbitrary predicate; fails with `doc` as the reason. */
rule(doc: string, ok: (p: P) => boolean): CrossFieldRule;
}
const present = (p: Record<string, unknown>, key: string): boolean => p[key] !== undefined;
const groupOk = (p: Record<string, unknown>, g: string | string[]): boolean =>
Array.isArray(g) ? g.every((k) => present(p, k)) : present(p, g);
const groupLabel = (g: string | string[]): string => (Array.isArray(g) ? `(${g.join('+')})` : g);
const RULES: RuleBuilders<Record<string, unknown>> = {
exactlyOneOf(...groups) {
const doc = `exactly one of: ${groups.map(groupLabel).join(' | ')}`;
return {
doc,
check: (p) => (groups.filter((g) => groupOk(p, g)).length === 1 ? null : err('', doc)),
};
},
atLeastOneOf(...keys) {
const doc = `at least one of: ${keys.join(', ')}`;
return { doc, check: (p) => (keys.some((k) => present(p, k)) ? null : err('', doc)) };
},
requiredTogether(...keys) {
const doc = `all or none of: ${keys.join(', ')}`;
return {
doc,
check: (p) => {
const n = keys.filter((k) => present(p, k)).length;
return n === 0 || n === keys.length ? null : err('', doc);
},
};
},
mutuallyExclusive(...keys) {
const doc = `at most one of: ${keys.join(', ')}`;
return { doc, check: (p) => (keys.filter((k) => present(p, k)).length <= 1 ? null : err('', doc)) };
},
rule(doc, okFn) {
return { doc, check: (p) => (okFn(p as never) ? null : err('', doc)) };
},
};
// ─────────────────────────── defineAction ───────────────────────────
export interface ParamDoc extends FieldDoc {
name: string;
}
export interface ActionDoc {
name: string;
aliases: string[];
/** Domain category (set by the doc collector, e.g. 群管理/消息). */
category?: string;
summary?: string;
returns?: string;
/** True only for pure data-fetch actions (no side effects). Drives the MCP's
* read/write tool routing; defaults to false (treated as a write). */
readOnly: boolean;
params: ParamDoc[];
invariants: string[];
/** Composed JSON Schema for the whole params object (properties + required). */
inputSchema: JsonSchema;
}
type Handler = (params: JsonObject) => Promise<ApiResponse>;
export interface ActionSpec<S extends Spec> {
readonly names: string[];
readonly params: S;
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
toHandler(ctx: ApiActionContext): Handler;
/** Doc metadata (D4); a renderer walks this. */
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
interface ActionDef<S extends Spec> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
/** Mark true ONLY for pure data-fetch actions with no side effects. Default
* false = write. Surfaced via describe() into the catalog for the MCP's
* read/write routing. Classify by what `run` actually does, not the name. */
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
/** `raw` is the original untouched params — an escape hatch for the
* irregular tail (alias-key fallbacks, arbitrary nested objects). Declared
* fields in `p` remain the validated path; reach for `raw` only for keys
* the spec can't express. */
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
}
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
const names = typeof def.name === 'string' ? [def.name] : [...def.name];
const rules: readonly CrossFieldRule[] = def.rules
? def.rules(RULES as unknown as RuleBuilders<InferParams<S>>)
: [];
const parse = (raw: JsonObject): CoerceResult<InferParams<S>> => {
const out: Record<string, unknown> = {};
for (const key of Object.keys(def.params)) {
const field = def.params[key];
const value = Object.prototype.hasOwnProperty.call(raw, key) ? (raw[key] as JsonValue) : MISSING;
const r = field.coerce(value, key);
if (!r.ok) return r;
out[key] = r.value;
}
for (const rule of rules) {
const e = rule.check(out);
if (e) return e;
}
return ok(out as InferParams<S>);
};
const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => {
const r = parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params);
};
return {
names,
params: def.params,
parse,
toHandler,
describe: () => {
const entries = Object.entries(def.params);
const properties: Record<string, JsonSchema> = {};
const required: string[] = [];
for (const [name, field] of entries) {
properties[name] = field.toJsonSchema();
if (field.doc.required) required.push(name);
}
const inputSchema: JsonSchema = {
type: 'object',
properties,
...(required.length ? { required } : {}),
additionalProperties: true,
};
return {
name: names[0],
aliases: names.slice(1),
summary: def.summary,
returns: def.returns,
readOnly: def.readOnly ?? false,
params: entries.map(([name, field]) => ({ name, ...field.doc })),
invariants: rules.map((rule) => rule.doc),
inputSchema,
};
},
register: (h, ctx) => {
const handler = toHandler(ctx);
for (const name of names) h.registerAction(name, handler);
},
};
}
// ─────────────────────────── presets ───────────────────────────
// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the
// dominant shape. The injected fields are surfaced in `describe()` so docs
// list them even though the caller never typed them (ADR-0006 trade-off).
type WithGroup<S extends Spec> = S & { group_id: Field<number> };
type WithGroupUser<S extends Spec> = S & { group_id: Field<number>; user_id: Field<number> };
interface PresetDef<S extends Spec, Extra> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
readOnly?: boolean;
params?: S;
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
run: (p: InferParams<S> & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
}
/** Pre-seeds `group_id` (uint, required). */
export function groupAction<S extends Spec>(def: PresetDef<S, { group_id: number }>): ActionSpec<WithGroup<S>> {
const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroup<S>>);
}
/** Pre-seeds `group_id` + `user_id` (both uint, required). */
export function groupUserAction<S extends Spec>(
def: PresetDef<S, { group_id: number; user_id: number }>,
): ActionSpec<WithGroupUser<S>> {
const params = {
group_id: f.uint().describe('群号'),
user_id: f.uint().describe('QQ 号'),
...(def.params ?? {}),
} as WithGroupUser<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
}
// ─────────────────────────── registration helper ───────────────────────────
/** Register many specs onto an ApiHandler. Coexists with legacy
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<ActionSpec<Spec>>): void {
for (const spec of specs) spec.register(h, ctx);
}
File diff suppressed because it is too large. Load diff
+44 -27
View File
@@ -1,30 +1,47 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { okResponse } from '../types';
export const actions = [
defineAction({
name: 'get_friend_list',
summary: '获取好友列表',
readOnly: true,
params: {},
run: async (_p, ctx) => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
},
}),
defineAction({
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
params: { user_id: f.uint().describe('QQ 号') },
run: async (p, ctx) => {
const userId = p.user_id;
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
}
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
},
}),
defineAction({
name: 'delete_friend',
summary: '删除好友',
params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
return okResponse();
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_friend_list', async () => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
});
h.registerAction('get_stranger_info', async (params) => {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
}
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
});
h.registerAction('delete_friend', async (params) => {
const userId = asNumber(params.user_id);
const block = asBoolean(params.block, false);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.bridge.apis.friend.delete(userId, block);
return okResponse();
});
registerActions(h, ctx, actions);
}
+130 -113
View File
@@ -1,118 +1,135 @@
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asBoolean, asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_group_kick', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.kickMember(groupId, userId, reject);
return okResponse();
});
h.registerAction('set_group_kick_members', async (params) => {
const groupId = asNumber(params.group_id);
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
await ctx.bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject);
return okResponse();
});
h.registerAction('set_group_ban', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const duration = asNumber(params.duration) || 1800;
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.muteMember(groupId, userId, duration);
return okResponse();
});
h.registerAction('set_group_whole_ban', async (params) => {
const groupId = asNumber(params.group_id);
const enable = asBoolean(params.enable, true);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.muteAll(groupId, enable);
return okResponse();
});
h.registerAction('set_group_add_option', async (params) => {
const groupId = asNumber(params.group_id);
const addType = asNumber(params.add_type);
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType);
return okResponse();
});
h.registerAction('set_group_search', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.setSearch(groupId);
return okResponse();
});
h.registerAction('set_group_admin', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable);
return okResponse();
});
h.registerAction('set_group_card', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card);
return okResponse();
});
h.registerAction('set_group_name', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.setName(groupId, name);
return okResponse();
});
h.registerAction('set_group_leave', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.leave(groupId);
return okResponse();
});
h.registerAction('set_group_special_title', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title);
return okResponse();
});
h.registerAction('set_group_anonymous', async () => {
return okResponse();
});
h.registerAction('set_group_anonymous_ban', async () => {
return okResponse();
});
h.registerAction('set_group_portrait', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.bridge.apis.profile.setGroupAvatar(groupId, file);
export const actions = [
groupUserAction({
name: 'set_group_kick',
summary: '踢出群成员',
params: { reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMember(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
},
}),
groupAction({
name: 'set_group_kick_members',
summary: '批量踢出群成员',
params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_ban',
summary: '禁言群成员(duration=0 解除)',
params: { duration: f.int({ min: 0 }).default(1800) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
return okResponse();
},
}),
groupAction({
name: 'set_group_whole_ban',
summary: '全员禁言开关',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteAll(p.group_id, p.enable);
return okResponse();
},
}),
groupAction({
name: 'set_group_add_option',
summary: '设置加群选项',
params: { add_type: f.int({ min: 0 }).default(0) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAddOption(p.group_id, p.add_type);
return okResponse();
},
}),
groupAction({
name: 'set_group_search',
summary: '允许群被搜索',
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_admin',
summary: '设置/取消管理员',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAdmin(p.group_id, p.user_id, p.enable);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_card',
summary: '设置群名片(空字符串清除)',
params: { card: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setCard(p.group_id, p.user_id, p.card);
return okResponse();
},
}),
groupAction({
name: 'set_group_name',
summary: '设置群名',
params: { group_name: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setName(p.group_id, p.group_name);
return okResponse();
},
}),
groupAction({
name: 'set_group_leave',
summary: '退群',
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.leave(p.group_id);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_special_title',
summary: '设置群头衔',
params: { special_title: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSpecialTitle(p.group_id, p.user_id, p.special_title);
return okResponse();
},
}),
// No-op stubs (accept and ignore any params, as before).
defineAction({ name: 'set_group_anonymous', summary: '匿名开关(未实现,返回 ok)', params: {}, run: () => okResponse() }),
defineAction({ name: 'set_group_anonymous_ban', summary: '匿名禁言(未实现,返回 ok)', params: {}, run: () => okResponse() }),
groupAction({
name: 'set_group_portrait',
summary: '设置群头像',
params: { file: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+119 -120
View File
@@ -1,133 +1,132 @@
import { groupAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import type { JsonValue } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_album_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
export const actions = [
groupAction({
name: 'get_group_album_list',
readOnly: true,
run: async (p, ctx) => {
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(groupId);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
groupAction({
name: 'upload_image_to_qun_album',
params: {
album_id: f.string({ allowEmpty: false }),
album_name: f.string({ allowEmpty: false }),
file: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
h.registerAction('upload_image_to_qun_album', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const albumName = asString(params.album_name);
const file = asString(params.file);
groupAction({
name: 'get_group_album_media_list',
readOnly: true,
params: {
album_id: f.string({ allowEmpty: false }),
attach_info: f.string().default(''),
},
run: async (p, ctx) => {
try {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info);
return okResponse(mediaList as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
groupAction({
name: 'do_group_album_comment',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }),
content: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content);
return okResponse(comment as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
try {
await ctx.bridge.apis.groupAlbum.upload(groupId, albumId, albumName, file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('get_group_album_media_list', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const attachInfo = asString(params.attach_info) || '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
try {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo);
return okResponse(mediaList as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('do_group_album_comment', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
const content = asString(params.content);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
try {
const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content);
return okResponse(comment as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('set_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
groupAction({
name: 'set_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
// 取消点赞群相册媒体
h.registerAction('cancel_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
groupAction({
name: 'cancel_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
groupAction({
name: 'del_group_album_media',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
];
try {
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('del_group_album_media', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
if (!groupId || !albumId || !lloc) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
}
try {
const res = await ctx.bridge.apis.groupAlbum.delete(groupId, albumId, lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+153 -114
View File
@@ -1,118 +1,157 @@
import { defineAction, groupAction, registerActions, f } from '../action-kit';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asBoolean, asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse } from '../types';
import { okResponse } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
export const actions = [
groupAction({
name: 'upload_group_file',
summary: '上传群文件',
returns: '{ file_id: string }',
// `folder` / `folder_id` are two aliases for one target dir; the first
// non-empty wins, else '/'. Both default '' so the `||` chain matches the
// legacy `asString(folder) || asString(folder_id) || '/'`.
params: {
file: f.string({ allowEmpty: false }),
name: f.string().default(''),
folder: f.string().default(''),
folder_id: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const folderId = p.folder || p.folder_id || '/';
const result = await ctx.bridge.apis.groupFile.upload(p.group_id, p.file, p.name, folderId, p.upload_file);
return okResponse({ file_id: result.fileId });
},
}),
defineAction({
name: 'upload_private_file',
summary: '上传私聊文件',
returns: '{ file_id: string }',
params: {
user_id: f.uint(),
file: f.string({ allowEmpty: false }),
name: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupFile.uploadPrivate(p.user_id, p.file, p.name, p.upload_file);
return okResponse({ file_id: result.fileId });
},
}),
groupAction({
name: 'get_group_file_url',
summary: '获取群文件下载链接',
readOnly: true,
returns: '{ url: string }',
// busid: legacy `asNumber(busid) || 102` mapped absent/0/invalid → 102.
// f.int({min:0}).default(102) keeps absent → 102, but a present 0 now
// stays 0 and a non-numeric busid is now rejected (BAD_REQUEST) instead
// of silently becoming 102.
params: { file_id: f.string({ allowEmpty: false }), busid: f.int({ min: 0 }).default(102) },
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, p.busid) });
},
}),
groupAction({
name: 'get_group_root_files',
summary: '获取群根目录文件列表',
readOnly: true,
run: async (p, ctx) => {
return okResponse(await ctx.getGroupFiles(p.group_id, '/'));
},
}),
groupAction({
name: 'get_group_files_by_folder',
summary: '获取群子目录文件列表',
readOnly: true,
// folder_id / folder are aliases; first non-empty wins, else '/'.
params: { folder_id: f.string().default(''), folder: f.string().default('') },
run: async (p, ctx) => {
const folderId = p.folder_id || p.folder || '/';
return okResponse(await ctx.getGroupFiles(p.group_id, folderId));
},
}),
groupAction({
name: 'delete_group_file',
summary: '删除群文件',
params: { file_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id);
return okResponse();
},
}),
groupAction({
name: 'move_group_file',
summary: '移动群文件',
params: {
file_id: f.string({ allowEmpty: false }),
parent_directory: f.string({ allowEmpty: false }),
target_directory: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.move(p.group_id, p.file_id, p.parent_directory, p.target_directory);
return okResponse();
},
}),
groupAction({
name: 'create_group_file_folder',
summary: '创建群文件夹',
params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/');
return okResponse();
},
}),
groupAction({
name: 'delete_group_file_folder',
summary: '删除群文件夹',
params: { folder_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id);
return okResponse();
},
}),
groupAction({
name: 'rename_group_file_folder',
summary: '重命名群文件夹',
// new_folder_name / name are aliases; first non-empty wins and must be
// non-empty (legacy `asString(new_folder_name) || asString(name)` + `!newName`).
params: { folder_id: f.string({ allowEmpty: false }), new_folder_name: f.string().default(''), name: f.string().default('') },
run: async (p, ctx) => {
const newName = p.new_folder_name || p.name;
if (!newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.bridge.apis.groupFile.renameFolder(p.group_id, p.folder_id, newName);
return okResponse();
},
}),
defineAction({
name: 'get_private_file_url',
summary: '获取私聊文件下载链接',
readOnly: true,
returns: '{ url: string }',
params: {
user_id: f.uint(),
file_id: f.string({ allowEmpty: false }),
file_hash: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id, p.file_id, p.file_hash) });
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('upload_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
const name = asString(params.name);
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
const uploadFile = asBoolean(params.upload_file, true);
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
const result = await ctx.bridge.apis.groupFile.upload(groupId, file, name, folderId, uploadFile);
return okResponse({ file_id: result.fileId });
});
h.registerAction('upload_private_file', async (params) => {
const userId = asNumber(params.user_id);
const file = asString(params.file);
const name = asString(params.name);
const uploadFile = asBoolean(params.upload_file, true);
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
const result = await ctx.bridge.apis.groupFile.uploadPrivate(userId, file, name, uploadFile);
return okResponse({ file_id: result.fileId });
});
h.registerAction('get_group_file_url', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const busId = asNumber(params.busid) || 102;
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(groupId, fileId, busId) });
});
h.registerAction('get_group_root_files', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
return okResponse(await ctx.getGroupFiles(groupId, '/'));
});
h.registerAction('get_group_files_by_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
return okResponse(await ctx.getGroupFiles(groupId, folderId));
});
h.registerAction('delete_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
await ctx.bridge.apis.groupFile.delete(groupId, fileId);
return okResponse();
});
h.registerAction('move_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const parentDirectory = asString(params.parent_directory);
const targetDirectory = asString(params.target_directory);
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
}
await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory);
return okResponse();
});
h.registerAction('create_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.name);
const parentId = asString(params.parent_id) || '/';
if (!groupId || !name) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
}
await ctx.bridge.apis.groupFile.createFolder(groupId, name, parentId);
return okResponse();
});
h.registerAction('delete_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId);
return okResponse();
});
h.registerAction('rename_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
const newName = asString(params.new_folder_name) || asString(params.name);
if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName);
return okResponse();
});
h.registerAction('get_private_file_url', async (params) => {
const userId = asNumber(params.user_id);
const fileId = asString(params.file_id);
const fileHash = asString(params.file_hash);
if (!userId || !fileId || !fileHash) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
}
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash) });
});
registerActions(h, ctx, actions);
}
+103 -67
View File
@@ -1,84 +1,120 @@
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean, asString } from '../api-handler';
import { asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_list', async (params) => {
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
return okResponse([]);
});
export const actions = [
defineAction({
name: 'get_group_list',
summary: '获取群列表',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const noCache = p.no_cache;
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
return okResponse([]);
},
}),
h.registerAction('get_group_info', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
}
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
});
groupAction({
name: 'get_group_info',
summary: '获取群信息',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
}
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
},
}),
h.registerAction('get_group_member_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
});
groupAction({
name: 'get_group_member_list',
summary: '获取群成员列表',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
},
}),
h.registerAction('get_group_member_info', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(info ?? {
groupUserAction({
name: 'get_group_member_info',
summary: '获取群成员信息',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const userId = p.user_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(info ?? {
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
}
return okResponse({
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
}
return okResponse({
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
});
},
}),
h.registerAction('get_group_honor_info', async (params) => {
const groupId = asNumber(params.group_id);
const typeStr = asString(params.type) || 'all';
// `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string
// / empty-string all collapse to 'all'), which a typed string field can't
// replicate exactly — so it stays a raw param coerced in run().
groupAction({
name: 'get_group_honor_info',
summary: '获取群荣誉信息',
readOnly: true,
params: { type: f.raw() },
run: async (p, ctx) => {
const groupId = p.group_id;
const typeStr = asString(p.type) || 'all';
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
}
try {
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
}
},
}),
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
}
defineAction({
name: 'get_group_system_msg',
summary: '获取群系统消息',
readOnly: true,
params: {},
run: async (_p, ctx) => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg());
}
return okResponse([]);
},
}),
];
try {
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
}
});
h.registerAction('get_group_system_msg', async () => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg());
}
return okResponse([]);
});
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+58 -27
View File
@@ -1,32 +1,63 @@
import { defineAction, registerActions } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { okResponse } from '../types';
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
export const actions = [
defineAction({
name: 'get_login_info',
readOnly: true,
params: {},
run: (_p, ctx) => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
},
}),
defineAction({
name: 'get_status',
readOnly: true,
params: {},
run: (_p, ctx) => {
const online = ctx.isOnline();
return okResponse({ online, good: online });
},
}),
defineAction({
name: 'get_version_info',
readOnly: true,
params: {},
run: () => {
return okResponse({
app_name: 'SnowLuma',
app_version: `${appVersion}-node`,
protocol_version: 'v11',
});
},
}),
defineAction({
name: 'can_send_image',
readOnly: true,
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
},
}),
defineAction({
name: 'can_send_record',
readOnly: true,
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_login_info', async () => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
});
h.registerAction('get_status', async () => {
const online = ctx.isOnline();
return okResponse({ online, good: online });
});
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
h.registerAction('get_version_info', async () => {
return okResponse({
app_name: 'SnowLuma',
app_version: `${appVersion}-node`,
protocol_version: 'v11',
});
});
h.registerAction('can_send_image', async () => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
});
h.registerAction('can_send_record', async () => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
});
registerActions(h, ctx, actions);
}
+76 -86
View File
@@ -1,6 +1,6 @@
import type { JsonObject, JsonValue } from '../types';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
import { defineAction, groupAction, registerActions, f } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
/**
@@ -32,96 +32,86 @@ async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext):
}
}
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('send_msg', async (params) => {
const messageType = asString(params.message_type);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
if (messageType === 'group' || params.group_id !== undefined) {
const groupId = asNumber(params.group_id);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
export const actions = [
// send_msg routes on message_type / group_id presence, so the *required*
// id is conditional — that branch stays in run(). The fields themselves
// (message required; group_id/user_id valid uints when present) are
// validated by the spec; message_type is left lenient for parity.
defineAction({
name: 'send_msg',
summary: '发送消息(按 message_type/群号 自动路由群聊或私聊)',
returns: '{ message_id: number }',
params: {
message: f.message(),
message_type: f.string().optional(),
group_id: f.uint().optional(),
user_id: f.uint().optional(),
auto_escape: f.bool().default(false),
},
run: async (p, ctx) => {
if (p.message_type === 'group' || p.group_id !== undefined) {
if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
}
},
}),
const userId = asNumber(params.user_id);
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
defineAction({
name: 'send_private_msg',
summary: '发送私聊消息',
returns: '{ message_id: number }',
params: { user_id: f.uint(), message: f.message(), auto_escape: f.bool().default(false) },
run: async (p, ctx) => {
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
},
}),
h.registerAction('send_private_msg', async (params) => {
const userId = asNumber(params.user_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
groupAction({
name: 'send_group_msg',
summary: '发送群消息',
returns: '{ message_id: number }',
params: { message: f.message(), auto_escape: f.bool().default(false) },
run: async (p, ctx) => {
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
},
}),
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
defineAction({
name: 'get_msg',
summary: '获取消息',
readOnly: true,
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const data = ctx.getMessage(p.message_id);
if (!data) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
const result: JsonObject = { ...data };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? p.message_id) as JsonValue;
await refreshStoredImageUrls(result, ctx);
return okResponse(result);
},
}),
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
defineAction({
name: 'delete_msg',
summary: '撤回消息',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
await ctx.deleteMessage(p.message_id, meta);
return okResponse();
},
}),
];
h.registerAction('send_group_msg', async (params) => {
const groupId = asNumber(params.group_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('get_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const data = ctx.getMessage(messageId);
if (!data) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
}
const result: JsonObject = { ...data };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? messageId) as JsonValue;
await refreshStoredImageUrls(result, ctx);
return okResponse(result);
});
h.registerAction('delete_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
}
await ctx.deleteMessage(messageId, meta);
return okResponse();
});
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+39 -20
View File
@@ -1,23 +1,42 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asString, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asString } from '../api-handler';
import { okResponse } from '../types';
export const actions = [
defineAction({
name: 'set_friend_add_request',
summary: '处理好友添加请求',
params: {
flag: f.string({ allowEmpty: false }),
approve: f.bool().default(true),
},
run: async (p, ctx) => {
await ctx.bridge.apis.friend.handleRequest(p.flag, p.approve);
return okResponse();
},
}),
defineAction({
name: 'set_group_add_request',
summary: '处理加群请求',
params: {
flag: f.string({ allowEmpty: false }),
// sub_type/type pass through with a nested fallback (sub_type → type → 'add');
// kept raw so the original asString resolution is preserved verbatim.
sub_type: f.raw(),
type: f.raw(),
approve: f.bool().default(true),
reason: f.string().default(''),
},
run: async (p, ctx) => {
const subType = asString(p.sub_type, asString(p.type, 'add'));
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
return okResponse();
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_friend_add_request', async (params) => {
const flag = asString(params.flag);
const approve = asBoolean(params.approve, true);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
await ctx.bridge.apis.friend.handleRequest(flag, approve);
return okResponse();
});
h.registerAction('set_group_add_request', async (params) => {
const flag = asString(params.flag);
const subType = asString(params.sub_type, asString(params.type, 'add'));
const approve = asBoolean(params.approve, true);
const reason = asString(params.reason);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
await ctx.handleGroupRequest(flag, subType, approve, reason);
return okResponse();
});
registerActions(h, ctx, actions);
}
+28 -7
View File
@@ -1,5 +1,5 @@
import { summarizeParams } from '@snowluma/common/log-summary';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary';
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { register as registerExtended } from './actions/extended';
import { register as registerFriend } from './actions/friend';
@@ -76,6 +76,7 @@ export interface ApiActionContext {
}>;
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
fetchPttText: (messageId: number) => Promise<{ text: string }>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
@@ -108,13 +109,33 @@ export class ApiHandler {
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
}
// Entry log goes to file always (debug); console only when level is
// dialed down to debug. Caller-perspective summary lets the operator
// grep "what did the bot get asked to do" without scraping wire logs.
this.log.debug('%s params=%s', action, summarizeParams(params));
// Correlate the whole request — entry, every outbound packet it triggers,
// and the exit — under one `[req#N]` tag via AsyncLocalStorage. Only pay
// the wrap + id allocation when trace is actually live, so the default
// path stays allocation-free.
if (getLogLevel() !== 'trace') {
return this.runAction(action, handler, params);
}
return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params));
}
private async runAction(
action: string,
handler: ActionHandler,
params: JsonObject,
): Promise<import('./types').ApiResponse> {
// Terse breadcrumb to the log file (debug, always persisted): lets the
// operator grep "what did the bot get asked to do" in post-mortems.
this.log.debug('%s params=%s', action, summarizeParams(params));
// Full request shape, memory-only (trace). Lazy producer → the deep render
// only runs when trace is live.
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
const startedAt = Date.now();
try {
return await handler(params);
const response = await handler(params);
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
return response;
} catch (error) {
// Action failures are almost always param-shape problems coming
// from the OneBot client; warn (not error) is the right level so
@@ -32,10 +32,15 @@ export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMember
export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject {
let subType: string;
if (event.isKick) {
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
} else {
subType = 'leave';
switch (event.leaveType) {
case 'disband':
subType = 'disband';
break;
case 'kick':
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
break;
default:
subType = 'leave';
}
return {
time: event.time,
@@ -104,12 +104,22 @@ async function elementToSegment(
if (element.type === 'file') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const fileName = element.fileName ?? '';
const fileSize = element.fileSize ?? 0;
const fileId = element.fileId ?? '';
return {
type: 'file',
data: {
name: element.fileName ?? '',
size: element.fileSize ?? 0,
id: element.fileId ?? '',
// NapCat/LLOneBot-style canonical fields — most downstream
// OneBot adapters read these (`file`/`file_id`/`file_size`).
file: fileName,
file_id: fileId,
file_size: fileSize,
// Legacy SnowLuma field names, kept for backward compat with
// any consumer that already reads name/size/id.
name: fileName,
size: fileSize,
id: fileId,
url,
file_hash: element.fileHash ?? '',
},
+40 -6
View File
@@ -1,26 +1,33 @@
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { convertEvent } from './event-converter';
import type { OneBotInstanceContext } from './instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter';
const moduleLog = createLogger('Event');
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
const uinNum = Number.parseInt(ctx.uin, 10);
const log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
const disposers: Array<() => void> = [];
disposers.push(
ctx.bridge.events.on('group_message', async (event) => {
cacheGroupMessageMeta(ctx, event);
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
disposers.push(
ctx.bridge.events.on('friend_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
disposers.push(
ctx.bridge.events.on('temp_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
for (const kind of NOTICE_KINDS) {
@@ -29,10 +36,17 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
if (event.kind === 'group_msg_emoji_like') {
cacheReaction(ctx, event);
}
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
}
// Internal-only: voice-to-text result push. Not converted to a OneBot event —
// it just unblocks the fetch_ptt_text call waiting on this msgId.
disposers.push(
ctx.bridge.events.on('ptt_trans_result', (event) => {
deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
}),
);
return () => {
for (const dispose of disposers) {
@@ -58,10 +72,30 @@ const NOTICE_KINDS = [
'group_msg_emoji_like',
] as const satisfies readonly QQEventVariant['kind'][];
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
async function convertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
// Inbound choke point — the receive-side mirror of the outbound api-handler.
// Correlate the whole receive chain (decode → convert, incl. any rkey-fetch
// packets the conversion triggers, → dispatch) under one [req#N]. Only pay
// the AsyncLocalStorage wrap + id when trace is actually live.
if (getLogLevel() !== 'trace') {
await runConvertAndDispatch(ctx, log, event);
return;
}
await runWithRequestId(nextRequestId(), () => runConvertAndDispatch(ctx, log, event));
}
async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
// Raw inbound event, memory-only (trace). Lazy → the deep render runs only
// when trace is live.
log.trace(() => [`recv ${event.kind} ⇐ %s`, renderParamsVerbose(event)]);
const startedAt = Date.now();
const converted = await convertEvent(ctx.converterCtx, event);
if (!converted) return;
if (!converted) {
log.trace(() => [`recv ${event.kind} ⇒ dropped (${Date.now() - startedAt}ms)`]);
return;
}
ctx.dispatchEvent(converted);
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
}
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {
+2
View File
@@ -18,6 +18,7 @@ import {
getStrangerInfo,
} from './modules/contact-actions';
import {
fetchPttText as fetchPttTextAction,
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
@@ -116,6 +117,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
},
getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
fetchPttText: (messageId) => fetchPttTextAction(messageStore, mediaStore, bridge, ref.selfId, messageId),
};
}
+4 -3
View File
@@ -288,8 +288,9 @@ export async function segmentToElement(type: string, data: Record<string, unknow
}
case 'file': {
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
if (!fileId) {
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
if (!fileId && !source) {
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
return null;
}
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
@@ -297,7 +298,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
const elem: MessageElement = { type: 'file', fileId };
const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source };
if (fileName) elem.fileName = fileName;
if (fileSize > 0) elem.fileSize = fileSize;
if (md5Hex) elem.md5Hex = md5Hex;
@@ -3,10 +3,78 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/protocol/events';
import type { ImageUrlResolver } from '../event-converter';
import type { MediaStore } from '../media-store';
import type { MessageStore } from '../message-store';
import {
deliverPttTransText,
failPttTransWaiter,
pttTransKey,
waitPttTransText,
} from './ptt-trans-waiter';
import type { JsonObject } from '../types';
const log = createLogger('OneBot');
/**
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
* Resolves the message's `record` segment to its cached fingerprint
* (uuid + md5 + duration/size/format), then drives QQ's native
* `pttTrans.Trans{C2C,Group}PttReq` via the bridge and returns the text.
*/
export async function fetchPttText(
messageStore: MessageStore,
mediaStore: MediaStore,
bridge: BridgeInterface,
selfId: number,
messageId: number,
): Promise<{ text: string }> {
const event = messageStore.findEvent(messageId);
if (!event) throw new Error('消息不存在或已被撤回');
const segments = Array.isArray(event.message) ? event.message : [];
let file = '';
for (const seg of segments) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const so = seg as JsonObject;
if (so.type !== 'record') continue;
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) ? so.data as JsonObject : {};
file = String(data.file ?? data.url ?? '');
break;
}
if (!file) throw new Error('消息中不包含语音');
const cached = mediaStore.findRecord(file);
if (!cached) throw new Error('语音不在缓存中,无法转写');
const isGroup = event.message_type === 'group' || cached.isGroup;
const senderUin = Number(event.user_id) || 0;
// c2c: receiver is self (inbound voice); group: the group uin.
const peerUin = isGroup ? (Number(event.group_id) || cached.sessionId) : selfId;
// Register the waiter BEFORE triggering, so a fast async push can't race
// ahead of us. The trigger response may carry the text inline (already
// transcribed) — settle immediately then; otherwise the Event 0x210
// subType-61 push resolves the waiter via the event-pipeline subscription.
const key = pttTransKey(selfId, messageId);
const waiter = waitPttTransText(key, 20000);
try {
const syncText = await bridge.apis.extras.translatePttToText({
isGroup,
msgId: messageId,
senderUin,
peerUin,
uuid: cached.fileId || '',
md5Hex: cached.md5Hex ?? '',
duration: cached.duration ?? 0,
size: cached.fileSize ?? 0,
format: cached.voiceFormat ?? 0,
});
if (syncText) deliverPttTransText(key, syncText);
} catch (e) {
failPttTransWaiter(key, e instanceof Error ? e : new Error(String(e)));
}
return { text: await waiter };
}
export async function getImageInfo(
mediaStore: MediaStore,
file: string,
+46 -70
View File
@@ -241,54 +241,40 @@ export async function sendPrivateMessage(
// never mixed with the regular elements. We only need it for file
// here — video/ARK/ptt already go through commonElem so the
// element-builder handles them inline.
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
// Two sub-paths:
// a) has url/path but no file_id → uploadPrivate() which internally calls sendC2cFile()
// b) has file_id from a prior upload_private_file → sendC2cFile() only
const allFileElements = elements.filter(e => e.type === 'file');
const nonFileElements = elements.filter(e => e.type !== 'file');
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
log.warn('[OneBot] private file segment without file_id — skipped (upload first via upload_private_file)');
}
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
}
if (fileElements.length > 0) {
// C2C file send needs the recipient's UID — resolve once and reuse.
if (allFileElements.length > 0) {
const userUid = await ref.bridge.resolveUserUid(userId);
if (!userUid) {
throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
}
for (const fileEl of fileElements) {
// C2C file send requires fileSize/fileMd5/fileName to ride on the
// wire (NotOnlineFile inside msgContent). The OneBot caller
// usually only echoes the file_id from a previous
// `upload_private_file`, so look up the rest from the upload
// cache. Inline segment fields (md5/size/name) take precedence so
// a caller that already knows everything can bypass the cache.
const cached = ref.bridge.recallUploadedFile(fileEl.fileId!);
const fileMd5 = fileEl.md5Hex
? Buffer.from(fileEl.md5Hex, 'hex')
: (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
// Fall back to a generic name — the QQ server resolves the
// file by fileUuid, not name, so a missing name only affects
// the chat bubble display.
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash;
if (fileSize === 0 && !cached) {
log.warn(
'[OneBot] c2c file_id=%s sent without fileSize and no upload cache — recipient may see 0 B',
fileEl.fileId,
);
if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
for (const fileEl of allFileElements) {
if (fileEl.url && !fileEl.fileId) {
// uploadPrivate() already calls sendC2cFile() internally — do NOT call it again.
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
await ref.bridge.apis.groupFile.uploadPrivate(userId, fileEl.url, name, true);
logSentMessage(false, userId, [fileEl]);
if (!lastReceipt) {
lastReceipt = { messageId: 0, sequence: 0, clientSequence: 0, random: 0, timestamp: Math.floor(Date.now() / 1000) };
}
} else if (fileEl.fileId) {
const cached = ref.bridge.recallUploadedFile(fileEl.fileId);
const fileMd5 = fileEl.md5Hex ? Buffer.from(fileEl.md5Hex, 'hex') : (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash;
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash });
logSentMessage(false, userId, [fileEl]);
} else {
log.warn('[OneBot] private file segment without file_id or url — skipped');
}
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, {
fileId: fileEl.fileId!,
fileName,
fileSize,
fileMd5,
fileHash,
});
logSentMessage(false, userId, [fileEl]);
}
}
if (!lastReceipt) throw new Error('message is empty');
@@ -345,47 +331,37 @@ export async function sendGroupMessage(
});
if (elements.length === 0) throw new Error('message is empty');
// Group `{type:'file', file_id}` segments don't ride on the elems[]
// pipeline either. The QQ-NT server rejects PbSendMsg with a
// transElem(24) file payload (result=79); the correct send path is a
// dedicated OIDB call (`OidbSvcTrpcTcp.0x6d9_4`) that publishes a
// previously-uploaded file id as a chat bubble. Mirrors the c2c-file
// split below (private path) — both must be peeled off before the
// regular sendGroupMessage runs.
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
// Two sub-paths for group file segments:
// a) has url/path but no file_id → upload() which internally calls publish()
// b) has file_id from a prior upload_group_file → publish() only
const allFileElements = elements.filter(e => e.type === 'file');
const nonFileElements = elements.filter(e => e.type !== 'file');
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
log.warn('[OneBot] group file segment without file_id — skipped (upload first via upload_group_file)');
}
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
logSentMessage(true, groupId, nonFileElements);
}
for (const fileEl of fileElements) {
// Group-file publish has no per-message sequence/random tuple to
// hash a messageId from — OIDB 0x6d9_4 is fire-and-forget on the
// wire. If this is the LAST element we still need a receipt so
// the OneBot caller can cache the id; synthesise one from the
// file_id hash + a fresh timestamp.
await ref.bridge.apis.groupFile.publish(groupId, fileEl.fileId!);
for (const fileEl of allFileElements) {
let fileId: string;
if (fileEl.url && !fileEl.fileId) {
// upload() already calls publish() internally — do NOT call publish() again.
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true);
fileId = result.fileId ?? '';
if (!fileId) { log.warn('[OneBot] group file auto-upload returned no file_id — skipped'); continue; }
} else if (fileEl.fileId) {
fileId = fileEl.fileId;
await ref.bridge.apis.groupFile.publish(groupId, fileId);
} else {
log.warn('[OneBot] group file segment without file_id or url — skipped');
continue;
}
logSentMessage(true, groupId, [fileEl]);
if (!lastReceipt) {
// Use a hash of the fileId as a stable pseudo-id; this gets
// mixed with groupId in `hashMessageIdInt32` below.
let h = 0;
const s = fileEl.fileId ?? '';
for (let i = 0; i < s.length; i++) {
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
}
lastReceipt = {
messageId: 0,
sequence: h & 0x7FFFFFFF,
clientSequence: 0,
random: h & 0x7FFFFFFF,
timestamp: Math.floor(Date.now() / 1000),
};
for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.charCodeAt(i)) | 0;
lastReceipt = { messageId: 0, sequence: h & 0x7FFFFFFF, clientSequence: 0, random: h & 0x7FFFFFFF, timestamp: Math.floor(Date.now() / 1000) };
}
}
if (!lastReceipt) throw new Error('message is empty');
@@ -0,0 +1,56 @@
// Correlates an async voice-to-text result back to the fetch_ptt_text call
// that triggered it. QQ delivers the text via an Event 0x210 subType-61 push
// (decoded into a `ptt_trans_result` event), not in the request response — so
// the action registers a waiter keyed by `${selfUin}:${msgId}`, fires the
// trigger request, and the push subscription resolves the waiter by msgId.
interface Pending {
resolve: (text: string) => void;
reject: (err: Error) => void;
timer: ReturnType<typeof setTimeout>;
}
const pending = new Map<string, Pending>();
export function pttTransKey(selfUin: number, msgId: number): string {
return `${selfUin}:${msgId}`;
}
/**
* Register a waiter for `key`'s transcription. Rejects after `timeoutMs`.
* A new waiter for the same key supersedes (rejects) the previous one.
*/
export function waitPttTransText(key: string, timeoutMs: number): Promise<string> {
const existing = pending.get(key);
if (existing) {
clearTimeout(existing.timer);
pending.delete(key);
existing.reject(new Error('语音转文字请求被新的请求取代'));
}
return new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => {
if (pending.get(key)?.timer === timer) pending.delete(key);
reject(new Error('语音转文字超时(未收到结果推送)'));
}, timeoutMs);
timer.unref?.();
pending.set(key, { resolve, reject, timer });
});
}
/** Resolve a waiting fetch_ptt_text with the recognised text. No-op if none. */
export function deliverPttTransText(key: string, text: string): void {
const p = pending.get(key);
if (!p) return;
clearTimeout(p.timer);
pending.delete(key);
p.resolve(text);
}
/** Reject a waiter (e.g. the trigger request itself failed). No-op if none. */
export function failPttTransWaiter(key: string, err: Error): void {
const p = pending.get(key);
if (!p) return;
clearTimeout(p.timer);
pending.delete(key);
p.reject(err);
}
+60 -2
View File
@@ -1,3 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
@@ -33,12 +34,16 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected readonly log: Logger;
protected isEnabled = false;
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
constructor(name: string, config: C, ctx: NetworkAdapterContext, moduleLog?: Logger) {
this.name = name;
this.config = structuredClone(config);
this.ctx = ctx;
const base = moduleLog ?? createLogger('OneBot.Network');
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? base.child({ uin: uinNum }) : base;
}
get isActive(): boolean { return this.isEnabled; }
@@ -47,10 +52,63 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** Report live connection health for the WebUI dashboard. */
abstract describeStatus(): AdapterStatus;
// ── reload: shared hot-reload state machine (template method) ──────────
//
// All four adapters reconcile a live config swap identically: decide
// whether the binding changed, whether the adapter should be enabled, and
// then open/close to reach the target state. The skeleton lives here; the
// three things that genuinely differ per adapter are the hooks below.
//
// NOTE: the returned `NetworkReloadType` is a *test-observability* seam.
// The sole production caller (`instance.applyConfigDiff`) discards it —
// it exists so tests can assert "which transition did this config cause"
// without poking private state. Behaviour, not the label, is the contract.
/** Stable string identity of the bound resource (host:port / url / token …).
* A change here means the live binding must be torn down and re-opened. */
protected abstract bindingSignature(config: C): string;
/** Whether `config` should result in an enabled adapter. Defaults to the
* `enabled` flag; client adapters also require a target `url`. */
protected willEnable(config: C): boolean {
return config.enabled !== false;
}
/** Refresh derived state after `this.config` has been replaced (report
* options, role, propagation to live connections). Default: nothing. */
protected onConfigReplaced(_next: C): void { /* no-op */ }
async reload(next: C): Promise<NetworkReloadType> {
const prevSig = this.bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = this.willEnable(next);
this.config = structuredClone(next);
this.onConfigReplaced(next);
const sigChanged = prevSig !== this.bindingSignature(next);
if (sigChanged && wasEnabled) {
await this.close();
if (willEnable) {
await this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
await this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
await this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
}
@@ -1,4 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -6,7 +6,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const moduleLog = createLogger('OneBot.POST');
@@ -14,20 +14,11 @@ const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private lastDelivery: { at: number; ok: boolean } | null = null;
private readonly log: Logger;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -49,33 +40,16 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
protected override bindingSignature(config: HttpClientNetwork): string {
return `${config.url}#${config.accessToken ?? ''}#${config.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
this.config = structuredClone(next);
protected override willEnable(config: HttpClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: HttpClientNetwork): void {
this.options = resolveReportOptions(next);
const newSig = bindingSignature(next);
const sigChanged = newSig !== this.signature_;
this.signature_ = newSig;
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
@@ -139,10 +113,6 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
}
}
function bindingSignature(net: HttpClientNetwork): string {
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
@@ -1,4 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
createServer,
type IncomingMessage,
@@ -7,7 +7,7 @@ import {
} from 'http';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const moduleLog = createLogger('OneBot.HTTP');
@@ -15,16 +15,9 @@ const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private listening = false;
private readonly log: Logger;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
super(name, config, ctx, moduleLog);
}
open(): void {
@@ -48,31 +41,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
protected override bindingSignature(config: HttpServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}`;
}
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
@@ -223,10 +193,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
}
function bindingSignature(net: HttpServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
@@ -1,5 +1,5 @@
import { WebSocket } from '@snowluma/websocket';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -8,7 +8,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
@@ -21,18 +21,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
private readonly log: Logger;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -61,33 +54,17 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
}
this.config = structuredClone(next);
protected override willEnable(config: WsClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: WsClientNetwork): void {
this.options = resolveReportOptions(next);
this.role = next.role ?? 'Universal';
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
@@ -128,6 +105,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
});
socket.on('close', () => {
// Ignore close events from a socket that is no longer the current
// connection. A hot reload (signature change) calls close() then open()
// back-to-back; the old socket's `'close'` event fires AFTER the new
// one is already assigned to `this.socket`, and without this guard it
// would null out `this.socket`, drop `connected`, and schedule an
// unwanted reconnect — observable as a reconnect storm against a
// single-connection backend that kicks duplicates. See issue #97.
if (this.socket !== socket) return;
this.socket = null;
this.connected = false;
if (this.explicitlyClosed || !this.isEnabled) return;
@@ -181,6 +166,3 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
function bindingSignature(net: WsClientNetwork): string {
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
}
@@ -1,6 +1,6 @@
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -9,7 +9,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
@@ -25,17 +25,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private listening = false;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
private readonly log: Logger;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -71,33 +64,13 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
}
this.config = structuredClone(next);
protected override onConfigReplaced(next: WsServerNetwork): void {
this.options = resolveReportOptions(next);
for (const conn of this.connections.values()) conn.options = this.options;
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
@@ -188,7 +161,3 @@ function classifyForwardRole(request: IncomingMessage): WsRole {
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function bindingSignature(net: WsServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
}
+31
View File
@@ -0,0 +1,31 @@
// Tests the self-generated docs (D4): the describe()-walker aggregates every
// declarative action and renders coherent metadata/markdown.
import { describe, it, expect } from 'vitest';
import { collectActionDocs, renderActionDocsMarkdown } from '../src/action-docs';
describe('action-docs', () => {
const docs = collectActionDocs();
it('covers the migrated declarative actions with unique names', () => {
expect(docs.length).toBeGreaterThanOrEqual(120);
const names = docs.map((d) => d.name);
expect(new Set(names).size).toBe(names.length); // no duplicates
});
it('surfaces preset-injected fields + defaults (set_group_ban)', () => {
const ban = docs.find((d) => d.name === 'set_group_ban');
expect(ban).toBeDefined();
expect(ban!.params.map((p) => p.name)).toEqual(['group_id', 'user_id', 'duration']);
const groupId = ban!.params.find((p) => p.name === 'group_id')!;
expect(groupId).toMatchObject({ type: 'uint', required: true });
const duration = ban!.params.find((p) => p.name === 'duration')!;
expect(duration).toMatchObject({ type: 'int', required: false, default: 1800 });
});
it('renders markdown with header + an action section', () => {
const md = renderActionDocsMarkdown(docs);
expect(md).toContain('# OneBot Actions');
expect(md).toContain('`set_group_ban`');
expect(md).toContain('| 参数 | 类型 | 必填 | 默认 | 说明 |');
});
});
+220
View File
@@ -0,0 +1,220 @@
// Interface tests for action-kit — the deepened param-validation module.
// The interface IS the test surface: we drive `parse()` (pure, no ctx) for
// coercion/validation/cross-field, `describe()` for doc metadata, and
// `toHandler()` for the BAD_REQUEST shaping + ctx threading.
import { describe, it, expect } from 'vitest';
import { f, defineAction, groupUserAction, type CoerceResult } from '../src/action-kit';
import type { ApiActionContext } from '../src/api-handler';
import { RETCODE, okResponse } from '../src/types';
const ctx = {} as unknown as ApiActionContext;
function expectErr<T>(r: CoerceResult<T>): { field: string; reason: string } {
if (r.ok) throw new Error(`expected Err, got Ok(${JSON.stringify(r.value)})`);
return { field: r.field, reason: r.reason };
}
function expectOk<T>(r: CoerceResult<T>): T {
if (!r.ok) throw new Error(`expected Ok, got Err(${r.field}: ${r.reason})`);
return r.value;
}
describe('f.uint — positive integer, missing≠0', () => {
const spec = defineAction({ name: 't', params: { x: f.uint() }, run: () => okResponse() });
it('accepts number and numeric string, truncates', () => {
expect(expectOk(spec.parse({ x: 123 }))).toEqual({ x: 123 });
expect(expectOk(spec.parse({ x: '456' }))).toEqual({ x: 456 });
expect(expectOk(spec.parse({ x: 5.7 }))).toEqual({ x: 5 });
});
it('rejects missing / 0 / negative / garbage, naming the field', () => {
expect(expectErr(spec.parse({})).field).toBe('x');
expect(expectErr(spec.parse({})).reason).toBe('is required');
expect(expectErr(spec.parse({ x: 0 })).field).toBe('x'); // 0 is not a valid id
expect(expectErr(spec.parse({ x: -3 })).field).toBe('x');
expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x');
});
});
describe('f.int({min:0}).default — the duration / unmute fix', () => {
const spec = defineAction({ name: 't', params: { d: f.int({ min: 0 }).default(1800) }, run: () => okResponse() });
it('missing ⇒ default; present 0 ⇒ 0 (not the default); negative ⇒ err', () => {
expect(expectOk(spec.parse({}))).toEqual({ d: 1800 });
expect(expectOk(spec.parse({ d: 0 }))).toEqual({ d: 0 }); // the bug the old `|| 1800` had
expect(expectErr(spec.parse({ d: -1 })).field).toBe('d');
});
it('present garbage is an error, not a silent fallback', () => {
expect(expectErr(spec.parse({ d: 'abc' })).field).toBe('d');
});
});
describe('f.messageId — non-zero integer, negatives allowed', () => {
const spec = defineAction({ name: 't', params: { id: f.messageId() }, run: () => okResponse() });
it('accepts negative ids (signed int32 hash), rejects 0 and garbage', () => {
expect(expectOk(spec.parse({ id: -2147483648 }))).toEqual({ id: -2147483648 });
expect(expectOk(spec.parse({ id: 123 }))).toEqual({ id: 123 });
expect(expectErr(spec.parse({ id: 0 })).reason).toBe('must not be 0');
expect(expectErr(spec.parse({ id: 'x' })).field).toBe('id');
});
});
describe('f.bool / f.string / f.enum', () => {
it('bool synonyms', () => {
const s = defineAction({ name: 't', params: { b: f.bool() }, run: () => okResponse() });
expect(expectOk(s.parse({ b: 'on' }))).toEqual({ b: true });
expect(expectOk(s.parse({ b: 0 }))).toEqual({ b: false });
expect(expectErr(s.parse({ b: 'maybe' })).field).toBe('b');
});
it('string allowEmpty toggle', () => {
const s = defineAction({ name: 't', params: { c: f.string({ allowEmpty: false }) }, run: () => okResponse() });
expect(expectErr(s.parse({ c: '' })).field).toBe('c');
expect(expectOk(s.parse({ c: 'x' }))).toEqual({ c: 'x' });
});
it('enum literal set', () => {
const s = defineAction({ name: 't', params: { e: f.enum('a', 'b') }, run: () => okResponse() });
expect(expectOk(s.parse({ e: 'a' }))).toEqual({ e: 'a' });
expect(expectErr(s.parse({ e: 'c' })).field).toBe('e');
});
});
describe('f.array(...).nonEmpty — per-element + non-empty', () => {
const spec = defineAction({ name: 't', params: { ids: f.array(f.uint()).nonEmpty() }, run: () => okResponse() });
it('accepts a non-empty uint array', () => {
expect(expectOk(spec.parse({ ids: [1, 2, 3] }))).toEqual({ ids: [1, 2, 3] });
});
it('rejects empty and names the bad element index', () => {
expect(expectErr(spec.parse({ ids: [] })).field).toBe('ids');
expect(expectErr(spec.parse({ ids: [1, 'x'] })).field).toBe('ids[1]');
});
});
describe('f.message — union passthrough + JSON-array string', () => {
const spec = defineAction({ name: 't', params: { m: f.message() }, run: () => okResponse() });
it('parses a JSON-array string, passes plain string / array through', () => {
expect(expectOk(spec.parse({ m: '[{"type":"text","data":{"text":"hi"}}]' })).m).toEqual([
{ type: 'text', data: { text: 'hi' } },
]);
expect(expectOk(spec.parse({ m: 'hello' })).m).toBe('hello');
expect(expectOk(spec.parse({ m: [{ type: 'face' }] })).m).toEqual([{ type: 'face' }]);
});
it('required when missing', () => {
expect(expectErr(spec.parse({})).reason).toBe('is required');
});
});
describe('optional fields', () => {
const spec = defineAction({ name: 't', params: { x: f.uint().optional() }, run: () => okResponse() });
it('missing ⇒ undefined value, present-invalid ⇒ err', () => {
expect(expectOk(spec.parse({}))).toEqual({ x: undefined });
expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x');
});
});
describe('cross-field rules', () => {
const spec = defineAction({
name: 'set_msg_emoji_like',
params: {
message_id: f.uint().optional(),
group_id: f.uint().optional(),
user_id: f.uint().optional(),
emoji_id: f.uint(),
},
rules: (r) => [r.exactlyOneOf('message_id', ['group_id', 'user_id'])],
run: () => okResponse(),
});
it('passes when exactly one locator group present', () => {
expect(spec.parse({ message_id: 5, emoji_id: 1 }).ok).toBe(true);
expect(spec.parse({ group_id: 9, user_id: 8, emoji_id: 1 }).ok).toBe(true);
});
it('fails when zero or both groups present', () => {
expect(expectErr(spec.parse({ emoji_id: 1 })).reason).toContain('exactly one of');
expect(expectErr(spec.parse({ message_id: 5, group_id: 9, user_id: 8, emoji_id: 1 })).reason).toContain('exactly one of');
});
it('field errors take priority over rule errors (per-field first)', () => {
expect(expectErr(spec.parse({ emoji_id: 0 })).field).toBe('emoji_id');
});
});
describe('toHandler — BAD_REQUEST shaping + ctx threading', () => {
const spec = groupUserAction({
name: 'set_group_ban',
params: { duration: f.int({ min: 0 }).default(1800) },
run: (p) => okResponse({ seen: [p.group_id, p.user_id, p.duration] }),
});
it('success path returns run output with typed/defaulted params', async () => {
const res = await spec.toHandler(ctx)({ group_id: 10, user_id: 20 });
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { seen: [10, 20, 1800] } });
});
it('bad params ⇒ BAD_REQUEST naming the field (not INTERNAL_ERROR)', async () => {
const res = await spec.toHandler(ctx)({ user_id: 20 }); // missing group_id
expect(res.retcode).toBe(RETCODE.BAD_REQUEST);
expect(res.status).toBe('failed');
expect(res.wording).toContain('group_id');
});
});
describe('run raw escape hatch — original params as 3rd arg', () => {
it('exposes untouched params for undeclared keys (alias fallbacks etc.)', async () => {
const spec = defineAction({
name: 't',
params: { user_id: f.uint() },
run: (_p, _ctx, raw) => okResponse({ extra: (raw.long_nick ?? raw.longNick ?? null) as never }),
});
const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi' });
expect(res).toMatchObject({ status: 'ok', data: { extra: 'hi' } });
});
});
describe('toJsonSchema / inputSchema (for the MCP)', () => {
it('emits a JSON Schema fragment per coercer', () => {
expect(f.uint().toJsonSchema()).toEqual({ type: 'integer', minimum: 1 });
expect(f.messageId().toJsonSchema()).toEqual({ type: 'integer', not: { const: 0 } });
expect(f.int({ min: 0 }).default(1800).toJsonSchema()).toEqual({ type: 'integer', minimum: 0, default: 1800 });
expect(f.string({ allowEmpty: false }).toJsonSchema()).toEqual({ type: 'string', minLength: 1 });
expect(f.bool().toJsonSchema()).toEqual({ type: 'boolean' });
expect(f.enum('a', 'b').toJsonSchema()).toEqual({ enum: ['a', 'b'] });
expect(f.array(f.uint()).nonEmpty().toJsonSchema()).toEqual({
type: 'array',
items: { type: 'integer', minimum: 1 },
minItems: 1,
});
expect(f.uint().describe('群号').toJsonSchema()).toEqual({ type: 'integer', minimum: 1, description: '群号' });
});
it('composes an action inputSchema (object + required + defaults)', () => {
const spec = groupUserAction({
name: 'set_group_ban',
params: { duration: f.int({ min: 0 }).default(1800) },
run: () => okResponse(),
});
const { inputSchema } = spec.describe();
expect(inputSchema).toMatchObject({
type: 'object',
additionalProperties: true,
required: ['group_id', 'user_id'],
properties: {
group_id: { type: 'integer', minimum: 1 },
user_id: { type: 'integer', minimum: 1 },
duration: { type: 'integer', minimum: 0, default: 1800 },
},
});
});
});
describe('describe — doc metadata for self-generated docs (D4)', () => {
const spec = groupUserAction({
name: ['set_group_ban', 'ban'],
summary: 'Mute a member',
params: { duration: f.int({ min: 0 }).default(1800).describe('seconds; 0 unmutes') },
run: () => okResponse(),
});
it('exposes name, aliases, and per-param metadata (incl. preset-injected fields)', () => {
const doc = spec.describe();
expect(doc.name).toBe('set_group_ban');
expect(doc.aliases).toEqual(['ban']);
expect(doc.summary).toBe('Mute a member');
const names = doc.params.map((p) => p.name);
expect(names).toEqual(['group_id', 'user_id', 'duration']); // presets surfaced
const duration = doc.params.find((p) => p.name === 'duration');
expect(duration).toMatchObject({ type: 'int', required: false, default: 1800, desc: 'seconds; 0 unmutes' });
});
});
@@ -0,0 +1,224 @@
// Base-level test for the reload state machine that `IOneBotNetworkAdapter`
// now owns (the template method lifted out of all four concrete adapters).
//
// It imports `../src/network/adapter` DIRECTLY rather than the `../src/network`
// barrel on purpose: the barrel re-exports the ws adapters, which pull in
// `@snowluma/websocket`'s native addon — absent in a plain checkout. The base
// class has no such dependency, so the state machine is testable in isolation.
//
// A `ProbeAdapter` deliberately does NOT override `reload()`: it exercises the
// inherited template, with `open()`/`close()` reduced to call-counters so each
// test can assert exactly which transition the template drove (and that the
// returned `NetworkReloadType` — a test-only observability seam — matches).
import { describe, expect, it } from 'vitest';
import {
IOneBotNetworkAdapter,
NetworkReloadType,
type AdapterStatus,
type NetworkAdapterContext,
} from '../src/network/adapter';
import type { NetworkBase } from '../src/types';
interface ProbeConfig extends NetworkBase {
/** The only field `bindingSignature` reads — lets a test flip the binding
* independently of `enabled` / `url`. */
sig?: string;
/** Present only so the client-style `willEnable` override has something to
* require. */
url?: string;
}
const CTX: NetworkAdapterContext = {
uin: '10001',
api: {} as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
class ProbeAdapter extends IOneBotNetworkAdapter<ProbeConfig> {
opens = 0;
closes = 0;
configReplaced = 0;
constructor(name: string, config: ProbeConfig, private readonly requireUrl = false) {
super(name, config, CTX);
}
open(): void {
this.opens++;
// Faithful to the real adapters: only actually enable when the config says
// so. The template should only ever call open() when willEnable is true,
// so this doubles as an invariant check.
if (this.willEnable(this.config)) this.isEnabled = true;
}
close(): void {
this.closes++;
this.isEnabled = false;
}
onEvent(): void { /* unused here */ }
describeStatus(): AdapterStatus {
return { name: this.name, kind: 'httpServer', status: this.isEnabled ? 'ok' : 'disabled', detail: '' };
}
protected bindingSignature(config: ProbeConfig): string {
return config.sig ?? 'fixed';
}
// Mirrors the client adapters (ws-client / http-post): also requires a url.
protected override willEnable(config: ProbeConfig): boolean {
return config.enabled !== false && (!this.requireUrl || !!config.url);
}
protected override onConfigReplaced(_next: ProbeConfig): void {
this.configReplaced++;
}
}
function cfg(partial: Partial<ProbeConfig> = {}): ProbeConfig {
return { name: 'probe', enabled: true, sig: 'A', messageFormat: 'array', reportSelfMessage: false, ...partial };
}
/** Build a probe, optionally bring it to the enabled state, then zero the
* counters so a test observes only reload-driven open/close calls. */
function makeProbe(initial: Partial<ProbeConfig>, opts: { requireUrl?: boolean; open?: boolean } = {}): ProbeAdapter {
const a = new ProbeAdapter('probe', cfg(initial), opts.requireUrl);
if (opts.open) a.open();
a.opens = 0;
a.closes = 0;
a.configReplaced = 0;
return a;
}
describe('IOneBotNetworkAdapter.reload — shared state machine', () => {
it('stable enabled, signature unchanged → Normal (no open/close)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
expect(a.isActive).toBe(true);
const t = await a.reload(cfg({ sig: 'A' }));
expect(t).toBe(NetworkReloadType.Normal);
expect(a.opens).toBe(0);
expect(a.closes).toBe(0);
expect(a.isActive).toBe(true);
});
it('stable disabled stays disabled → Normal (no open/close)', async () => {
const a = makeProbe({ enabled: false, sig: 'A' }); // not opened → wasEnabled=false
expect(a.isActive).toBe(false);
const t = await a.reload(cfg({ enabled: false, sig: 'A' }));
expect(t).toBe(NetworkReloadType.Normal);
expect(a.opens).toBe(0);
expect(a.closes).toBe(0);
expect(a.isActive).toBe(false);
});
it('disabled → enabled → Opened (open only)', async () => {
const a = makeProbe({ enabled: false, sig: 'A' });
const t = await a.reload(cfg({ enabled: true, sig: 'A' }));
expect(t).toBe(NetworkReloadType.Opened);
expect(a.opens).toBe(1);
expect(a.closes).toBe(0);
expect(a.isActive).toBe(true);
});
it('disabled → enabled even with a changed signature → Opened, NOT Reopened', async () => {
// Reopened requires wasEnabled; a signature change alone must not promote
// an Opened into a Reopened.
const a = makeProbe({ enabled: false, sig: 'A' });
const t = await a.reload(cfg({ enabled: true, sig: 'B' }));
expect(t).toBe(NetworkReloadType.Opened);
expect(a.opens).toBe(1);
expect(a.closes).toBe(0);
});
it('enabled → disabled (enabled:false), signature unchanged → Closed (close only)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
const t = await a.reload(cfg({ enabled: false, sig: 'A' }));
expect(t).toBe(NetworkReloadType.Closed);
expect(a.closes).toBe(1);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
it('enabled, signature changed, still enabled → Reopened (close + open)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
const t = await a.reload(cfg({ sig: 'B' }));
expect(t).toBe(NetworkReloadType.Reopened);
expect(a.closes).toBe(1);
expect(a.opens).toBe(1);
expect(a.isActive).toBe(true);
});
it('enabled, signature changed, will disable → Closed (close only, no reopen)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
const t = await a.reload(cfg({ enabled: false, sig: 'B' }));
expect(t).toBe(NetworkReloadType.Closed);
expect(a.closes).toBe(1);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
it('onConfigReplaced runs on every reload, and config is swapped before the decision', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
await a.reload(cfg({ sig: 'A' })); // Normal
await a.reload(cfg({ sig: 'B' })); // Reopened
await a.reload(cfg({ enabled: false, sig: 'B' })); // Closed
expect(a.configReplaced).toBe(3);
expect(a.currentConfig.sig).toBe('B');
expect(a.currentConfig.enabled).toBe(false);
});
describe('willEnable override (client-style: requires url)', () => {
it('enabled:true but no url → willEnable false → stays disabled → Normal', async () => {
const a = makeProbe({ enabled: false, sig: 'A', url: undefined }, { requireUrl: true });
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: undefined }));
expect(t).toBe(NetworkReloadType.Normal);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
it('enabled:true with a url → Opened', async () => {
const a = makeProbe({ enabled: false, sig: 'A' }, { requireUrl: true });
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: 'ws://x' }));
expect(t).toBe(NetworkReloadType.Opened);
expect(a.opens).toBe(1);
expect(a.isActive).toBe(true);
});
it('url removed while enabled (signature unchanged) → willEnable false → Closed', async () => {
// Proves the `wasEnabled && !willEnable` branch fires from the predicate
// alone, independent of any binding-signature change.
const a = makeProbe({ sig: 'A', url: 'ws://x' }, { requireUrl: true, open: true });
expect(a.isActive).toBe(true);
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: undefined }));
expect(t).toBe(NetworkReloadType.Closed);
expect(a.closes).toBe(1);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
});
});
+17 -6
View File
@@ -144,27 +144,34 @@ describe('convertEvent — notice kinds', () => {
expect(invite!.sub_type).toBe('invite');
});
it('group_member_leave: leave / kick / kick_me', async () => {
it('group_member_leave: leave / kick / kick_me / disband', async () => {
const leave = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 0, isKick: false,
userUin: PEER_UIN, operatorUin: 0, leaveType: 'leave',
} as QQEventVariant);
expect(leave!.sub_type).toBe('leave');
const kick = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, isKick: true,
userUin: PEER_UIN, operatorUin: 33333, leaveType: 'kick',
} as QQEventVariant);
expect(kick!.sub_type).toBe('kick');
const kickMe = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: SELF_ID, operatorUin: 33333, isKick: true,
userUin: SELF_ID, operatorUin: 33333, leaveType: 'kick',
} as QQEventVariant);
expect(kickMe!.sub_type).toBe('kick_me');
const disband = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: SELF_ID, operatorUin: 33333, leaveType: 'disband',
} as QQEventVariant);
expect(disband!.sub_type).toBe('disband');
});
it('group_mute: ban vs lift_ban driven by duration', async () => {
@@ -431,14 +438,18 @@ describe('convertEvent — message elements (13 segment types)', () => {
expect((seg2.data as Record<string, unknown>).resid).toBe(50);
});
it('file: name + size + id + url + file_hash, url via mediaUrlResolver', async () => {
it('file: canonical file/file_id/file_size + legacy name/size/id + url + file_hash', async () => {
const seg = await segment(
{ type: 'file', fileName: 'doc.pdf', fileSize: 7, fileId: 'fid', fileHash: 'h' },
{ mediaUrlResolver: async () => 'http://download' },
);
expect(seg.type).toBe('file');
expect(seg.data).toEqual({
name: 'doc.pdf', size: 7, id: 'fid', url: 'http://download', file_hash: 'h',
// NapCat/LLOneBot-style canonical fields
file: 'doc.pdf', file_id: 'fid', file_size: 7,
// legacy SnowLuma fields
name: 'doc.pdf', size: 7, id: 'fid',
url: 'http://download', file_hash: 'h',
});
});
+106
View File
@@ -0,0 +1,106 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
createLogger,
currentRequestId,
getLogLevel,
getRecentLogs,
runWithRequestId,
setLogLevel,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
describe('renderParamsVerbose', () => {
it('shows the full nested structure (message segments), unlike the shallow summary', () => {
const out = renderParamsVerbose({
group_id: 123,
message: [{ type: 'text', data: { text: 'hello' } }, { type: 'at', data: { qq: '456' } }],
});
expect(out).toContain('group_id:123');
expect(out).toContain('text');
expect(out).toContain('"hello"');
expect(out).toContain('"456"');
});
it('truncates long strings (e.g. base64) with a size marker', () => {
const big = 'A'.repeat(5000);
const out = renderParamsVerbose({ file: `base64://${big}` });
expect(out).toContain('base64://');
expect(out).toContain('…<'); // truncation marker
expect(out).toContain('B>');
expect(out.length).toBeLessThan(2000); // bounded by the total budget
});
it('redacts sensitive keys at any depth', () => {
const out = renderParamsVerbose({
access_token: 'super-secret-value',
nested: { password: 'hunter2', SECRET: 'x', ok: 'visible' },
});
expect(out).not.toContain('super-secret-value');
expect(out).not.toContain('hunter2');
expect(out).toContain('"***"');
expect(out).toContain('"visible"'); // non-sensitive keys still rendered
});
it('handles circular references without throwing', () => {
const a: Record<string, unknown> = { name: 'a' };
a.self = a;
expect(() => renderParamsVerbose(a)).not.toThrow();
expect(renderParamsVerbose(a)).toContain('[circular]');
});
});
describe('logger trace level + request correlation', () => {
let prevLevel: string;
beforeEach(() => {
prevLevel = getLogLevel();
});
afterEach(() => {
setLogLevel(prevLevel);
});
it('captures trace into the in-memory buffer only when the level is trace', () => {
const log = createLogger('Test.Trace');
const marker = `trace-marker-${Math.trunc(performance.now())}-${getRecentLogs(1).length}`;
setLogLevel('info');
log.trace('off %s', marker);
expect(getRecentLogs(2000).some((e) => e.message.includes(marker))).toBe(false);
setLogLevel('trace');
log.trace('on %s', marker);
const hit = getRecentLogs(2000).find((e) => e.message.includes(marker));
expect(hit).toBeDefined();
expect(hit?.level).toBe('trace');
});
it('does NOT evaluate a lazy producer when trace is off (the efficiency guarantee)', () => {
const log = createLogger('Test.Lazy');
const produce = vi.fn(() => ['lazy payload']);
setLogLevel('info');
log.trace(produce);
expect(produce).not.toHaveBeenCalled();
setLogLevel('trace');
log.trace(produce);
expect(produce).toHaveBeenCalledTimes(1);
});
it('stamps the ambient request id onto entries emitted inside runWithRequestId', () => {
const log = createLogger('Test.Req');
setLogLevel('trace');
const marker = `req-marker-${Math.trunc(performance.now())}`;
expect(currentRequestId()).toBeUndefined();
runWithRequestId(4242, () => {
expect(currentRequestId()).toBe(4242);
log.trace('inside %s', marker);
});
expect(currentRequestId()).toBeUndefined();
const hit = getRecentLogs(2000).find((e) => e.message.includes(marker));
expect(hit?.req).toBe(4242);
expect(hit?.line).toContain('[req#4242]');
});
});
+12 -6
View File
@@ -481,16 +481,22 @@ describe('parseMessage', () => {
]);
});
it('drops a file segment with no file_id (upload-first contract)', async () => {
// Path-only segments aren't supported here — callers must
// upload via `upload_group_file` / `upload_private_file` first
// to obtain a file_id. Dropping with a warning is preferable
// to silently kicking off an upload from inside the message
// parser, which can't fail loudly without changing call sites.
it('parses {type:"file", file:"/path"} (no file_id) into a file element with url', async () => {
// Inline file path: the parser now accepts file/url/path and stores
// it in `url`. The send layer (sendGroupMessage / sendPrivateMessage)
// handles the actual upload so the parser stays side-effect-free.
const result = await parseMessage(
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
false,
);
expect(result).toEqual([{ type: 'file', url: '/local/path/a.bin' }]);
});
it('drops a file segment with neither file_id nor file/url', async () => {
const result = await parseMessage(
[{ type: 'file', data: {} } as any],
false,
);
expect(result).toEqual([]);
});
@@ -25,7 +25,9 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
this.closes++;
this.isEnabled = false;
}
reload(next: FakeNetworkConfig): NetworkReloadType {
// Keeps its own reload — this is a manager test double, not a reload test;
// base.reload became concrete so this is now a genuine override.
override reload(next: FakeNetworkConfig): NetworkReloadType {
this.reloads++;
this.config = structuredClone(next);
if (next.enabled === false && this.isEnabled) {
@@ -38,6 +40,9 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
}
return NetworkReloadType.Normal;
}
protected bindingSignature(config: FakeNetworkConfig): string {
return JSON.stringify(config);
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
this.events.push(event);
this.lastPayloads.push(payload);
+35 -4
View File
@@ -105,14 +105,13 @@ describe('send_group_msg with {type:"file"} segment', () => {
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// Same upload-by-reference contract as the c2c file path —
// missing file_id means there's nothing to publish.
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const publish = vi.fn();
const upload = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
groupFile: { publish, upload },
} as any,
resolveUserUid: vi.fn(),
} as any);
@@ -120,10 +119,42 @@ describe('send_group_msg with {type:"file"} segment', () => {
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
{ type: 'file', data: {} }, // no file_id and no url
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(publish).not.toHaveBeenCalled();
expect(upload).not.toHaveBeenCalled();
});
it('file segment with url (no file_id) auto-uploads via groupFile.upload (not publish)', async () => {
// Happy path for inline file sending: the bot passes a local path
// directly. upload() internally calls publish(), so we must NOT
// call publish() a second time.
const upload = vi.fn(async (_gid: number, _src: string, _name: string, _folder: string, _doUpload: boolean) =>
({ fileId: 'auto-fid', fileHash: null }));
const publish = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendGroup: vi.fn() },
groupFile: { upload, publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [{
type: 'file', data: { file: '/tmp/audio.wav', name: 'audio.wav' },
}] as any, false);
expect(upload).toHaveBeenCalledOnce();
const [gid, src, name, folder, doUpload] = upload.mock.calls[0]!;
expect(gid).toBe(12345);
expect(src).toBe('/tmp/audio.wav');
expect(name).toBe('audio.wav');
expect(folder).toBe('/');
expect(doUpload).toBe(true);
// publish must NOT be called — upload() already handles it internally
expect(publish).not.toHaveBeenCalled();
});
});
@@ -227,4 +227,33 @@ describe('send_private_msg with {type:"file"} segment', () => {
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
it('file segment with url (no file_id) auto-uploads via groupFile.uploadPrivate (not sendC2cFile)', async () => {
// uploadPrivate() internally calls sendC2cFile() — must NOT call it again.
const uploadPrivate = vi.fn(async (_uid: number, _src: string, _name: string, _doUpload: boolean) =>
({ fileId: 'auto-fid', fileHash: null }));
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage },
groupFile: { uploadPrivate },
} as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file: '/tmp/audio.wav', name: 'audio.wav' },
}] as any, false);
expect(uploadPrivate).toHaveBeenCalledOnce();
const [uid, src, name, doUpload] = uploadPrivate.mock.calls[0]!;
expect(uid).toBe(67890);
expect(src).toBe('/tmp/audio.wav');
expect(name).toBe('audio.wav');
expect(doUpload).toBe(true);
// sendC2cFile must NOT be called — uploadPrivate() handles it internally
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,181 @@
// Regression for issue #97: a hot reload that swaps WsClientAdapter's
// underlying socket (binding-signature change → `await this.close()` then
// `await this.open()`) leaves the OLD socket's `'close'` event scheduled to
// fire AFTER the new socket has already been assigned to `this.socket`.
// Without a guard in the close handler that event would null out
// `this.socket`, drop `connected`, and schedule an unwanted reconnect — on a
// single-connection backend that kicks duplicates, this snowballed into a
// reconnect storm. The fix is a one-line identity check; these tests pin it.
//
// We mock `@snowluma/websocket` (its native addon isn't built in a plain
// checkout, mirroring the comment in adapter-reload-state-machine.test.ts)
// with a minimal EventEmitter-backed fake whose `'open'` / `'close'` events
// are driven explicitly by the test — this is exactly the lifecycle the
// adapter's connect() wires up to. Both the class and the instances registry
// live inside `vi.hoisted` so they are constructed BEFORE `vi.mock` runs.
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { FakeWebSocket, instances } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { EventEmitter } = require('node:events') as typeof import('node:events');
const instances: FakeWebSocket[] = [];
class FakeWebSocket extends EventEmitter {
// 1 = OPEN, 2 = CLOSING, 3 = CLOSED — matches @snowluma/websocket.
public readyState = 1;
public closeArgs?: { code: number; reason: string };
public readonly url: string;
constructor(url: string, _opts: unknown) {
super();
this.url = url;
instances.push(this);
}
close(code = 1000, reason = 'normal'): void {
if (this.readyState === 3 || this.readyState === 2) return;
this.readyState = 2;
this.closeArgs = { code, reason };
// Crucially DO NOT auto-emit 'close' here — real WebSockets emit it
// only after the underlying net socket actually ends, which is the
// deferred delivery that creates the race. Tests trigger it
// explicitly via simulateClose() below.
}
send(_payload: string, cb?: (err?: Error | null) => void): void {
cb?.(null);
}
simulateOpen(): void {
this.emit('open');
}
simulateClose(): void {
this.readyState = 3;
this.emit('close');
}
}
return { FakeWebSocket, instances };
});
vi.mock('@snowluma/websocket', () => ({ WebSocket: FakeWebSocket }));
// Imports below resolve through the vi.mock above.
import { WsClientAdapter } from '../src/network/ws-client-adapter';
import type { NetworkAdapterContext } from '../src/network/adapter';
import type { WsClientNetwork } from '../src/types';
function ctx(): NetworkAdapterContext {
return {
uin: '10001',
api: { processRequest: async () => '' } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
}
function cfg(over: Partial<WsClientNetwork> = {}): WsClientNetwork {
return {
enabled: true,
url: 'ws://127.0.0.1:8080/',
role: 'Universal',
reconnectIntervalMs: 1000,
...over,
} as WsClientNetwork;
}
describe('WsClientAdapter — stale-socket close guard (issue #97)', () => {
beforeEach(() => {
instances.length = 0;
});
it('ignores the close event from a socket replaced by a hot reload', async () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
expect(instances).toHaveLength(1);
const a = instances[0];
a.simulateOpen();
// Hot reload with a binding-signature change (different URL). The base
// class drives `await this.close()` then `await this.open()`; the close
// handler on socket A has NOT yet fired (real flow: WebSocket.close()
// schedules the close frame + a deferred 'close' event).
await adapter.reload(cfg({ url: 'ws://127.0.0.1:8081/' }));
expect(instances).toHaveLength(2);
const b = instances[1];
expect(b).not.toBe(a);
// Delayed 'close' from the stale socket arrives now.
a.simulateClose();
// Pre-fix behavior: the close handler would null `this.socket`, drop
// `connected`, and scheduleReconnect → after the interval a third
// socket would appear. Post-fix: the guard short-circuits.
vi.advanceTimersByTime(10_000);
expect(instances).toHaveLength(2);
// The new socket is still the current connection: simulate its 'open'
// and the adapter reports 'ok' / '已连接' (only reachable when
// `this.socket` is non-null AND `connected` is true).
b.simulateOpen();
const status = adapter.describeStatus();
expect(status.status).toBe('ok');
expect(status.detail).toBe('已连接');
} finally {
vi.useRealTimers();
}
});
it('still drives reconnect when the CURRENT socket closes unexpectedly', () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
const a = instances[0];
a.simulateOpen();
// The current socket dies on its own (no close() / no reload). The
// handler must still null state and schedule the reconnect — the
// guard only suppresses STALE events, not real ones.
a.simulateClose();
vi.advanceTimersByTime(1500);
expect(instances).toHaveLength(2); // reconnect spun up a new socket
const status = adapter.describeStatus();
expect(status.status).toBe('warn');
} finally {
vi.useRealTimers();
}
});
it('does not reconnect when adapter.close() races with an in-flight close event', () => {
vi.useFakeTimers();
try {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
const a = instances[0];
a.simulateOpen();
// User-driven close (e.g. config disabled): close() flips
// explicitlyClosed=true and detaches `this.socket = null`
// synchronously. The deferred 'close' event from A then fires; the
// guard sees `this.socket !== socket` (this.socket is already null)
// and short-circuits — even though the explicitlyClosed flag would
// also have done so, the guard is the FIRST line of defence and
// matches the issue's exact stated invariant.
adapter.close();
a.simulateClose();
vi.advanceTimersByTime(10_000);
expect(instances).toHaveLength(1); // no reconnect, no new socket
const status = adapter.describeStatus();
expect(status.status).toBe('disabled');
} finally {
vi.useRealTimers();
}
});
});
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/proto-defs",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
@@ -35,6 +35,10 @@
"types": "./src/notify.ts",
"default": "./src/notify.ts"
},
"./ptt-trans": {
"types": "./src/ptt-trans.ts",
"default": "./src/ptt-trans.ts"
},
"./oidb": {
"types": "./src/oidb.ts",
"default": "./src/oidb.ts"
+97
View File
@@ -0,0 +1,97 @@
import type { pb, uint_32, uint_64, bytes } from '@snowluma/proton';
/**
* Voice-to-text (语音转文字) request/response protobufs for the
* `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` SSO commands.
*
* Reverse-engineered from QQ-NT `wrapper.node` (macOS 9.9.x) —
* `im_core/msg/ptt/ptt_trans_worker.cc` (`EncodeC2CPtt` / `EncodeTroopPtt`
* build the request, `OnTranslateResp` decodes the response). The wire shape
* here is RE-derived and NOT yet verified against a live server: the numeric
* field tags are read straight from the encoder, but the length-delimited
* fields (uuid / md5) and the response `text` tag should be confirmed with a
* single live capture before relying on them.
*
* Flow: send Trans{C2C,Group}PttReq → response carries the text inline when
* transcription is already done; when it's empty the server transcribes
* asynchronously (no dedicated push command exists — see NotifyTransUpdate),
* so the caller re-sends with backoff until the text arrives or it times out.
*/
/** Source ptt-element field (NT internal tag) noted in the comment after each. */
export interface C2CPttTransItem {
msgId?: pb<1, uint_64>;
senderUin?: pb<2, uint_64>;
receiverUin?: pb<3, uint_64>;
uuid?: pb<4, string>; // element 45503 (c2c ptt uuid)
duration?: pb<5, uint_32>; // element 45906 (seconds)
size?: pb<6, uint_32>; // element 45405 (bytes)
format?: pb<7, uint_32>; // element 45907 (voice codec)
eventType?: pb<8, uint_32>; // element 45921
md5?: pb<9, bytes>; // element 45406 (raw 16-byte md5)
}
export interface GroupPttTransItem {
msgId?: pb<1, uint_64>;
senderUin?: pb<2, uint_64>;
groupUin?: pb<3, uint_64>;
fileId?: pb<4, uint_32>; // element 45903 (group ptt numeric file id)
md5?: pb<5, bytes>; // element 45406
duration?: pb<6, uint_32>; // element 45906
size?: pb<7, uint_32>; // element 45405
format?: pb<8, uint_32>; // element 45907
uuid?: pb<9, string>; // element 45503
eventType?: pb<10, uint_32>; // element 45921
ext?: pb<11, uint_32>; // element 49202 (optional)
}
/**
* Outer request. `type` selects the scene (1 = group, 2 = c2c) and only the
* matching item is populated — group at field 2, c2c at field 3.
*/
export interface PttTransReq {
type?: pb<1, uint_32>;
groupItem?: pb<2, GroupPttTransItem>;
c2cItem?: pb<3, C2CPttTransItem>;
}
/** Per-scene result. `errCode` 0 = ok; `text` carries the recognised speech. */
export interface C2CPttTransResult {
errCode?: pb<2, uint_32>;
text?: pb<8, string>; // VERIFY LIVE: text tag from OnTranslateResp
}
export interface GroupPttTransResult {
errCode?: pb<2, uint_32>;
text?: pb<9, string>; // VERIFY LIVE: text tag from OnTranslateResp
}
/**
* Outer response. `type` echoes the scene; result is at field 2 (group) /
* field 3 (c2c). An empty `text` with `errCode == 0` means "transcribing,
* retry later".
*/
export interface PttTransResp {
type?: pb<1, uint_32>;
groupResult?: pb<2, GroupPttTransResult>;
c2cResult?: pb<3, C2CPttTransResult>;
}
/**
* Async result push (Event 0x210 subType 61), sent after the request once the
* server finishes transcribing. **Live-verified** against a real push: the
* outer carries a single result item at field 2; the item echoes the request
* `msgId` at field 1 (the correlation key) and the recognised text at field 8.
*/
export interface PttTransPushItem {
msgId?: pb<1, uint_64>; // echoes the request msgId — correlation key
text?: pb<8, string>; // recognised text
senderUin?: pb<9, uint_64>;
receiverUin?: pb<10, uint_64>;
uuid?: pb<13, string>;
}
export interface PttTransPush {
field1?: pb<1, uint_32>;
item?: pb<2, PttTransPushItem>;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/protocol",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
+20 -2
View File
@@ -153,7 +153,12 @@ export interface GroupMemberLeave extends QQEvent {
operatorUin: number;
userUid?: string;
operatorUid?: string;
isKick: boolean;
/**
* Protocol-level reason the member left, derived from
* GroupChange.decreaseType. `kick` is split into kick / kick_me
* downstream (OneBot converter) by comparing against selfId.
*/
leaveType: 'leave' | 'kick' | 'disband';
}
export interface GroupMuteEvent extends QQEvent {
@@ -263,6 +268,18 @@ export interface GroupMsgEmojiLikeEvent extends QQEvent {
isAdd: boolean;
}
/**
* Async voice-to-text result, pushed by the server (Event 0x210 subType 61)
* after a `pttTrans.Trans{C2C,Group}PttReq`. `msgId` echoes the request's
* msgId — the correlation key a pending `fetch_ptt_text` waits on. Internal
* (not surfaced to OneBot clients).
*/
export interface PttTransResultEvent extends QQEvent {
kind: 'ptt_trans_result';
msgId: number;
text: string;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -280,4 +297,5 @@ export type QQEventVariant =
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent
| GroupMsgEmojiLikeEvent;
| GroupMsgEmojiLikeEvent
| PttTransResultEvent;
+82 -4
View File
@@ -16,6 +16,7 @@ export interface ReplyEventLookup {
const MAX_TEXT_PREVIEW = 50;
const MAX_REPLY_BODY_PREVIEW = 30;
const MAX_CARD_TITLE_PREVIEW = 30;
/** "[群名(12345)]" if known, else "12345" (or "0" if missing). */
export function formatGroup(identity: IdentityService, groupId: number): string {
@@ -95,8 +96,25 @@ function renderSegment(type: string, data: Record<string, unknown>): string {
case 'reply': return `[回复:${data.id ?? ''}]`;
case 'record': return '[语音]';
case 'video': return '[视频]';
case 'file': return data.file ? `[文件:${truncate(String(data.file), 20)}]` : '[文件]';
case 'json': return '[JSON]';
case 'file': {
// OneBot file segments carry the filename under `data.name`
// (see to-segment.ts). Keep `data.file` as a fallback for any
// upstream that still uses the older field name.
const fileName = data.name ?? data.file;
return fileName ? `[文件:${truncate(String(fileName), 20)}]` : '[文件]';
}
case 'json': {
// OneBot json segments carry Tencent's ARK / mini-program / share card
// payload as a JSON string under data.data. For the log preview we try
// to surface a human-readable title — "[卡片:某某分享]" instead of just
// "[JSON]". The full payload stays intact in the OneBot segment for any
// downstream consumer that wants to parse it.
// For QQ's server-side fallback (e.g. cardId -896954183 "当前QQ版本不支持
// 此应用,请升级"), the `prompt` field carries that message — surfaces it
// so the operator sees the actual reason instead of "[JSON]".
const title = extractCardTitle(data.data);
return title ? `[卡片:${truncate(title, MAX_CARD_TITLE_PREVIEW)}]` : '[JSON]';
}
case 'xml': return '[XML]';
case 'markdown': return '[Markdown]';
case 'forward': return '[聊天记录]';
@@ -109,6 +127,64 @@ function truncate(s: string, max: number): string {
return s.length > max ? `${s.slice(0, max)}...` : s;
}
/**
* Best-effort extraction of an ARK / mini-program / share card's title for the
* log preview. The OneBot json segment's `data.data` is the raw JSON string
* Tencent embeds in the lightApp element; its shape varies by card type, but
* the common locations for a human-readable headline are:
*
* - meta.detail_1.title — mini-program shares
* - meta.detail.title — news / image shares
* - meta.news.title — news shares (alt schema)
* - meta.{music,video,mannounce}.title — domain-specific shares
* - meta.<single-key>.title — generic single-section ARK
* - prompt — QQ's server-side fallback cards (e.g. cardId
* -896954183 "当前QQ版本不支持此应用,请升级")
* - desc — some richer cards
*
* Returns null on parse failure / no recognised field — caller falls back to
* "[JSON]". Pure best-effort: this is a log-preview hint, not a contract.
*/
function extractCardTitle(raw: unknown): string | null {
if (typeof raw !== 'string' || raw.length === 0) return null;
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
const root = parsed as Record<string, unknown>;
const meta = root.meta;
if (meta && typeof meta === 'object' && !Array.isArray(meta)) {
const m = meta as Record<string, unknown>;
const sections = ['detail_1', 'detail', 'news', 'mannounce', 'music', 'video'];
for (const key of sections) {
const t = readTitle(m[key]);
if (t) return t;
}
// Fallback: meta has exactly one section — use its title.
const keys = Object.keys(m);
if (keys.length === 1) {
const t = readTitle(m[keys[0]]);
if (t) return t;
}
}
if (typeof root.prompt === 'string' && root.prompt.trim()) return root.prompt.trim();
if (typeof root.desc === 'string' && root.desc.trim()) return root.desc.trim();
return null;
}
function readTitle(node: unknown): string | null {
if (!node || typeof node !== 'object' || Array.isArray(node)) return null;
const t = (node as Record<string, unknown>).title;
if (typeof t !== 'string') return null;
const trimmed = t.trim();
return trimmed.length > 0 ? trimmed : null;
}
/**
* Resolve a `reply` segment's referenced message and return a short
* "[回复 user: body...]" string. On miss (older than store retention,
@@ -182,8 +258,10 @@ export function formatEvent(identity: IdentityService, event: QQEventVariant): s
return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`;
case 'group_member_join':
return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`;
case 'group_member_leave':
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`;
case 'group_member_leave': {
const leaveAction = event.leaveType === 'disband' ? '随群解散' : event.leaveType === 'kick' ? '被踢出' : '退出';
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${leaveAction} ${formatGroup(identity, event.groupId)}`;
}
case 'group_mute':
return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`;
case 'group_admin':
@@ -8,11 +8,13 @@ import type {
ReqDataHighwayHead,
RespDataHighwayHead,
} from '@snowluma/proto-defs/highway';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import net from 'net';
import type { BridgeContext } from '../bridge-context';
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
const log = createLogger('Highway');
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
@@ -69,7 +71,7 @@ export async function fetchHighwaySession(bridge: BridgeContext): Promise<Highwa
}
}
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
log.trace('session %s:%d sig=%dB', session.host, session.port, (session.sigSession as Uint8Array).length);
return session;
}
@@ -286,6 +288,6 @@ export async function uploadHighwayHttp(
);
}
offset += chunkSize;
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
log.trace('uploaded %d/%d bytes', offset, bytes.length);
}
}
@@ -12,6 +12,7 @@ import type {
GeneralGrayTipInfo,
NewFriend,
} from '@snowluma/proto-defs/notify';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
@@ -28,6 +29,7 @@ const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.PttTransResult: return decodePttTransResult(ctx);
// 138 (other-recalled) and 139 (self-recalled) share the same
// FriendRecall wire shape; the helper picks the right uid side
// based on the subType.
@@ -58,6 +60,20 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
return [];
};
// Voice-to-text async result push. Wire shape (live-verified):
// { f1: uint, f2: { f1 = msgId (echoes the request), f8 = text, ... } }
// `msgId` is the correlation key a pending fetch_ptt_text waits on; we surface
// it + the recognised text as an internal `ptt_trans_result` event.
function decodePttTransResult(ctx: MsgPushContext): QQEventVariant[] {
const push = protobuf_decode<PttTransPush>(ctx.content);
const item = push?.item;
if (!item) return [];
const msgId = Number(item.msgId ?? 0n);
const text = item.text ?? '';
if (!msgId || !text) return [];
return [{ kind: 'ptt_trans_result', time: ctx.head.timestamp, selfUin: ctx.selfUin, msgId, text }];
}
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protobuf_decode<FriendRequest>(ctx.content);
if (!request?.info) return [];
@@ -7,15 +7,42 @@ import type { MsgPushDecoder } from '../registry';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protobuf_decode<GroupAdmin>(ctx.content);
if (!admin?.body) return [];
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
if (!extra) return [];
// proton materializes an *absent* embedded-message field as an empty
// `{}` rather than leaving it undefined, so the old
// `extraEnable !== undefined` promote/demote test was always true and
// every demote got reported as a promotion (with a fallback userUin).
// The live sub-message is the one that actually carries an `adminUid`
// — key off that instead.
const enableUid = admin.body.extraEnable?.adminUid;
const disableUid = admin.body.extraDisable?.adminUid;
const adminUid = enableUid || disableUid;
if (!adminUid) return [];
const groupId = admin.groupUin ?? 0;
const set = !!enableUid;
const userUin = resolveUidToUin(ctx.identity, groupId, adminUid, ctx.fromUin);
// Keep the in-memory member cache in step with the promotion/demotion.
// `get_group_member_info` serves straight from this cache on its
// default (no_cache=false) path — and we deliberately *don't*
// force-refresh there, because clients like OlivaDice/MaiBot query it
// once per inbound message and a per-message OIDB refetch trips
// Tencent risk-control (see the ContactsApi member-list cache). So if
// we don't patch the role here, a freshly-promoted admin keeps reading
// back as `member` until the member-list TTL lapses, and permission
// gates reject their commands (#93). Only touch a member we already
// know, and never downgrade the owner.
const cached = ctx.identity.findGroupMember(groupId, userUin);
if (cached && cached.role !== 'owner') {
ctx.identity.updateGroupMember(groupId, { ...cached, role: set ? 'admin' : 'member' });
}
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: admin.groupUin ?? 0,
userUin: resolveUidToUin(ctx.identity, admin.groupUin ?? 0, extra.adminUid ?? '', ctx.fromUin),
set: admin.body.extraEnable !== undefined,
groupId,
userUin,
set,
};
return [ev];
};
@@ -23,6 +23,26 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
return [ev];
};
// QQ's GroupChange.decreaseType (proto field 4) on a member-decrease push:
// 3 → the bot itself was kicked
// 129 → the group was disbanded
// 130 → voluntary leave
// 131 → another member was kicked
// 0 / absent → treat as voluntary leave (defensive default)
// The kick → kick_me distinction (was it us?) is decided downstream in the
// OneBot converter via selfId; here we only resolve the protocol-level reason.
function leaveTypeFromDecreaseType(dt: number): GroupMemberLeave['leaveType'] {
switch (dt) {
case 129:
return 'disband';
case 0:
case 130:
return 'leave';
default:
return 'kick';
}
}
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
if (!change) return [];
@@ -39,7 +59,7 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
userUid,
operatorUid,
isKick: dt !== 0 && dt !== 130,
leaveType: leaveTypeFromDecreaseType(dt),
};
return [ev];
};
+8
View File
@@ -36,6 +36,14 @@ export enum Event0x2DCSubType {
export enum Event0x210SubType {
FriendRequestNotice = 35,
/**
* Voice-to-text (语音转文字) async result push, fired after a
* `pttTrans.Trans{C2C,Group}PttReq` once the server finishes transcribing.
* Live-verified body: `{ f1:uint, f2:{ f1=msgId, f8=text, ... } }`. There's
* no static sys_msg_0x210_0x3d handler — the ptt-trans subsystem registers
* it dynamically; we decode it into an internal `ptt_trans_result` event.
*/
PttTransResult = 61,
/**
* Outgoing friend-message recall — bot recalled its own message that
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
+3
View File
@@ -128,6 +128,9 @@ export async function invokeOidb<TCtx extends OidbSender, TReq, TResp, TParams,
subCommand
);
}
// success=false without an OIDB error code = the packet send itself failed;
// surface it instead of silently resolving with an undecoded response.
throw new Error(result.errorMessage || 'packet send failed');
}
const respBytes = result.responseData ?? new Uint8Array(0);
+41 -39
View File
@@ -98,9 +98,9 @@ export class IncomingPacketPipeline {
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
} else if (this.needsStrangerResolve(event)) {
void this.dispatchAfterStrangerResolve(event).catch((err) => {
this.log.warn('dispatchAfterStrangerResolve failed: %s',
} else if (this.needsGroupInviteEnrich(event)) {
void this.dispatchGroupInvite(event).catch((err) => {
this.log.warn('dispatchGroupInvite failed: %s',
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
} else {
@@ -125,28 +125,25 @@ export class IncomingPacketPipeline {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
/** Group join requests carry only the requester's UID (no UIN). We
* fire a UID-form FetchUserProfile to resolve UIN + nickname before
* dispatch so the OneBot layer's `user_id` field is populated and
* the consumer bot's follow-up `get_stranger_info` lookup succeeds.
* Mirrors Lagrange's `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
/** Every group_invite that carries a requester UID gets async
* enrichment before dispatch. Two INDEPENDENT things are filled in:
*
* Also catches the legacy cache-pollution case: pre-fix builds
* stored `<requester_uid> → <groupUin>` in the identity DB when
* the decoder's fallback was `ctx.fromUin` (= group's own uin on
* a group-scoped push). After upgrade, the decoder's
* `resolveUidToUin` hits that polluted mapping and returns the
* groupUin instead of 0, so the `fromUin <= 0` guard alone would
* silently skip the resolve and re-emit the bug. Treating
* `fromUin === groupId` as bogus forces the async resolve to
* overwrite the polluted entry on the next event. */
private needsStrangerResolve(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_invite' }> {
if (event.kind !== 'group_invite' || !event.fromUid) return false;
if (event.fromUin <= 0) return true;
// Pollution signature — a real requester's uin would never equal
// the group's own uin. Force a re-resolve so the cache self-heals.
if (event.groupId > 0 && event.fromUin === event.groupId) return true;
return false;
* 1. The verify COMMENT — the text the requester typed ("你们好" etc.).
* It is NEVER in the push; it lives on the OIDB pending-request
* queue, so we ALWAYS fetch it (mirrors Lagrange's unconditional
* `FetchGroupRequests`; NapCat reads the equivalent
* `notify.postscript`). See issue #98.
* 2. The requester's UIN + nickname — only when not already resolved
* (the push carries a bare UID). Mirrors Lagrange's
* `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
*
* These USED to be coupled — the comment fetch piggy-backed on the
* uin-resolve condition, so a requester whose uin was already cached
* silently lost their comment (bug #98). They're now decoupled inside
* `dispatchGroupInvite`; this guard just routes every uid-bearing
* group_invite onto the async path. */
private needsGroupInviteEnrich(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_invite' }> {
return event.kind === 'group_invite' && !!event.fromUid;
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
@@ -163,31 +160,36 @@ export class IncomingPacketPipeline {
this.emit(event);
}
private async dispatchAfterStrangerResolve(event: Extract<QQEventVariant, { kind: 'group_invite' }>): Promise<void> {
private async dispatchGroupInvite(event: Extract<QQEventVariant, { kind: 'group_invite' }>): Promise<void> {
const uid = event.fromUid;
if (uid) {
// Fire profile + pending-request lookups in PARALLEL — they're
// independent OIDB calls (0xFE1_2 stranger profile + 0x10C0
// pending request queue). Both `Promise.allSettled` so a flake
// on one path doesn't kill the other.
const subType = event.subType === 'invite' ? 'invite' : 'add';
// ALWAYS fetch the verify comment (it's never in the push). Resolve
// the UID→UIN profile only when the requester isn't already known —
// `fromUin === groupId` is the legacy cache-pollution signature
// (decoder fell back to the group's own uin) and must force a
// re-resolve so the cache self-heals. The two are independent OIDB
// calls (0xFE1_2 profile + 0x10C0 request queue); `Promise.allSettled`
// so a flake on one path can't kill the other.
const needsProfile = event.fromUin <= 0 || (event.groupId > 0 && event.fromUin === event.groupId);
const [profileR, requestR] = await Promise.allSettled([
this.deps.resolveStrangerProfile(uid),
needsProfile ? this.deps.resolveStrangerProfile(uid) : Promise.resolve(null),
this.deps.resolveGroupJoinRequest(event.groupId, uid, subType),
]);
if (profileR.status === 'fulfilled' && profileR.value && profileR.value.uin > 0) {
event.fromUin = profileR.value.uin;
} else if (profileR.status === 'rejected') {
this.log.warn('failed to resolve stranger profile: uid=%s err=%s',
uid, profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason));
if (needsProfile) {
if (profileR.status === 'fulfilled' && profileR.value && profileR.value.uin > 0) {
event.fromUin = profileR.value.uin;
} else if (profileR.status === 'rejected') {
this.log.warn('failed to resolve stranger profile: uid=%s err=%s',
uid, profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason));
}
}
if (requestR.status === 'fulfilled' && requestR.value) {
// NapCat surfaces the verify text as `comment` on the OneBot
// event (`postscript` server-side). Without this the bot's
// approval-prompt template renders an empty body line — see
// `dev/NapCatQQ/.../napcat-onebot/index.ts:496-498`.
// The verify text the requester typed; NapCat surfaces it as
// `notify.postscript`. Without this the OneBot `comment` field is
// empty — bug #98.
event.message = requestR.value.comment;
} else if (requestR.status === 'rejected') {
this.log.warn('failed to resolve group join request: groupId=%d uid=%s err=%s',
@@ -113,26 +113,37 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
expect(captured[0]).toMatchObject({ fromUin: 0, fromUid: 'u_x' });
});
it('skips the stranger resolve when fromUin is already populated (cache hit)', async () => {
// If the decoder's `resolveUidToUin` already found the uin in
// the local cache (e.g. group member roster), we shouldn't waste
// a wire call.
it('still fetches + applies the comment when fromUin is already cached (issue #98)', async () => {
// THE bug: the comment fetch used to piggy-back on the uin-resolve
// gate, so a requester whose uin was already in cache (group member
// roster, prior @-mention, re-application…) silently lost their
// verify text — the OneBot `comment` came out empty. The comment
// and the uin resolve are now decoupled: the comment is fetched
// unconditionally; only the (wasteful) profile lookup is skipped on
// a cache hit.
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
const resolveGroupJoinRequest = vi.fn(async () => ({ comment: '求通过', sequence: 42 }));
const { pipeline, captured } = makePipeline({ resolveStrangerProfile, resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 99999, fromUid: 'u_known',
subType: 'invite', message: '', flag: 'invite:12345:u_known',
subType: 'add', message: '', flag: 'add:12345:u_known',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
// Profile lookup is skipped — the uin is already known, no wasted call…
expect(resolveStrangerProfile).not.toHaveBeenCalled();
// …but the comment IS still fetched from the pending-request queue
// and applied to the emitted event.
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(12345, 'u_known', 'add');
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({ fromUin: 99999, fromUid: 'u_known' });
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.fromUin).toBe(99999);
expect(ev.message).toBe('求通过');
});
it('populates event.message from the pending-request queue (NapCat parity)', async () => {
@@ -260,9 +271,10 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
});
});
it('skips the stranger resolve when fromUid is empty (no uid to look up by)', async () => {
it('skips both lookups when fromUid is empty (no uid to look up by)', async () => {
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
const resolveGroupJoinRequest = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile, resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
@@ -274,7 +286,9 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
// No uid → nothing to query by → neither lookup runs, event still emits.
expect(resolveStrangerProfile).not.toHaveBeenCalled();
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/proton",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/runtime",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.9.4",
"version": "1.9.10",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
-23
View File
@@ -1,23 +0,0 @@
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { SNOWLUMA_ACTIONS } from '../src';
describe('SnowLuma action list', () => {
it('stays in sync with core registerAction calls', () => {
// Actions moved out of @snowluma/core into the dedicated
// @snowluma/onebot package in the RoadMap #3 4-way split.
const actionsDir = fileURLToPath(new URL('../../onebot/src/actions/', import.meta.url));
const registered = new Set<string>();
for (const file of fs.readdirSync(actionsDir)) {
if (!file.endsWith('.ts')) continue;
const source = fs.readFileSync(new URL(file, `file://${actionsDir}/`), 'utf8');
for (const match of source.matchAll(/registerAction\('([^']+)'/g)) {
registered.add(match[1]!);
}
}
expect([...SNOWLUMA_ACTIONS].sort()).toEqual([...registered].sort());
});
});
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.9.4",
"version": "1.9.10",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/websocket",
"version": "1.9.4",
"version": "1.9.10",
"private": true,
"type": "module",
"main": "./src/index.ts",
+39
View File
@@ -10,6 +10,45 @@
<meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet" />
<meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet" />
<title>SnowLuma 控制台</title>
<!-- Pre-paint theme bootstrap: applies the cached appearance to <html>
before the bundle mounts, so dark/OLED/density/scale don't flash from
the default light theme. Mirrors a subset of ThemeContext.applyAppearance;
defensive (never breaks page load). The bundle re-applies authoritatively. -->
<script>
(function () {
try {
var raw = localStorage.getItem('snowluma_ui_appearance');
if (!raw) return;
var a = JSON.parse(raw);
if (!a || typeof a !== 'object') return;
var root = document.documentElement;
var mode = a.mode;
var pal = a.palette;
// A non-default palette fixes light/dark; these flavors are light, the rest dark.
var LIGHT_PAL = { 'catppuccin-latte': 1, 'rose-pine-dawn': 1, 'everforest-light': 1 };
var isPal = typeof pal === 'string' && pal.length > 0 && pal !== 'default';
var resolved = isPal
? (LIGHT_PAL[pal] ? 'light' : 'dark')
: (mode === 'light' || mode === 'dark'
? mode
: (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'));
root.classList.remove('light', 'dark');
root.classList.add(resolved);
root.setAttribute('data-theme', resolved);
root.style.colorScheme = resolved;
if (isPal) root.setAttribute('data-palette', pal);
if (a.density === 'compact' || a.density === 'cozy') root.setAttribute('data-density', a.density);
// A palette forces soft so the OLED "black" rule can't fight it.
var intensity = isPal ? 'soft' : a.darkIntensity;
if (intensity === 'black' || intensity === 'soft') root.setAttribute('data-dark-intensity', intensity);
if (a.sidebarStyle === 'follow' || a.sidebarStyle === 'panel' || a.sidebarStyle === 'accent') root.setAttribute('data-sidebar-style', a.sidebarStyle);
root.setAttribute('data-contrast', a.highContrast ? 'high' : 'normal');
root.setAttribute('data-reduce-motion', a.reduceMotion ? '1' : '0');
if (typeof a.radius === 'number' && a.radius >= 0 && a.radius <= 2) root.style.setProperty('--radius', a.radius + 'rem');
if (typeof a.uiScale === 'number' && a.uiScale >= 0.5 && a.uiScale <= 2) root.style.fontSize = 16 * a.uiScale + 'px';
} catch (e) { /* ignore — fall back to default theme */ }
})();
</script>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;600;700&display=swap" rel="stylesheet" />
+2 -1
View File
@@ -1,7 +1,7 @@
{
"name": "webui",
"private": true,
"version": "1.9.4",
"version": "1.9.10",
"type": "module",
"scripts": {
"dev": "vite",
@@ -21,6 +21,7 @@
"@tanstack/react-router": "^1.169.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"gridstack": "^12.6.0",
"lucide-react": "^0.469.0",
"motion": "^12.0.0",
"react": "^19.2.5",
@@ -35,7 +35,7 @@ export function AccountSidebar({
<motion.aside
animate={{ width: collapsed ? 56 : 248 }}
transition={{ type: 'spring', stiffness: 300, damping: 32 }}
className="shrink-0 rounded-lg border bg-card/40"
className="shrink-0 rounded-xl border bg-card/40"
>
<div className={cn('flex items-center', collapsed ? 'justify-center px-1.5 py-2' : 'justify-between px-3 py-2')}>
{!collapsed && <span className="text-xs font-medium text-muted-foreground">在线连接</span>}
@@ -1,7 +1,7 @@
// "通用设置" tab — fields that apply to the whole OneBotInstance rather
// than any specific adapter: the music-sign service URL and the built-in
// `#sl` status command. Edits here mark the config dirty and are persisted
// via the page's explicit top-right 保存 (a continuously-edited surface).
// `#sl` status command. Edits here mark the config dirty and are
// auto-saved with debounce by the parent ConfigPage.
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -9,6 +9,7 @@ import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { cn } from '@/lib/utils';
import { useTheme } from '@/contexts/ThemeContext';
import type { AdapterCommon } from './defaults';
import type { AdapterStatus } from '@/types';
@@ -47,14 +48,15 @@ export function NodeSummaryCard<T extends AdapterCommon>({
}: NodeSummaryCardProps<T>) {
const enabled = item.enabled !== false;
const blankName = !item.name?.trim();
const off = useTheme().appearance.disableMotion;
return (
<motion.div
initial={{ opacity: 0, y: 4 }}
initial={off ? false : { opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18 }}
transition={off ? { duration: 0 } : { duration: 0.18 }}
className={cn(
'flex flex-col gap-2 rounded-lg border bg-card/40 p-3 transition-opacity sm:flex-row sm:items-center sm:gap-3',
'flex flex-col gap-2 rounded-xl border bg-card/40 p-3.5 transition-all hover:bg-accent/20 sm:flex-row sm:items-center sm:gap-3',
!enabled && 'opacity-60',
)}
>
@@ -79,22 +81,12 @@ export function NodeSummaryCard<T extends AdapterCommon>({
)}
</div>
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground tabular-nums">{summary}</div>
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
<Badge variant="outline" className="font-normal">
{item.messageFormat === 'string' ? 'CQ 码' : '数组'}
</Badge>
<Badge variant="outline" className="font-normal">
{item.reportSelfMessage ? '上报自身' : '不上报自身'}
</Badge>
{item.accessToken ? (
<Badge variant="outline" className="font-normal">
已设 Token
</Badge>
) : (
<Badge variant="outline" className="font-normal text-muted-foreground">
无 Token
</Badge>
)}
<div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground">
<span>{item.messageFormat === 'string' ? 'CQ 码' : '数组'}</span>
<span aria-hidden className="text-border">·</span>
<span>{item.reportSelfMessage ? '上报自身' : '不上报自身'}</span>
<span aria-hidden className="text-border">·</span>
<span className={cn(!item.accessToken && 'text-muted-foreground/60')}>{item.accessToken ? '已设 Token' : '无 Token'}</span>
</div>
</div>
@@ -6,6 +6,8 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { Sidebar } from '@/components/layout/sidebar';
import { TopBar } from '@/components/layout/top-bar';
import { useMediaQuery } from '@/hooks/use-media-query';
import { useTheme } from '@/contexts/ThemeContext';
import { useLayout } from '@/contexts/LayoutContext';
import { cn } from '@/lib/utils';
interface MainLayoutProps {
@@ -16,9 +18,24 @@ interface MainLayoutProps {
export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
const isMobile = !useMediaQuery('(min-width: 768px)');
const { appearance } = useTheme();
const [collapsed, setCollapsed] = useState(() => {
return localStorage.getItem('snowluma_sidebar_collapsed') === '1';
// An explicit per-browser toggle wins; otherwise fall back to the
// operator's `sidebarDefaultCollapsed` appearance preference.
const explicit = localStorage.getItem('snowluma_sidebar_collapsed');
if (explicit === '1') return true;
if (explicit === '0') return false;
return appearance.sidebarDefaultCollapsed;
});
const customBg = appearance.background.type !== 'none';
// Framer's reducedMotion only suppresses transforms, so the always-present
// width + page-transition animations need an explicit opt-out to make the
// “减少动效” setting actually felt.
const reduce = appearance.reduceMotion || appearance.disableMotion;
const { editing } = useLayout();
// Force the sidebar open while editing layout so its drag-to-reorder list
// has room (it returns to the user's collapsed pref on 完成).
const effectiveCollapsed = collapsed && !editing;
const [mobileOpen, setMobileOpen] = useState(false);
const pathname = useRouterState({ select: (s) => s.location.pathname });
@@ -27,16 +44,16 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
}, [collapsed]);
return (
<div className="flex h-screen w-screen overflow-hidden bg-background text-foreground">
<div className={cn('flex h-screen w-screen overflow-hidden text-foreground', customBg ? 'bg-transparent' : 'bg-background')}>
{/* Desktop sidebar */}
{!isMobile && (
<motion.aside
initial={false}
animate={{ width: collapsed ? 64 : 248 }}
transition={{ type: 'spring', stiffness: 280, damping: 32 }}
animate={{ width: effectiveCollapsed ? 64 : 248 }}
transition={reduce ? { duration: 0 } : { type: 'spring', stiffness: 280, damping: 32 }}
className="relative h-full shrink-0 border-r overflow-hidden"
>
<Sidebar collapsed={collapsed} />
<Sidebar collapsed={effectiveCollapsed} />
</motion.aside>
)}
@@ -58,11 +75,12 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
<div className="flex min-w-0 flex-1 flex-col">
<TopBar
status={status}
collapsed={collapsed}
collapsed={effectiveCollapsed}
onToggleCollapse={() => setCollapsed((v) => !v)}
onOpenMobile={() => setMobileOpen(true)}
onLogout={onLogout}
isMobile={isMobile}
editing={editing}
/>
<main className={cn('flex min-h-0 flex-1 flex-col')}>
@@ -71,10 +89,10 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
<AnimatePresence mode="wait">
<motion.div
key={pathname}
initial={{ opacity: 0, y: 10 }}
initial={reduce ? false : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
transition={{ duration: 0.22, ease: [0.16, 1, 0.3, 1] }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -8 }}
transition={reduce ? { duration: 0 } : { duration: 0.22, ease: [0.16, 1, 0.3, 1] }}
>
{children}
</motion.div>
+140 -37
View File
@@ -1,10 +1,12 @@
import { LayoutDashboard, PlugZap, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
import { motion } from 'motion/react';
import { Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react';
import { motion, Reorder } from 'motion/react';
import { Link, useRouterState } from '@tanstack/react-router';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
import { useAppState } from '@/contexts/AppStateContext';
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import type { AppPath } from '@/router';
export interface NavItem {
@@ -22,6 +24,12 @@ export const NAV_ITEMS: NavItem[] = [
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
];
// Anti-self-lock: these nav items can be reordered but never hidden.
// '/' — hosts the 「编辑布局」 entry point; hiding it would strand the
// user with no way back to un-hide anything.
// '/settings'— account + appearance.
export const PINNED_NAV: AppPath[] = ['/', '/settings'];
interface SidebarProps {
collapsed?: boolean;
onItemClick?: () => void;
@@ -29,6 +37,23 @@ interface SidebarProps {
export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const { updateInfo } = useAppState();
const { navItems, setNavItems, editing, setEditing } = useLayout();
// Full reconciled nav (incl. hidden) — pinned forced visible, forward-compat.
const reconciled = reconcileLayoutItems(navItems, NAV_ITEMS.map((i) => i.to), PINNED_NAV);
// View mode: configured order, hidden removed.
const orderedNav = reconciled
.filter((i) => i.visible)
.map((i) => NAV_ITEMS.find((n) => n.to === i.id))
.filter((n): n is NavItem => !!n);
const reorderNav = (ids: string[]) => {
const byId = new Map(reconciled.map((i) => [i.id, i]));
setNavItems(ids.map((id) => byId.get(id)).filter((x): x is NonNullable<typeof x> => !!x));
};
const toggleNav = (id: string) =>
setNavItems(reconciled.map((i) => (i.id === id ? { ...i, visible: !i.visible } : i)));
return (
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
@@ -50,45 +75,123 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
{/* Nav */}
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
{NAV_ITEMS.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
<Link
key={to}
to={to}
title={collapsed ? label : undefined}
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
)}
{editing ? (
<div className="flex flex-col gap-2 p-2">
<div className="flex items-center justify-between px-1">
<span className="text-[11px] font-medium text-muted-foreground">编辑导航</span>
<button
type="button"
onClick={() => setEditing(false)}
className="inline-flex items-center gap-1 rounded-md border border-primary/40 bg-primary/10 px-2 py-0.5 text-[11px] text-primary transition-colors hover:bg-primary/15 cursor-pointer"
>
{isActive && (
<motion.span
layoutId="sidebar-active-pill"
className="absolute inset-0 rounded-lg bg-sidebar-accent ring-1 ring-primary/20"
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
/>
)}
<Icon className={cn('relative z-10 size-4 shrink-0', isActive && 'text-primary')} />
{!collapsed && (
<span className="relative z-10 flex min-w-0 flex-1 flex-col items-start">
<span className="truncate leading-tight">{label}</span>
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
</span>
)}
</Link>
);
})}
</nav>
<Check className="size-3" /> 完成
</button>
</div>
<Reorder.Group axis="y" values={reconciled.map((i) => i.id)} onReorder={reorderNav} className="flex flex-col gap-1">
{reconciled.map((item) => {
const meta = NAV_ITEMS.find((n) => n.to === item.id);
if (!meta) return null;
const Icon = meta.icon;
const pinned = (PINNED_NAV as string[]).includes(item.id);
return (
<Reorder.Item
key={item.id}
value={item.id}
className={cn(
'flex select-none items-center gap-2 rounded-lg border bg-sidebar-accent/30 px-2 py-2 cursor-grab active:cursor-grabbing',
!item.visible && 'opacity-50',
)}
>
<GripVertical className="size-3.5 shrink-0 text-muted-foreground" />
<Icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{meta.label}</span>
{pinned ? (
<span title="必选项,不可隐藏" className="inline-flex size-7 items-center justify-center text-muted-foreground/50">
<Lock className="size-3.5" />
</span>
) : (
<button
type="button"
onClick={() => toggleNav(item.id)}
title={item.visible ? '隐藏' : '显示'}
aria-label={item.visible ? '隐藏' : '显示'}
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-sidebar-accent/50 hover:text-foreground cursor-pointer"
>
{item.visible ? <Eye className="size-3.5" /> : <EyeOff className="size-3.5" />}
</button>
)}
</Reorder.Item>
);
})}
</Reorder.Group>
</div>
) : (
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
{orderedNav.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
<Link
key={to}
to={to}
title={collapsed ? label : undefined}
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
)}
>
{isActive && (
<motion.span
layoutId="sidebar-active-pill"
className="absolute inset-0 rounded-lg bg-sidebar-accent ring-1 ring-primary/20"
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
/>
)}
<Icon className={cn('relative z-10 size-4 shrink-0', isActive && 'text-primary')} />
{!collapsed && (
<span className="relative z-10 flex min-w-0 flex-1 flex-col items-start">
<span className="truncate leading-tight">{label}</span>
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
</span>
)}
</Link>
);
})}
</nav>
)}
</ScrollArea>
<Separator />
{updateInfo?.hasUpdate && (
<div className={cn('px-2 pt-2', collapsed && 'px-0')}>
<Link
to="/settings"
search={{ tab: 'about' }}
onClick={onItemClick}
title={updateInfo.latest ? `有新版本 v${updateInfo.latest} · 点击查看` : '有可用更新'}
aria-label="有可用更新"
className={cn(
'group relative flex items-center gap-2.5 rounded-lg border border-primary/30 bg-primary/[0.07] px-3 py-2 text-left transition-colors hover:bg-primary/10',
collapsed && 'mx-auto w-10 justify-center px-0',
)}
>
<Sparkles className="size-4 shrink-0 text-primary" />
{!collapsed && (
<span className="flex min-w-0 flex-1 flex-col">
<span className="text-xs font-medium leading-tight text-foreground">有新版本可用</span>
<span className="truncate text-[10px] text-muted-foreground">v{updateInfo.latest} · 点击查看</span>
</span>
)}
{collapsed && (
<span className="absolute right-1 top-1 size-2 rounded-full border-2 border-sidebar bg-primary" />
)}
</Link>
</div>
)}
<div className={cn('px-4 py-3 text-[10px] text-muted-foreground', collapsed && 'text-center px-2')}>
{collapsed ? '©' : `© ${new Date().getFullYear()} SnowLuma`}
</div>
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more