Commit Graph
1068 Commits
Author SHA1 Message Date
DrSmoothl 659970077a refactor(onebot): move rkey fallback from per-UIN to a global config store
The rkey fallback endpoint is deployment infra (one self-hosted server serves
all accounts; fallback rkeys are fungible), so it doesn't belong in per-UIN
onebot_<uin>.json. Introduce config/snowluma.json — a generic home for small
all-accounts SnowLuma settings — and move rkey.fallbackServers there.

- New onebot/global-config.ts: load/save/normalize with section-merge + atomic
  write; http(s)+host URL validation; default [] (off). Lives in onebot (not
  core) because the onebot manager constructs instances and must not depend on
  core.
- OneBotInstance takes globalSettings; manager loads it on session start and
  exposes reloadGlobalSettings() to hot-push edits to every live instance via
  applyGlobalSettings → RKeyCache.setFallbackServers.
- Remove rkey from per-UIN OneBotConfig + the WebUI per-UIN round-trip (never
  released, so no migration). Register snowluma.json in the backup allowlist.

Reworks the per-UIN rkey from 12b0190. Phase 1 of the global-settings split.
2026-06-28 20:52:07 +08:00
DrSmoothl 5d39cf5782 fix(core): finalize c2c file upload so the recipient can download (#157)
Private (c2c) file sends uploaded the bytes (apply 0xE37_1700 + Highway)
and PbSendMsg returned ok, but the receiver saw "文件传输失败": the message
carried only FileExtra.file (metadata) and not the server-issued download
routing. Group files use a different element, hence c2c-only.

Port NapCat's upload→finalize→send sequence:
- add 0xE37_800 (FinalizeOfflineFile) OIDB service, run after the Highway
  PUT to fetch the download metadata (field30)
- extend FileExtra with field6 (PrivateFileExtra.field2) and populate it
  from that metadata in sendC2cFile; covers both the url-upload and the
  file_id-resend send paths (both funnel through sendC2cFile)

Tests: byte-oracle locks the 0xE37_800 request + FileExtra.field6 tags;
core routing test now asserts finalize runs and field6 is populated.
Needs real-machine verification (send a private file, confirm download).
2026-06-28 20:11:17 +08:00
DrSmoothl 12b01907bc feat(onebot): opt-in remote rkey fallback server (#156)
On accounts where the native OIDB 0x9067_202 rkey fetch persistently returns
nothing, every image was served as a bare multimedia.nt.qq.com.cn URL the CDN
rejects with invalid rkey — SnowLuma had no fallback, unlike NapCat.

Add config.rkey.fallbackServers (default []: OFF; no third-party server is
contacted unless the operator configures one). When the native fetch leaves the
cache without a usable image rkey, each configured HTTP endpoint is tried in
turn for { group_rkey, private_rkey, expired_time } (NapCat rkey-server format;
an OneBot { retcode, data } wrapper is also accepted), populating the group/
private image rkey types. Values keep any leading &rkey=/?rkey= since
resolveImageUrl strips before re-appending.

WebUI has no form yet but round-trips rkey.fallbackServers verbatim so a hand-
edited value survives an unrelated config save. Part B of #156 (cooldown is A).
2026-06-28 01:37:58 +08:00
DrSmoothl 219d60410a fix(onebot): prefer real url over unresolvable file id in media segments
When a bot framework echoes a received image/voice/video, it resends the
original `file=<md5>.ext` (a QQ-internal media id) together with the
download `url`. The parser collapsed sources as `file ?? url ?? ...`, so
`file` won and the send path statSync'd the id as a local path → ENOENT
(retcode 1200). Reported in #155 for images via Yunzai复读.

Add pickMediaSource(): keep `file` when it is directly loadable (inline
base64/data bytes, a remote url, or a path with a separator); otherwise
fall back to a sibling http(s) `url`. Applied to image/record/video.

Tests cover the #155 echo case plus the path/base64-wins guards.
2026-06-28 01:33:07 +08:00
DrSmoothl 182df4b0e2 fix(onebot): retry rkey fetch eagerly while cache holds none (#156)
When the OIDB 0x9067_202 rkey fetch returns empty or fails, the cache stays
empty and resolveImageUrl hands out a bare multimedia.nt.qq.com.cn URL the CDN
rejects with {retcode:-5503010, invalid rkey}. The 30s refresh cooldown then
blacked out every image for 30s+ after each empty/failed fetch.

Use a short RKEY_EMPTY_COOLDOWN (10s) whenever no usable image rkey is cached,
keeping the 30s steady-state backoff only once we actually hold one — so a
transient empty fetch self-heals in seconds instead of 30s. (Part A of #156;
remote-server fallback follows.)
2026-06-28 01:25:19 +08:00
DrSmoothl 5eaac0870c feat(webui): scale notification-channel opt-in to large lists
The per-account 上下线通知渠道 picker rendered every global channel as a
flat toggle row, so 40+ channels produced an unbounded, messy wall inside
通用设置. Rework it into a collapsible control:

- collapsed: one-line summary — selected count badge + selected channels
  as removable chips (cap 8, then "+N 更多")
- expanded: description + name/url search filter + 全选/清空 bulk actions
  + a height-bounded ScrollArea list (max-h-64) so it never blows up
- globally-disabled channels stay locked off; data flow unchanged

Reuses Badge / ScrollArea / ToggleSwitch / Input.
2026-06-28 01:23:12 +08:00
DrSmoothl 04591517fa feat(webui): redesign adapter edit dialog (Apple-HIG) + custom dropdown
Rework the OneBot adapter create/edit modal into an iOS grouped-list
layout matching the debug-page language: captioned soft-card sections,
a per-kind icon chip, settings rows, and staggered motion entrance.

- reportSelfMessage: segmented control -> shared ToggleSwitch
- messageFormat (+ WS role): segmented/native select -> new custom
  DropdownSelect (accessible listbox, keyboard nav, spring popover)
- enable toggle promoted to a prominent top card
- new components/ui/dropdown-select.tsx (zero new deps, hand-rolled)

Presentation-only; draft/validation/data flow unchanged.
2026-06-28 01:14:37 +08:00
DrSmoothl e1f5267764 fix(onebot): make group large-video file fallback actually fire
#153 added a video→file fallback but the group side was dead code: it
lived in element-builder behind `isGroup && element.fileId`, and a video
sent by url/path has no fileId, so oversize group videos just rethrew the
raw Highway error (real bot: `error_code=323` on a 1.4 GB group send).

Move the fallback to the OneBot layer for groups, mirroring the private
path: on a failed Highway send, re-route oversize videos through
groupFile.upload. Verified on a live bot — a 1.4 GB group video now lands
as `[文件:video.mp4]` instead of failing.

Extract the shared heuristic (isHighwaySizeError / videoNeedsFileFallback
/ splitVideoFileFallback) so private and group stay in sync, and drop the
now-unreachable element-builder video catch. Adds send-video-fallback
tests covering both the known-oversize and remote-error-heuristic paths.
2026-06-27 16:27:33 +08:00
stla 85182795b5 feat(protocol,onebot): raise video size limit with Highway-first fallback (#153)
Round 3: fix hardcoded 4096 MB in error messages
- Use MAX_VIDEO_SIZE_HARD constant instead of hardcoded 4096 MB
- Both throw sites now derive limit from the same constant
2026-06-27 16:10:25 +08:00
DrSmoothl 70fd40e34c chore(mcp): regenerate catalog after returnsSchema backfill 2026-06-26 23:08:38 +08:00
DrSmoothl 0e8a194d4f feat(onebot): backfill returnsSchema on remaining read-only actions (c2: source-proven only) 2026-06-26 23:05:52 +08:00
DrSmoothl d2490787ae feat(onebot): backfill returnsSchema on info/group-info read-only actions 2026-06-26 22:44:10 +08:00
DrSmoothl 5e0d2db8b2 feat(mcp): emit catalog.json twin + carry returnsSchema in catalog 2026-06-26 22:03:42 +08:00
DrSmoothl 18014fb3c5 feat(onebot): backfill returnsSchema on representative read-only actions 2026-06-26 22:03:42 +08:00
DrSmoothl 355cce1e52 feat(onebot): add optional returnsSchema to action doc metadata 2026-06-26 22:03:42 +08:00
游手好闲的言柒 04a9016a7d fix(onebot): strip at segments from private messages (#151)
* 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): strip at segments from private messages
2026-06-26 21:08:01 +08:00
DrSmoothl cf7de9f7bd chore: update vite version to ^8.0.16 in pnpm-workspace.yaml 2026-06-26 19:59:58 +08:00
DrSmoothl 351db573d8 chore(release): v1.10.3 2026-06-26 19:49:41 +08:00
DrSmoothl 3b023b3275 fix(protocol): collapse ark/card messages structurally, not by string match (#146)
Follow-up to the previous #146 fix, which dropped QQ's compat fallback text by
content-matching the "版本不支持 … 升级" family. RE of the QQ kernel
(wrapper.linux.node) showed that is not how QQ does it:
- the receiver binary contains NONE of these fallback strings, so QQ cannot be
  matching by content;
- the on-target wire is [lightApp, text(compat), generalFlags, extraInfo] and the
  text element has no distinguishing marker (no pbReserve / attr6Buf);
- QQ NT's kernel codec (msg_codec_mgr) collapses the message to a single ark
  element — the sibling text is never emitted. NapCat maps kernel elements 1:1
  with no ark-aware skip yet still surfaces only the card, confirming the kernel
  drops it upstream.

Switch to that structural rule: when a lightApp/richMsg card is present, drop
sibling plain text outright. It is version/locale-proof (won't break when Tencent
rewords the string) and matches QQ NT + NapCat output exactly. @ mentions /
replies / faces are not plain text and survive; QQ clients can't attach a caption
to a card anyway, so no QQ-origin message loses real text.

Verified live on a logged-in build: get_msg returns a single json segment.
2026-06-26 18:31:43 +08:00
DrSmoothl 319c7d607d fix(protocol): drop QQ ark-compat fallback text beside mini-app cards (#146)
A QQ mini-program / ark share (B站 video, QQ 小程序, …) arrives on the wire
as a lightApp/richMsg ark element followed by a plain text element carrying
QQ's graceful-degradation compat string "当前QQ版本不支持此应用,请升级". That
text is meant only for protocol-old clients that can't render the card; QQ NT
and the kernel-backed bridges (NapCat) surface just the card.

On-target capture (test group) confirmed the text element has no distinguishing
wire marker (no pbReserve / attr6Buf) — it is a bare text sibling of the ark.
SnowLuma was decoding both, so every mini-app card came through as the card
plus a spurious "当前QQ版本不支持" text segment.

Drop the compat string when it sits beside a card, matched narrowly (the
"版本不支持 … 升级/更新" family, <=40 chars) so genuine user captions sent
alongside a card are preserved.

Verified live on a logged-in build: get_msg now returns a single json segment.
2026-06-26 18:08:26 +08:00
DrSmoothl 9de12db447 fix(onebot): align file-url actions with NapCat param tolerance (#147)
get_private_file_url required file_hash (and user_id), but NapCat needs
only file_id — it re-derives the hash from its composite file_id. Make
user_id and file_hash optional; the empty hash is accepted on the wire
(SnowLuma's private file_id already carries the md5 prefix). Verified
live: only-file_id returns a working URL (148237B download matches).

get_group_file_url rejected a present non-numeric busid with
`expected an integer` after the f.int().default(102) refactor, while
NapCat/LLBot omit busid entirely and ignore any value. Restore the
legacy `asNumber(busid) || 102` tolerance via f.raw()+busidOr102.
Verified live: null/"102"/omitted/"abc" all return a working URL.
2026-06-26 17:34:16 +08:00
DrSmoothl ecea72df40 test(onebot): expect forced full video upload retry on stale fast-path
The NTV2 fast-upload video test still asserted a single sendRawPacket
call, but #145 (forceFullOnFastPath) re-issues the OIDB request with
fast-upload disabled when a flagged main file carrying real bytes is
fast-pathed by the server. The stale assertion was never caught because
the dev push workflow doesn't run the suite — only the PR gate (ci.yml)
does, so it first surfaced on #149.

Assert two packets go out and that the second round drops
tryFastUploadCompleted, locking #145's behavior at the onebot layer.
2026-06-26 17:09:18 +08:00
Airline233 39338c3f1d fix(protocol,onebot): generate and send ark of contact cards correctly (#149) 2026-06-26 17:04:40 +08:00
Airline233 02de2acea4 fix(core): support file sources in forwarded messages (#144)
Pre-upload file/url/base64 segments for forwarded message nodes into the
target scope, re-upload cached file_ids when crossing private/group scope,
and suppress standalone file-message publishing during forward preparation.
2026-06-25 20:55:39 +08:00
DrSmoothl 3eba2a677c fix(highway): force full video upload when server fast-paths a stale resource (#145)
Group/c2c video resources expire server-side. When the bot re-sends a
video whose md5 the server already cached, the NTV2 OIDB returns no uKey
for the main file (fast-upload hit) and SnowLuma trusted it — the send
"succeeds" but the receiver sees 资源已过期, because the reused object had
expired. Confirmed by the reporter: same MP4 fast-paths and breaks, but
mutating one byte (new md5) forces a full upload and plays fine.

Add a per-sub `forceFullOnFastPath` flag on MediaSubFileUpload. When a
flagged sub-file (video main) carries real bytes but the server fast-paths
it, runNtv2Upload re-issues the OIDB request with tryFastUploadCompleted
disabled (proton drops a `false` bool, which the server reads as "no
fast-upload"), forcing a fresh resource + full PUT. The thumb stays
fast-path-OK so a cached thumb never re-pushes the main video; forwarding
paths carry no bytes so they never trigger the retry.

Also fixes the observability gap the reporter hit: the main file being
silently skipped on a fast-path now logs explicitly, and so does the
forced-retry, instead of only the thumb PUT showing up.

Note: the retry relies on the server treating an absent
tryFastUploadCompleted as "no fast-upload" — needs real-device
confirmation that the forced round actually returns a uKey.
2026-06-25 20:52:11 +08:00
stlaandSnowLuma Dev 78b0e1a124 feat(webui): auto-compress per-core density grid to fixed container (#140) (#141)
Replace fixed grid-cols-8 per-core bar display with dynamically
computed square grid that fills a fixed-height (80px) container.

- Adds bestGrid() utility that finds optimal (cols,rows) partition
  by minimizing empty cells and aspect balance
- Grid uses grid-template-rows: repeat(N, 1fr) for equal row height
- Empty cells filled with hidden divs for stable layout
- Preserves existing color tokens (bg-muted, bg-primary/70, rounded-sm)
- No scrollbar regardless of core count (tested up to 256)

Closes #140

Co-authored-by: SnowLuma Dev <dev@snowluma.local>
2026-06-25 20:46:16 +08:00
DrSmoothl feaa94bec7 build(core,runtime): native websocket-darwin-arm64.node + drop build hatch
WebSocket native is now built for darwin-arm64 — source is at
github.com/SnowLuma/snowluma-websocket (cmake-js + node-addon-api,
clones to dev/snowluma-websocket and builds with `npm install`).

  npm install in dev/snowluma-websocket → build/Release/snowluma_ws.node
  cp → packages/runtime/native/websocket-darwin-arm64.node (102 KB)

Reverts the SNOWLUMA_BUILD_SKIP_NATIVES escape hatch in vite.config.ts
that 67f8bf3 added — no longer needed; the darwin native binary is
present. Keeps `packages/core/config/.gitignore` (independently useful
runtime-state hygiene). vite build now runs clean on darwin with no
env overrides; the runtime SNOWLUMA_DEV_NO_NATIVE=1 stub also becomes
optional (only needed if the operator wants to bypass WebSocket I/O
specifically).

Existing native binaries unchanged. CI invariant restored: every
release build must include every platform's native set.
2026-06-25 16:25:56 +08:00
DrSmoothl 67f8bf3941 build(core): SNOWLUMA_BUILD_SKIP_NATIVES=1 escape hatch for darwin dev
Two architectural cleanups that complement the bridge darwin support in
7343ae6, both opt-in / default-safe:

1) `vite.config.ts` — gate the missing-native build error behind
   `SNOWLUMA_BUILD_SKIP_NATIVES=1`. Default behaviour (no env) still
   throws as before, so the CI invariant "release builds must carry the
   full native set" is untouched. Darwin developers without prebuilt
   `websocket-darwin-arm64.node` (source lives in a separate private
   build repo) can now run `SNOWLUMA_BUILD_SKIP_NATIVES=1 pnpm build`
   and pair it with the runtime `SNOWLUMA_DEV_NO_NATIVE=1` stub at
   `node dist/index.mjs` boot. The qq-hook path (separate addon) is
   independent and unaffected.

2) `packages/core/config/.gitignore` — `runtime.json` is the only
   tracked deploy-time override file in that dir; every other config
   file is per-instance runtime state written by the daemon/dev server
   (admin password hash, EULA consent, per-uin OneBot binding, WebUI
   layout). Previously they showed up as 5 untracked files after every
   `pnpm dev:mode`, polluting `git status` and risking accidental
   commit of local creds via `git add -A`. Pattern: ignore everything
   except `runtime.json` (and the .gitignore itself).

No code paths changed; both are operator-experience fixes for running
SnowLuma on darwin against the nnphook DYLD_INSERT hook.
2026-06-25 14:27:59 +08:00
DrSmoothl 7343ae6372 feat(bridge): darwin support — DYLD_INSERT-style hook discovery
Adds the missing macOS branch so HookManager + PipeWatcher discover QQ
processes when the dylib is injected via DYLD_INSERT_LIBRARIES (the
in-process injection model used by apps/qq/macos/qq_hook_dylib.cpp in
the nnphook private repo, vs Linux's out-of-process ptrace + N-API
addon model and Windows's manual-PE-loader injection).

Two small changes:

1. `linuxRuntimeDir()` (qq-hook-client.ts) — name kept for callsite
   stability; the function now applies to every non-win32 platform.
   New darwin branch prefers `$TMPDIR/snowluma-hook/` to match the
   dylib's `runtime_dir()` (apps/qq/macos/qq_hook_dylib.cpp). The
   Linux `/tmp/snowluma-<uid>` fallback stays as the last resort.
   $TMPDIR is per-user under /var/folders/ on stock macOS, which is
   the right place — /tmp/snowluma-<uid> doesn't exist by default.

2. `listSnowlumaPipePidsSync()` (qq-hook-client.ts) + darwin branch
   in `listHookProcesses()` (injector.ts) — on macOS there is no
   native enumerate-QQ-processes addon (DYLD_INSERT obviates the
   need; the dylib is already mapped in QQ when SnowLuma launches).
   The watcher's `listProcesses` dep is sync, so we provide a sync
   directory scan that returns the pids encoded in mojo.<pid>.control.sock
   filenames. The subsequent async `listLivePipes()` still gates the
   pipe-up emit via a real connect probe — a dangling socket file
   from a force-killed previous run can't drive a false connect.

Without these two changes, `pipe-watcher.tickOnce()` filtered out our
QQ pid at line 170 (`if (!newKnownPids.has(pid)) continue;`) because
`listProcessesNative()` returned []. The pipe stayed live (verified
by our nnphook recv hook firing), but the bridge never emitted
'pipe-up', HookManager never auto-loaded the session, and the WebUI
showed an empty process list.

Verified end-to-end against the resigned QQ 6.9.96-49738 + nnphook
gpt54 branch dylib on macOS 26.5.1 (Tahoe) arm64:

  * Direct HookManager harness picks up PID=16032 in <2.5s,
    fast-paths to 'reconnect' (the live-pipe-skip-injection branch
    in hook-session.ts:200), pipe connected, status=loaded
  * `pnpm dev` (SNOWLUMA_DEV_NO_NATIVE=1 for the websocket stub):
    /api/processes returns the live QQ entry with method=reconnect,
    connected=true, awaiting login

The websocket darwin-arm64.node native addon is still missing — set
SNOWLUMA_DEV_NO_NATIVE=1 to dev-mode boot with the existing stub
fallback. That's a separate runtime artifact and not in scope here.

`shouldAutoLoadPid()` returns true on non-linux without further checks
(no Electron-child-process scanning needed on darwin), and the
`hook-session.ts` "pipe already live → reconnect" fast path means
the bridge never tries to invoke the non-existent darwin native
injector. Auto-load on a freshly discovered macOS QQ is therefore
safe with or without `SNOWLUMA_HOOK_AUTOLOAD=1`.

Tests: bridge typecheck + 62 unit tests still pass.
2026-06-25 02:53:44 +08:00
stla 41bad7f24c feat: make #sl status command trigger configurable (exact match, max 32 char) (#138)
* feat: make #sl status command trigger configurable (exact match, max 32 char)

The trigger word for the built-in #sl status command is now configurable
via statusCommand.trigger, with exact case-insensitive matching preserved.

* chore: reject control chars in trigger + add sync assertion
2026-06-25 01:02:17 +08:00
DrSmoothl fbc5a3c981 refactor(core): use @snowluma/common/coerce in config normalizers
Phase 2. notifications/config and webui/ui-config dropped their verbatim-
duplicated isObject/boolOr/clampInt (+ ui-config clampNum) in favor of the
shared @snowluma/common/coerce. Pure delete-and-import: the shared
primitives are byte-identical to the originals (adversarially verified),
so behavior is unchanged.

Kept local: strOr (notifications-only), oneOf/isFiniteNum/hexOr
(ui-specific). notifications-config suite green (21), core+common
typecheck clean.
2026-06-25 00:05:46 +08:00
DrSmoothl 1ce7385d1e feat(common): add zero-dep scalar coercion primitives (coerce)
Phase 1 of de-duplicating config normalization. isObject/boolOr/clampNum/
clampInt were copied verbatim across notifications/config and webui/
ui-config; give them a single home as @snowluma/common/coerce (new
per-file subpath export, zero deps — fits common's leaf-utility charter).

Byte-identical to both originals (adversarially verified), so the phase-2
migration is a pure delete-and-import. clampInt is clamp-then-trunc;
10 table tests pin types, numeric-string coercion, non-finite→fallback,
bounds, and the clamp/trunc order. Not yet wired into consumers.
2026-06-25 00:01:39 +08:00
DrSmoothl 3a4af38842 refactor(onebot): lift bootstrap-meta framing into the network adapter base
Phase 1. The connect/enable/heartbeat bootstrap triplet was built +
shaped + stringified + null-dropped identically in WsServerAdapter and
WsClientAdapter. Lift that into IOneBotNetworkAdapter:

- metaFrame(event, options): string|null  — shape via shapeEventForAdapter
  then JSON.stringify, or null when the shaper drops it
- bootstrapMetaFrames(options): string[]  — the 3 bootstrap events,
  framed and null-filtered

Both ws adapters' sendBootstrapMetaEvents become one-liners over
bootstrapMetaFrames (ws-client keeps its role guard at the call site);
ws-server's close() disable broadcast reuses metaFrame. Base now owns
the shape+serialize policy, adapters own only the transport — same
shape as ADR-0009's reload template method.

Behavior-preserving (adversarially verified byte-for-byte); the two ws
adapters drop their now-unused shapeEventForAdapter import. Safety net
(network-bootstrap-meta, 9 tests) green.
2026-06-24 23:40:31 +08:00
DrSmoothl e11601bfec test(onebot): characterize network bootstrap-meta behavior (safety net)
Phase 0 of the bootstrap-meta deepening. No production code; pins the
observable behavior the phase-1 base-class lift must preserve:

- shapeEventForAdapter shaping policy (meta passthrough, message_sent
  drop under !reportSelfMessage, string-format raw collapse)
- ws-client emits [connect,enable,heartbeat] on open, role-guarded,
  and skips a frame that shapes to null (options genuinely threaded)
- ws-server sends the triplet to an Event connection and broadcasts a
  single disable on close(), skipping Api connections on both paths

Adversarially hardened: two gaps (null-drop/options-threading, close
Api-skip) were found via surviving mutations and closed. 9/9 green.
2026-06-24 23:35:07 +08:00
DrSmoothl a305afbc76 fix(webui): observable projector wedge + tighten non-array fallback
Round-2 follow-up. Two small holes flagged by the adversarial review of
the connection-diff-loop projector:

- A projector that starts throwing only after a shape regression would
  wedge the diff baseline silently — no publishes, no log, the only
  symptom is the dashboard's connections card freezing until restart.
  Latch a one-shot console.error on the first throw so the failure is
  visible without re-running the loop locally.

- The non-array fallback at the projector site in server.ts returned
  `acc.adapters` verbatim, which would re-introduce volatile fields if
  the snapshot shape ever drifts. Tighten to `[]`.

Also documented the deliberate trade-off: per-second adapter `detail`
rotation (client count, last-delivery HH:MM:SS) refreshes on the next
SSE push or the 30s REST reconcile rather than in real time. The user's
original bugs were about process/account edges (which DO push
instantly); detail-string freshness was not in scope. If it becomes one,
surface client-count as a structured AdapterStatus field instead of
parsing the localised `detail`.

437/437 core green.
2026-06-24 23:17:26 +08:00
DrSmoothl 84cdd99868 fix(webui): dropped-frame reconcile + split systemInfo cadence + diff-loop unref
Three findings from the adversarial review, all in the WebUI integration:

D: SSE {kind:'dropped'} now triggers a one-shot REST refresh of
   qq-list/processes/connections instead of being silently ignored.
   Reasoning: when createFramePusher drops frames under backpressure, the
   NEXT delivered frame is per-resource (only the resource whose debounce
   timer next fires) — NOT a refresh of all 3. If the dropped frame was
   the only update for a slow-changing resource (e.g. connections stable
   afterwards), the WebUI stays stale until the 30s reconcile. The
   refresh is fire-and-forget; each refresh helper already swallows errors.

E: systemInfo gets its own fast useEffect on the user's pollInterval
   (default 3s). The earlier commit slowed it to 30s claiming the data was
   'daily cadence', but SystemInfo carries live values (uptime,
   cpu.loadAvg, memory.usagePercent, runtime.heapUsed) that the overview
   widget animates — 30s is a visible regression. The other 3 resources
   stay on the 30s SSE-reconcile fallback.

F: connection-diff-loop's setInterval is now .unref()'d (mirrors the
   tokenJanitor pattern at server.ts:462). The discarded handle is now
   commented as intentional — initWebUI has no shutdown path, so the
   handle has no consumer; unref is the right cleanup primitive.

WebUI typecheck clean. 437/437 core suite (no behavior change in core
tests — only the diff-loop file's timer.unref?.() call is new and is
optional-chained so vitest's fake timers don't crash).
2026-06-24 23:05:25 +08:00
DrSmoothl bae9f8edb0 fix(webui): connection-diff-loop compares ONLY level — strip detail timestamps
Adversarial review caught: HttpPostAdapter.describeStatus() embeds
HH:MM:SS in 'detail' (e.g. "上次推送 14:53:01"). Every webhook delivery
rotates that string every second under any active push — and the diff
loop's raw JSON.stringify compared everything, so it published on every
500ms tick under any non-idle webhook. Net effect: SSE pushed a full
connections frame at 2 Hz, exactly the polling the loop was meant to
replace, just on the push channel.

Add an optional pickComparable projector. server.ts caller passes one
that returns { uin, nickname, adapters[{ name, kind, status }] } — the
LEVEL only, not the live-rendered detail string. The SSE handler still
ships the FULL snapshot (including detail) to the WebUI; only the diff
key is pruned.

2 new tests pin the invariant: 10 detail-only ticks → ZERO publishes; a
real status-level transition publishes exactly once. Plus a throwing-
projector isolation test. 7/7 diff-loop tests green.
2026-06-24 22:55:51 +08:00
DrSmoothl f9ce49ac7e fix(webui): single-flight per resource in bindStateStream — ordering safety
Adversarial review caught: uneven snapshot latency can deliver a STALE
final frame. Concrete repro added as a test:
  - publish('processes') @ T=0 → flush A starts a slow snapshot (200ms)
  - publish('processes') @ T=60 → flush B fires at T=110 with a fast (10ms)
    snapshot → send B at T=120
  - flush A's slow snapshot resolves at T=250 → send A with snapshot data
    captured BEFORE B → client's LAST frame is stale.

Fix: at most one in-flight flush per resource. While a flush is pending,
new publishes set a  flag instead of starting an overlapping
flush; on completion the flag re-arms the debounce timer for exactly one
follow-up flush. Sustained publish streams therefore produce at most one
frame per (debounceMs + flushLatency).

Test 'serialises overlapping flushes' fails on the pre-fix code (last
frame = 'snap-T0' stale), passes on the fix (last frame = 'snap-T60'
fresh). Test 'coalesces N publishes during in-flight' verifies the
pending flag is set-like (5 publishes → 1 follow-up, not 5).

9/9 state-stream tests green; 432/432 core suite.
2026-06-24 22:44:09 +08:00
DrSmoothl bb752b13a1 fix(webui): add /api/state/stream to SSE token-query allowlist
Adversarial review caught: EventSource cannot set custom headers, so every
SSE endpoint MUST appear in the TOKEN_QUERY_ALLOWLIST or the auth
middleware at server.ts:404 computes queryToken='' and 401s every connect.

Without this fix the entire phase-3 SSE endpoint is dead on arrival:
clients silently fall back to the 30s REST reconcile and the original
"WebUI must refresh to see new state" bug is unfixed.

Export the allowlist as SSE_TOKEN_QUERY_PATHS so a regression test can
lock the invariant — a missing entry has no error log, the only symptom
is the silent stream failure.
2026-06-24 22:36:40 +08:00
DrSmoothl a9f5f277f1 feat(core): connection-status diff loop — publish 'connections' on change
Phase 4b. OneBot adapters expose no event-emitter for connection-state edges
(listening / connected / client-count / last-delivery), so the SSE handler
can't subscribe — without this loop a connection change would only reach the
WebUI on the 30s REST reconcile fallback.

startConnectionDiffLoop polls getConnectionStatuses() at 500ms, compares
JSON-serialised snapshots, and publishes 'connections' through the StateBus
when (and only when) it actually moves. The first SUCCESSFUL observation is
treated as a baseline (no publish): the SSE handler's sendAllInitial has
already shipped the initial snapshot to every connected client on connect.
Snapshot exceptions are isolated — the loop retries on the next tick without
clobbering the baseline.

Started once per initWebUI lifetime; lives until process exit (consistent
with the other heartbeat-style intervals like the SSE 15s keepalives).

431/431 core suite green (5 new tests cover stable=silent, change=publish,
first-observation=baseline, dispose stops, snapshot-throw isolation).
2026-06-24 22:09:13 +08:00
DrSmoothl de3bb4817d feat(webui): subscribe to /api/state/stream — push-driven dashboard state
Phase 4 of the SSE migration. The dashboard's three live resources now
update the moment the backend sees a change instead of within 0-3000ms of
the next polling tick.

- New api.stateStream({ onEvent, onStatus }) in lib/api/client.ts mirrors
  the existing openLogStream / openDebugStream EventSource pattern: token in
  the query string (EventSource can't set headers), single onerror →
  'reconnecting' status, source.close() on dispose, JSON.parse with skip-
  malformed isolation. Browser-native EventSource auto-reconnect covers
  transport drops with no manual retry timer.

- StateStreamEvent union covers the three resource frames plus the two
  control frames ('ready' on connect, 'dropped' on backpressure). The
  resource frames carry typed HookProcessInfo[] / QQInfo[] /
  AccountConnections[] payloads.

- AppLayout now subscribes on mount, applies pushed snapshots to the same
  setProcessList / setQqList / setConnections React state slots the polling
  tick used to drive. The REST polling tick is RETAINED but slowed to
  max(pollInterval × 10, 10s) (default 3s → 30s) so it acts as a silent-
  drop reconcile rather than the primary update path. systemInfo isn't on
  the SSE feed — it stays on the slow REST loop.

Resolves the two reported bugs:
  1. new QQ.exe not showing in WebUI until manual refresh → process-
     discovered now publishes 'processes' through the StateBus → frame
     arrives within 50ms.
  2. injection panel stuck at "waiting for connection" after a successful
     hook (group messages arriving) → HookSession 'status-changed' now
     publishes 'processes' → 'online' status frame arrives within 50ms.

WebUI typecheck clean. No unit tests in packages/webui (consistent with the
existing openLogStream/openDebugStream which also have no client tests).
2026-06-24 21:51:35 +08:00
DrSmoothl a7522deb82 feat(webui): /api/state/stream SSE — push processes/qq-list/connections
Phase 3 of switching the three dashboard resources from REST polling to
SSE push.

- New pure helper packages/core/src/webui/state-stream.ts owns the
  debounce/snapshot/fan-out logic, decoupled from Hono so it's unit-testable
  with fake timers (7 tests cover initial-snapshot, single-publish coalesce,
  per-resource independent debounce, dispose-cancels-pending, snapshot
  rejection isolation, send() throw isolation).

- /api/state/stream handler in server.ts mirrors the /api/debug/stream
  pattern: ReadableStream + createFramePusher (drop-under-backpressure with
  the same {kind:'dropped'} marker), 15s heartbeats, abort-signal teardown.
  On connect: one frame per resource. After: a fresh-snapshot frame per
  StateBus invalidation, 50ms per-resource debounce.

- The endpoint 503s when stateBus is absent (build without state-wiring),
  so clients can still fall back to the REST endpoints; the existing
  GET /api/processes etc remain in place for initial fetch + reconcile.

44 test files, 426/426 core suite green.
2026-06-24 21:44:28 +08:00
DrSmoothl 53f68b3945 feat(core): wire HookManager/BridgeManager edges into the StateBus
Phase 2 of switching processes/qq-list/connections from REST polling to SSE
push. Sinks the three publisher edges into a fresh StateBus:

- HookManager grows an OPTIONAL `onSessionsChanged: () => void` dep; called
  from pipe-watcher process-discovered/process-gone and from the previously
  unsubscribed HookSession 'status-changed' event (login/disconnected reach
  it transitively via applyStatus, so a single subscription covers every
  transition the WebUI processes view cares about). Throwing subscribers are
  caught + logged so the watcher loop is never aborted.

- New packages/core/src/webui/state-wiring.ts owns the coupling: produces the
  bus + the `onSessionsChanged` callback to feed HookManager, and registers
  BridgeManager session-started / session-closed listeners that publish
  'qq-list' + 'connections' (in source-of-truth order: account first, then
  adapters).

- index.ts threads stateWiring.bus into initWebUI so the phase-3 SSE handler
  has something to subscribe to; dispose runs on SIGINT/SIGTERM.

Bridge: 62/62 (was 57). Core: 419/419 (was 414). 10 new tests cover all
publish points + exception isolation + the optional-dep contract.
2026-06-24 21:35:27 +08:00
DrSmoothl 5302341dfc feat(core): StateBus — pure pub/sub for WebUI state invalidations
Phase 1 of switching processes/qq-list/connections from 3s REST polling to
SSE-pushed snapshots. The bus is a frozen-snapshot fan-out (subscribers added
during a publish() see only the next one, peer unsubscribes mid-fan-out don't
skip survivors) with exception isolation per listener.

Pure pub/sub by design — debounce and snapshot reads belong with the
subscriber (the /api/state/stream handler in phase 3) so different consumers
can coalesce on their own cadence.

8 unit tests, 414/414 core suite green.
2026-06-24 21:10:53 +08:00
DrSmoothl fb7675f3cb test(bridge): lock HookSession refresh drift fix
Two tests pinning the one intended behavior change from the status-
machine deepening: refresh while the pipe is down on a connected-but-
never-logged-in session now reports 'connecting' (matching onPipeDown),
not the old spurious 'disconnected'; and a session that HAD logged in
still settles to 'disconnected' + emits disconnected(true), proving the
flip is scoped to the never-logged-in case.

Verified against the pre-refactor baseline: test (1) fails on old code
(produced 'disconnected'), so it locks the flip rather than restating it.
2026-06-24 19:49:21 +08:00
DrSmoothl 1d2a56bcdb refactor(bridge): wire HookSession status through statusFor + shared reconcilers
Phase 2. Migrate the ~6 hand-copied status ternaries to the pure
statusFor() and collapse the pipe up/down orchestration into two shared
private reconcilers:

- reconcilePipeUp  ← onPipeUp + refresh's pipe-up branch
- reconcilePipeDown ← onPipeDown + refresh's pipe-down branch + the
  client 'close' handler (4 call sites, all were near-duplicates)

applyStatus() pushes the statusFor-derived status; loading/error stay
explicit. refreshInternal collapses to a one-line pipe poll. Behavior-
preserving except the intended drift fix (refresh-while-down + never
logged in now reports 'connecting', matching onPipeDown, not the old
spurious 'disconnected').

reconcilePipeDown short-circuits when !connected so a pipe-down tick
can't clobber a diagnostic error or emit a spurious status-changed on a
failed-connect/failed-load session — covered by two new regression
tests (caught in adversarial review). 55/55 green.
2026-06-24 19:42:59 +08:00
DrSmoothl 74c7e086c7 refactor(bridge): extract pure statusFor for HookSession status derivation
Phase 1 of deepening the HookSession status machine. The 5 settled
HookProcessStatus values (available/connecting/loaded/online/disconnected)
were hand-derived from (injected,connected,loggedIn,wasLoggedIn) at ~6
call sites in hook-session.ts. Extract that truth table into a pure
statusFor() in hook-status.ts so it has one source of truth and a
mutation-tight exhaustive table test. loading/error stay out-of-band.

Not yet wired into hook-session (phase 2).
2026-06-24 19:23:00 +08:00
DrSmoothl 1bdb8a40c4 fix(protocol): dedup duplicate system pushes (#137 official-robot double group_increase)
Inviting an official robot (e.g. 2854207029) into a group made QQ push the
group_member_increase notice twice, so SnowLuma emitted two
notice.group_increase events; a normal member produced one.

Root cause (RE of wrapper.linux.node): QQ NT dedups every received system
message in sys_msg_mgr.cc::ProcessRecvSysMsg (sub_37BADE0) by a global_key
`{peerUid}_{chatType}_{msg_seq}_{random}` (sub_37BC4E0) — an already-seen key
is dropped ("ignore dup msg") before any listener sees it. The per-message
discriminators msg_seq (attr 40003 = contentHead field 5) and random (attr
40002 = contentHead field 4) are exactly head.sequence and head.msgId
(msg_header_codec_helper.cc sub_37C8AD0). Kernel-based bots (NapCat/LLOneBot)
receive events after this dedup; SnowLuma reads the raw OlPush before it.

Mirror it: SysMsgDedup, a per-account bounded ring that drops a duplicate
system push by (msgType, subType, fromUin, sequence, msgId). Push-level (drops
the whole duplicate like NT), live path only (Bridge owns the tracker; the
forward re-parse passes none), system kinds only (chat messages excluded), and
never dedups a push lacking a server identity (sequence or msgId 0).
2026-06-23 20:36:24 +08:00
DrSmoothl 4e0ec92c23 fix(core): emit group_decrease + drop cache on set_group_leave (#133)
The server never pushes a member-decrease back to the member that left of its
own accord, so set_group_leave produced no notice.group_decrease — downstream
kept a 'zombie' group in its cache, and a later set_group_add_request failed
with 'matching group request not found'.

bridge.leave() now, after the 0x1097_1 OIDB succeeds, synthesizes a self
group_member_leave (user_id = operator_id = self, sub_type 'leave') through the
event bus — converted to notice.group_decrease by the existing path — and
calls identity.forgetGroup() so get_group_list / member lookups drop it
immediately (in-memory + DB inactive).

Kick / disband already arrive via the GroupMemberDecrease push (PkgType 34).
Limitation: a MANUAL leave in the NTQQ client isn't covered — SL is packet-
based with no kernel callback, and a voluntary self-leave isn't pushed back;
only kernel-based clients (NapCat/LLOneBot) catch that.

Validated by unit tests (bridge leave emits the event + forgets the group).
2026-06-22 23:07:44 +08:00
DrSmoothl 2b3d1c67c2 test(common): cover hex/log-summary/request-context; fix Utf8Validator dead code (#84, #85)
Reimplements PR #86 independently (author abandoned it after change-requests),
with the review feedback applied — the original tests asserted behavior the
code never had.

#84 — add @snowluma/common unit tests:
- hex: toHex/toHexUpper/hexPreview boundary + fromHex round-trip & odd-length throw
- log-summary: summarizeParams (top-level primitive is String()'d WITHOUT quotes;
  fields quoted; nested collapsed; total cap) and renderParamsVerbose (redaction,
  long-string marker is the Unicode ellipsis '…<N B>' not ASCII '...', circular guard)
- request-context: nextRequestId monotonic; runWithRequestId sync/async + nested scopes
- root scripts test:common/test:all/coverage; coverage/ gitignored

#85 — Utf8Validator: the second surrogate check was unreachable (within the
0x80–0xBF continuation-byte guard, 'b & 0x20' is true iff 'b >= 0xA0'); merge to
one check. No behavior change.

common suite green (26 tests).
2026-06-22 22:53:21 +08:00