Wrap the post-write chmodSync in try/catch like auth.ts: the key is already
written with mode 0600, so a rare chmod failure shouldn't misreport a
successful write as a 500.
Adversarial Wave A1 pass (MAJOR): the TLS private key was written with the
default umask mode (typically 0644 — world-readable). Write config/key.pem
with mode 0600 + an explicit chmodSync (writeFileSync's mode is ignored for an
existing file), mirroring auth.ts's webui.json handling. cert.pem stays public.
GET/POST /api/system/settings (port/host/tlsEnabled/trustProxy) persisted via
updateRuntimeConfig — listener-level, restart-to-apply; response carries
restartRequiredToApply + the env-overridden field names so the panel can flag
edits that won't take effect. Enabling TLS is blocked unless a usable cert is
present. POST/DELETE /api/system/tls/cert validates a pasted PEM pair
(validateTlsPair) before writing config/cert.pem + key.pem. Adds read-only
readRuntimeConfig() and a tested pure coerceSettingsPatch validator. All routes
sit behind the existing /api/* auth middleware.
Move the trust-proxy/client-ip resolver from a module-level direct read of
SNOWLUMA_WEBUI_TRUST_PROXY into initWebUI, fed by runtime.json's trustProxy
(loadRuntimeConfig already merges the env override on top). Default '' parses
identically to the old undefined (trust socket peer only), so behavior is
unchanged when unset.
initWebUI now takes { host, tlsEnabled }. When TLS is enabled, load+validate
config/cert.pem + key.pem (tls.ts: validateTlsPair / resolveTlsContext, both
unit-tested) and serve via @hono/node-server's https createServer; a missing
or invalid cert falls back to HTTP with a loud warning (never bricks the WebUI).
Bind host is now configurable (default 0.0.0.0). Wired from runtime.json
(webuiHost / webuiTls.enabled) in core/index.ts.
Server-side image OCR ported from Lagrange.Core ([Service]
"OidbSvcTrpcTcp.0xe07_0") cross-checked with NapCat's Oidb.0xE07 proto
(NapCat's transformer cmd 0xEB7 is a typo; the proto name + Lagrange + the
wire name all say 0xE07_0). New ImageOcr service + proto types, misc.ocrImage
api, and the ocr_image/.ocr_image action. The cmd takes an image URL, so the
action accepts an http(s) url or a cached image file_id (resolved via
getImageInfo); base64/local input is unsupported (NapCat's path is a
Windows-only kernel OCR, not portable). Wire round-trip + response-parse
tests lock the pb tags.
Add the file-rename slot to the group-file OIDB envelope (req/resp field 5),
a RenameGroupFile service mirroring MoveGroupFile, a groupFile.rename() api
method, and the rename_group_file action (params group_id/file_id/
current_parent_directory/new_name, NapCat-aligned), replacing the stub.
Wire fields (busId=102, parentFolder=current dir, newFileName) verified
against NapCat's Oidb.0x6D6 transformer; subCommand 4 cross-checked against
the move op (sub 5 on both sides). Serialize + envelope round-trip test locks
the pb tags.
Global singleton observing every account's online/offline edge:
- Pure per-UIN debounce state machine (debounce.ts): an offline surviving
debounceSeconds fires "offline"; recovery fires the paired "online"; a
self-heal within the window fires nothing; a cold online fires nothing.
- NotificationManager (manager.ts): renders each opted-in + enabled channel's
body template and POSTs it (single attempt + timeout, JSON), recording the
outcome in a bounded in-memory history (lost on restart). Side effects
(config/channelIds/post/clock) are injected for testability.
- BridgeManager: single-callback setters → additive listeners so OneBotManager
and NotificationManager observe independently; close edge now carries the
bridge (read nickname before dispose); fire-all with per-listener try/catch.
- Wired into the composition root, bound after OneBotManager.
Tests: debounce machine (pure, all misfire sequences) + manager (selectChannels,
dispatch, history cap, fake-timer self-heal/pairing). 23 green, typecheck clean.
Adversarial review: 0 blockers / 0 should-fix (2 NITs applied).
Global channel store at config/notifications.json, mirroring ui-config's
total-normalize + atomic-write + cached-load conventions: NotificationsConfig
(version, debounceSeconds clamp [0,3600] default 30, channels[]), a total
normalizeNotificationsConfig (drops malformed/non-http channels, dedupes by
id, strips unknown fields), and the pure renderTemplate ({key} substitution;
missing keys left as-is; no re-expansion of substituted values).
Per-UIN opt-in: OneBotConfig.notifications.channelIds (validated slugs,
last-write-wins merge across global+per-uin, deduped) in the onebot package.
Tests: 19 (core notifications-config) + 12 (onebot config), all green.
Adversarial review: 0 blockers / 0 should-fix.
The read-only push-body probe in Bridge has served its purpose; the KickNT
push body and its reason fields are captured for the upcoming notification
reason-enrichment. Bridge back to baseline.
Conclude the spike on the inbound
`trpc.qq_new_tech.status_svc.StatusService.KickNT` push and remove its
throwaway instrumentation:
- Bridge: drop the outbound send probe.
- HookSession: drop the loggedIn-gate bypass; restore `if (!this.loggedIn) return;`.
- HookManager: drop the disconnect-timing log.
Keep one read-only `[KICK-BODY]` probe in Bridge that logs the KickNT push
body (hex + utf8) so the reason fields (tipsTitle / tipsDesc) can be reversed
for the upcoming notification reason-enrichment. Remove once captured.
- 导出当前视图: a toolbar button dumps the current (filtered) log view to a
client-side `.log` text file — no server endpoint, respects the active level
filter + search.
- 视图预设: 开发 / 运维 / 精简 presets bundle the existing display prefs
(visibleLevels / maxLines / autoScroll / wrap); a new `UiLogsPrefs.preset`
field stores the active id. Any hand edit to those prefs drops to 自定义.
The client owns the preset→prefs bundles; the server just stores + validates
the id (oneOf, defaults custom). No non-chronological reordering, per plan.
Schema foundation for the B2 dashboard batch, mirroring the navItems shape:
- `overviewMobile: UiLayoutItem[]` — a separate single-column (id+visible)
ordering for phones, kept fully disjoint from the desktop 2D `overviewBlocks`
grid so mobile ordering never pollutes grid coords.
- `topbarItems: UiLayoutItem[]` — show/hide list for toggleable top-bar
elements (status badge, theme toggle, kiosk button); essential elements stay
pinned in the consumer.
Server `normalizeLayout` round-trips both (idOr + dedup, total over corrupt
input); defaults seed first run. `LayoutContext` exposes them with
setOverviewMobile/setTopbarItems setters and reconcile-on-consume semantics, so
adding a widget/element later just appears. Old configs lacking the fields fall
back to defaults on load.
Consumers (mobile render, topbar render + config, drag-sort panel) land in
follow-up B2 commits.
Adds two appearance customizations from the WebUI plan's B1 batch:
- Custom fonts: new `fontSansCustom`/`fontMonoCustom` free-form family
fields (mirroring accent's preset/custom dual-field). A "自定义" segment
reveals a text input; on Chromium it gets a native <datalist> of installed
fonts via `queryLocalFonts()`, feature-detected with a silent fallback to
a plain text box on Firefox/Safari/mobile. No font-file uploads.
- Theme-variable panel: new `cssVars` map lets the operator override
individual theme tokens (background/foreground/primary/…) with colour
pickers, layered last over palette+accent. Both keys (token whitelist) and
values (hex/named/functional colour) are validated, so — unlike customCss —
this stays safe to serve to the unauthenticated login page.
Server `normalizeAppearance` gains `fontFamilyOr` (rejects control
chars/injection) and `normalizeCssVars` (whitelist keys + colour-only values,
total over corrupt input). Client `ThemeContext` re-validates defensively
(the localStorage cache is locally tamperable) before injecting into CSS.
Tests for the new normalizers land with the B4 batch.
Upgrades the blank-body heuristic to NT's exact discriminator. RE of
wrapper.linux.node (msg_header_codec_helper.cc::DecodeRoutingHead, sub_3B42650)
shows the official client classifies a C2C push by (svr_msg_type, c2c_cmd):
msgType ∈ {141,166,167} with c2c_cmd ∈ {1,73,75,129,131,133,135,192} is routed
through OnRecvSysMsg (long_cnn_msg_mgr.cc) as a system/control signal and never
shown as a chat bubble — the group-invite "[空消息]" phantom is one of these.
- proto-defs: ContentHead field 3 was mislabelled `divSeq`; it is `c2c_cmd`.
Renamed (only other use was forward.ts, which zeroes it on a fake send).
- MsgPushHead now carries c2cCmd; new isC2cControlPush() in blank-filter.ts.
- parseMsgPush + both history fetches drop control pushes by (msgType, c2cCmd)
regardless of body, so a control signal carrying stray content is caught too
(not just the empty case). isBlankMessage stays as the fallback for
content-less pushes we don't yet classify by cmd. Live path debug-logs a
control push that carried elements, in case the table ever eats real content.
NOTE: the c2c_cmd set is taken from NT; we have not captured #24's actual cmd
(our diagnostic never logged field 3), so the blank fallback remains load-bearing
until a live capture confirms which cmd the invite phantom uses.
A group invite push carries no group name (confirmed across SnowLuma / Lagrange
/ NapCat — all three invite protos only have groupUin + invitorUid), and
get_group_info only resolved joined groups (fetchGroupList → roster), so an
invited group rendered "未知群名". Add a by-id server lookup so the name
resolves even when the bot isn't a member.
- proto-defs: 0x88D_0 request (field1 + config.uin + a request-mask `flags`
block) + response (groupInfo.results: name / member counts / owner / …),
field tags transcribed from
dev/Lagrange.Core/.../OidbSvcTrpcTcp0x88D_0{,Response}.cs.
- protocol: FetchGroupDetail oidb-service. Envelope reserved=0 (NO uinForm) —
Lagrange's GetGroupInfoService builds it with isUid=false.
- core: ContactsApi.fetchGroupDetail(gid) → QQGroupInfo | null; deliberately
NOT remembered into the joined-groups roster (mustn't pollute get_group_list).
- onebot: get_group_info falls back to fetchGroupDetail for non-member groups,
behind a 5-min per-id TTL cache so a burst of invites for one group can't
hammer 0x88D_0 (rate-limit / kick risk). noCache bypasses it.
- tests: request/envelope round-trip (reserved=0, uin, command), response
decode; + non-member resolve / cache-hit / noCache-bypass at the onebot layer.
Live note: byte-identical to Lagrange's 0x88D_0, but not verified against a real
account on this host.
When an incoming reply quotes a message SnowLuma's store doesn't have (e.g. one
from before it was running, or never observed), the receive pipeline now fetches
just that message from the server and persists it before dispatch — so a
consumer's get_msg on the quote resolves instead of returning "message not
found". Works for both group and private (c2c).
- core: MessageApi.getGroupMessageBySeq / getC2cMessageBySeq — fetch a single
message over a 1-wide [seq,seq] range, through the shared history throttle
gate (same rate-limit as the bulk history APIs — no flood / kick risk).
- onebot: backfillReplyTarget — on a group/friend reply whose target isn't in
the store, fetch (group SsoGetGroupMsg / c2c SsoGetC2cMsg, uid resolved for
c2c) and persist under the EXACT id the reply resolves to, so get_msg hits
regardless of who sent the quoted message (a bot self-sent c2c message
converts with user_id=self but is keyed under the peer session). Awaited
before dispatch so the consumer sees it; best-effort — a back-fill failure
never blocks delivery of the live message.
- tests: gating (already-stored / no-reply / nothing-on-server) + keying
(group, c2c, c2c self-sent under peer session).
Only fires on a store miss, so the common path (no reply, or quote already
stored) stays zero-cost.
Mirror the group-history fetch for private chats via SsoGetC2cMsg
(trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg, fields per Lagrange:
flat friendUid/start/end request, messages@7 response). get_friend_msg_history
now resolves the anchor sequence + the friend's UID, fetches real history from
the server, converts + persists each message, and falls back to the local
store on unknown anchor / no uid / empty / error.
- protocol: fetchC2cMessageRange (decodes via the friend decoder).
- core: the group + c2c fetch now share a generic walkBackHistory loop
(same throttle gate + caps); added MessageApi.getC2cHistory.
- onebot: getFriendHistory + a generalized persistHistoryEvent (keys private
by sender uin, exactly like the live path — so reply to old private
messages resolves too).
Tests: SsoGetC2cMsg request/response round-trip + friend-decode reuse.
get_group_msg_history was served only from the local observed-message store,
so it could never return more than what SnowLuma saw live (the "only 100
messages" symptom). It now fetches real history from the server.
- protocol: new SsoGetGroupMsg packet (trpc.msg.register_proxy.RegisterProxy
.SsoGetGroupMsg, sequence-range fetch; fields per Lagrange). Each returned
PushMsgBody is decoded by the existing group decoder via a factored-out
buildContextFromMessage.
- core: MessageApi.getGroupHistory walks backward in small sequence windows
with rate-limiting + data-volume guards — a process-wide throttle (≥300ms
between sends), 30-seq chunks, ≤12 requests, ≤200 messages per call — so a
hammering client can't make us flood the server and get kicked.
- onebot: get_group_msg_history resolves the anchor sequence (requested
message_id or latest observed), fetches from the server, converts + returns,
and persists each fetched message. Falls back to the local store on
unknown anchor / empty / error.
Persisting fetched history also fixes replying to pre-injection messages:
the reply path resolves message_id→sequence via the store, which now contains
the fetched messages.
Tests: SsoGetGroupMsg request/response round-trip + decode reuse (protocol);
walk-back chunking/dedup/cap/floor (core).
- 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).
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.
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).
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).
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.
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.
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).
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).
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.
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.
* 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
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
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.
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.
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.
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.
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.