Compare commits

...

60 Commits

Author SHA1 Message Date
snowluma-bot[bot]
a60385c376 Merge pull request #150 from SnowLuma/dev
chore: promote dev → main (351db57)
2026-06-26 11:50:10 +00: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
DrSmoothl
214287da28 ci(issues): auto-close stale needs-logs reports
Daily stale sweep over issues still labeled needs-logs: mark stale after
7 days of inactivity, close (not_planned) after another 7. Issues that
get valid logs lose the needs-logs label and are skipped by only-labels.
PRs are excluded.
2026-06-26 17:05:50 +08:00
DrSmoothl
81969a4590 ci(issues): enforce TRACE logs on bug reports via github-script
Form validation can only force a field non-empty, not validate content.
On bug issue opened/edited, parse the TRACE-log section: if empty, missing
a TRACE marker, or too short, label needs-logs + post a one-time guide
comment; auto-remove the label once the reporter edits in valid logs.
2026-06-26 17:05:50 +08:00
DrSmoothl
860848a310 feat(issue-template): require TRACE-level logs in bug reports
- Make the logs textarea required so a bug report can't be submitted empty.
- Document how to enable TRACE: WebUI server log-level switch (+ '开发'
  preset so the export actually contains trace lines) or SNOWLUMA_LOG_LEVEL=trace.
- Add a required preflight checkbox attesting TRACE logs are attached.
2026-06-26 17:05:50 +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
stla
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
19c03eb0ba chore(gitignore): ignore per-package runtime data dirs (**/data/)
The root /data/ rule is anchored to the repo root and missed
packages/<pkg>/data/<uin>/*.db that IdentityService writes to cwd during
tests. Add a recursive **/data/ so those test artifacts stay untracked.
2026-06-25 00:21:21 +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
9ad37d4ada chore(github): add PR template, bug-report deploy field, feature-request willingness dropdown 2026-06-24 00:46:15 +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
DrSmoothl
b918450483 fix(protocol): set_group_special_title — send uinName so the title actually applies
The 0x8FC_2 body omitted uinName (tag 7), so the server accepted the request
(errorCode 0) but silently never applied the title — looking like the feature
was unsupported. Both NapCat (Oidb.0x8FC_2: uinName=title) and Lagrange
(0x8FC body @7 UinName=title) set it; mirror them by sending uinName = title.

No RE needed — two independent packet-based implementations agree on the field.

Note: setting a special title is group-owner-only, so on-target validation
requires a group the bot owns.
2026-06-22 21:53:33 +08:00
snowluma-bot[bot]
157cc90397 Merge pull request #132 from SnowLuma/dev
chore: promote dev → main (1bd1265)
2026-06-22 13:31:34 +00:00
DrSmoothl
1bd126562f chore(release): v1.10.2 2026-06-22 21:31:06 +08:00
DrSmoothl
e160837f8b feat(onebot): tiered reply backfill + quoted-file recovery for get_msg (#128)
Harvests the sound ideas from PR #128 while KEEPING origSeqs[0] as the c2c
reply sequence (on-target capture in #114/#124 proved origSeqs[0] == the quoted
message's head.sequence; pbReserve.friendSequence is a small unrelated counter
that makes reply.id miss). The PR's friendSequence override is intentionally
NOT taken.

- rich-body-decoder: enrich the reply element with replySenderUin/replyTime and
  the quoted message's own decoded elements (SrcMsg.elems, field 5); recover a
  c2c quoted FILE from sourceMsg (field 9 -> RichText.notOnlineFile) when elems
  carried none, so a quoted file survives into get_msg (#124).
- backfillReplyTarget: tiered fallback — Tier 0 local store, Tier 1 server fetch
  (correct seq = origSeqs[0]), Tier 2 reconstruct from the embedded quoted
  elements (no round-trip), Tier 3 minimal '[引用消息]' placeholder so get_msg
  never returns 'message not found'.
- to-segment: per-element try/catch (logged, not silent) so one bad element
  doesn't drop the whole message.
- actions/message: log get_msg misses.
- tests: fix request-actions getGroupInviteCardSequence mock (gap from #125);
  cover backfill Tier 2 (reconstruct) + Tier 3 (placeholder); flip the stale
  c2c reply test to assert origSeqs[0] (was asserting the disproven
  friendSequence).

Validated on-target (Docker): get_msg on group reply, private text reply, and a
private quoted FILE all return correct content (file with name/size/id); full
onebot + protocol suites green.
2026-06-22 21:25:05 +08:00
DrSmoothl
4593ba3340 fix(protocol): strip reply auto-mention on receive; align send to uin=0 (#127)
A QQ NT reply carries the replied sender as a structural auto-mention
(MentionExtra.type=2, uin=0) right after srcMsg, plus a blank separator
text. SnowLuma reported both as a real [CQ:at] + empty/space segment, so
downstreams saw a phantom @ (#127). A real user @ carries a non-zero
MentionExtra.uin, so it is preserved.

- receive (rich-body-decoder): after a reply, drop a type=2/uin=0 mention
  and the blank text that follows it; keep non-zero-uin mentions.
- send (element-builder, #129 follow-up): the reply auto-mention added for
  reply+@ now uses uin=0 (real uid stays in `uid`) to match QQ's native wire
  shape, so the bot's own replies are stripped the same way by receivers and
  don't surface a phantom @ either.

Validated on-target (Docker, group): reply w/o @ -> [reply, text] (no
phantom @/empty); reply w/ @ -> [reply, at(real), text]; bot reply+@ still
delivers the @ (uin=0).
2026-06-22 20:53:10 +08:00
DrSmoothl
45aae92af5 fix(protocol): group reply+at — emit replied-sender mention after srcMsg (#129)
When a group message combined a reply with a user @ , the @ showed but
never notified (no blue link, no ping). On-target capture showed SnowLuma
sent [srcMsg, @target(mention), text] — the @ lands directly in the reply's
mention slot right after srcMsg, which the QQ NT group server does not honor.

Mirror Lagrange's ForwardEntity.PackElement: when a reply and an @ coexist
in a group message, emit the replied sender as a trailing mention element
right after srcMsg, so the user's @ is no longer the first post-srcMsg
element and is honored. Gated to the reply+@ case so plain replies are
unchanged.

Validated on-target (Docker, group send): baseline reply+at -> @ not
delivered; fixed -> @ delivered (blue link + notification).
2026-06-22 20:37:19 +08:00
DrSmoothl
839de51519 fix(protocol): c2c reply uses origSeqs[0], not friendSequence (#114, #124)
A private (c2c) reply resolved to srcMsg.reserve.friendSequence, but a
received message's message_id is hashed from its head.sequence. On-target
capture showed origSeqs[0] == head.sequence (e.g. 12709) while friendSequence
is a small friend-relationship counter (e.g. 25) — so reply.id != the quoted
message_id. Downstream get_msg(reply_id) then missed:

- #114: reported reply id didn't match the quoted message's real id.
- #124: replying to a File message returned empty quoted content (AstrBot
  relies on get_msg(reply_id) to learn the quote was a file; text replies
  appeared fine because they read the inline follow-up text instead).

Drop the c2c friendSequence override (reverting cf8e62d's premise, which was
backwards) so both group and c2c replies use origSeqs[0].

Validated on-target (Docker): file message id == reply.id, and
get_msg(reply_id) -> retcode 0, message [{type:file}].
2026-06-22 16:07:36 +08:00
DrSmoothl
11e7584d1c fix(onebot): approve bot self-invite via private card msgseq (#125)
When the bot is invited to a group via a private-chat "qun.invite" ark
card, set_group_add_request failed: handleGroupAddRequest re-derived the
approval tuple from fetchGroupRequests (0x10c8_2), but for a self-invite the
only sequence the server accepts at 0x10c8_1 is the msgseq embedded in the
card's mqqapi://group/invite_join jumpUrl, applied with eventType=2 /
filtered=false. The MSF invite push (PkgType 87) never carries that msgseq,
so approval returned 120161001 'handle async message fail'.

- friend-message decoder: parse the private invite card's jumpUrl and stash
  groupUin -> msgseq on the per-instance IdentityService.
- ContactsApi.getGroupInviteCardSequence(groupId) exposes it.
- handleGroupAddRequest: for an invite flag, if a card msgseq is cached,
  approve with setAddRequest(groupId, msgseq, 2, approve, reason, false);
  otherwise fall back to the existing fetchGroupRequests path.

Validated on-target (Docker): private invite card -> set_group_add_request
approve -> 0x10c8_1 ok -> bot joined the group (get_group_member_info shows
role=member, fresh join_time); no 120161001.
2026-06-22 15:25:28 +08:00
snowluma-bot[bot]
f470b7a10c Merge pull request #122 from SnowLuma/dev
chore: promote dev → main (8b87f80)
2026-06-21 17:45:50 +00:00
DrSmoothl
8b87f80951 chore(release): v1.10.1 2026-06-22 01:45:25 +08:00
DrSmoothl
b135752577 fix(highway): retry chunk upload on transient transport errors (#118)
Large private files (e.g. 48 MB .flac via send_private_msg) failed with
"connection closed before response (received 0 bytes, headerSeen=false)".
uploadHighwayHttp sends one fresh TCP connection per 1 MB chunk with no
retry, so a 48 MB file is ~48 sequential connections and a single transient
peer-FIN / reset among them aborted the entire upload. Small files (1 chunk)
always worked; NapCat is unaffected because it delegates to QQ's native
highway client, which retries.

Wrap each chunk's connect + POST in a bounded retry (3 attempts, 300 ms ×
attempt backoff, fresh connection each time). Re-sending the same offset
range is idempotent server-side. Only transport failures retry; a decoded
highway error_code is a definitive server reject and is not retried.
2026-06-22 01:45:12 +08:00
snowluma-bot[bot]
fd2345b772 chore(native): replace native artifacts (native-latest) (#121)
Build: https://github.com/SnowLuma/SnowLumaNative/releases/tag/native-latest

Co-authored-by: snowluma-bot[bot] <283088347+snowluma-bot[bot]@users.noreply.github.com>
2026-06-22 01:41:50 +08:00
snowluma-bot[bot]
7f391e065e Merge pull request #117 from SnowLuma/dev
chore: promote dev → main (9efe162)
2026-06-21 12:23:09 +00:00
snowluma-bot[bot]
261d6596dc Merge pull request #109 from SnowLuma/dev
chore: promote dev → main (dfb6aa5)
2026-06-18 09:16:43 +00:00
snowluma-bot[bot]
5d08fc8471 Merge pull request #103 from SnowLuma/dev
chore: promote dev → main (16920b4)
2026-06-16 14:00:12 +00:00
snowluma-bot[bot]
e5e6d50f2f Merge pull request #101 from SnowLuma/dev
chore: promote dev → main (7e59dbf)
2026-06-15 05:58:03 +00:00
snowluma-bot[bot]
7d90820e19 Merge pull request #100 from SnowLuma/dev
chore: promote dev → main (ee8eb92)
2026-06-14 08:29:02 +00: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
snowluma-bot[bot]
d2c56d565b Merge pull request #92 from SnowLuma/dev
chore: promote dev → main (d508814)
2026-06-09 06:23:12 +00: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
snowluma-bot[bot]
40c65c87bd Merge pull request #88 from SnowLuma/dev
chore: promote dev → main (174150c)
2026-06-07 13:20:48 +00:00
110 changed files with 4116 additions and 400 deletions

View File

@@ -18,13 +18,15 @@ body:
required: true
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
required: true
- label: 我已将日志级别调到 TRACE,并在下方「TRACE 日志」一栏附上了复现期间的完整日志
required: true
- type: input
id: snowluma-version
attributes:
label: SnowLuma 版本
description: 启动日志首行或 `package.json` 里的版本号
placeholder: "例如 1.8.5"
placeholder: "例如 1.10.2"
validations:
required: true
@@ -53,6 +55,19 @@ body:
validations:
required: true
- type: dropdown
id: deploy
attributes:
label: 部署方式
description: 如何运行 SnowLuma
options:
- 源码运行(pnpm dev / start)
- 预构建包
- Docker
- 其他 / 不确定
validations:
required: true
- type: input
id: node-version
attributes:
@@ -106,11 +121,21 @@ body:
- type: textarea
id: logs
attributes:
label: 相关日志 / 错误堆栈
label: TRACE 日志 / 错误堆栈
description: |
粘贴控制台日志、SSE 实时日志或错误堆栈。
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
开启 TRACE 的两种方式(任选其一):
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
- **环境变量**:启动前设置 `SNOWLUMA_LOG_LEVEL=trace` 再运行,复现后复制控制台输出。
贴出的日志里应当能看到 `TRACE` 字样。请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
placeholder: |
[2026-06-26 12:00:00.000] TRACE [core] ...
[2026-06-26 12:00:00.001] DEBUG [bridge] ...
render: shell
validations:
required: true
- type: textarea
id: extra

View File

@@ -66,11 +66,13 @@ body:
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
- 相关讨论: #xxx
- type: checkboxes
- type: dropdown
id: willingness
attributes:
label: 您是否愿意提交 PR 来实现这个功能?
options:
- label: 愿意,且需要维护者讨论方案后再动手
- label: 愿意,已有大致实现思路
- label: 暂时只提建议
- 愿意,但需要维护者讨论方案后再动手
- 愿意,已有大致实现思路
- 暂时只提建议
validations:
required: true

17
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,17 @@
<!-- 感谢贡献。请填写以下内容,方便评审。 -->
## 关联 Issue
<!-- 例如 Closes #123。若无关联 issue,请说明这个 PR 解决什么问题、为何现在做。 -->
## 变更说明
<!-- 简述本 PR 做了什么、为什么这样做。 -->
## 提交前检查
- [ ] 本 PR 聚焦单一目标,未夹带无关改动
- [ ] 已通过 `pnpm lint` 与 `pnpm typecheck`
- [ ] 已补充/更新相关测试,且 `pnpm test` 通过
- [ ] 文件行尾为 LF(未引入 CRLF)
- [ ] PR 描述与实际实现一致

View File

@@ -0,0 +1,90 @@
name: 校验 Bug 反馈日志
# 表单只能强制「非空」,强制不了「内容真的是 TRACE 级别」。
# 这个 workflow 在 bug issue 打开/编辑时解析正文里的 TRACE 日志小节,
# 缺日志就打 needs-logs 标签 + 评论,补齐后自动移除标签。
on:
issues:
types: [opened, edited]
permissions:
issues: write
jobs:
require-trace-logs:
runs-on: ubuntu-latest
# 只校验 Bug 反馈(表单会自动打 bug 标签)
if: contains(join(github.event.issue.labels.*.name, ','), 'bug')
steps:
- uses: actions/github-script@v7
with:
script: |
const NEEDS = 'needs-logs';
const MARKER = '<!-- needs-logs-bot -->';
const { owner, repo } = context.repo;
const issue = context.payload.issue;
const number = issue.number;
const body = issue.body || '';
// 抽取「TRACE 日志 / 错误堆栈」小节(issue form 渲染成 ### 标题)
const m = body.match(/###\s*TRACE 日志[^\n]*\n([\s\S]*?)(?:\n###\s|$)/);
const section = (m ? m[1] : '').trim();
const empty = section === '' || /^_no response_$/i.test(section);
const hasTrace = /\bTRACE\b/i.test(section);
// 去掉代码围栏后过短,基本等于没给
const stripped = section.replace(/```[a-z]*|```|`/gi, '').trim();
const tooShort = stripped.length < 40;
const ok = !empty && hasTrace && !tooShort;
const hasLabel = (issue.labels || []).some((l) => (l.name || l) === NEEDS);
if (ok) {
if (hasLabel) {
try {
await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: NEEDS });
} catch (e) { /* 已被手动移除则忽略 */ }
}
return;
}
// 确保标签存在再添加(addLabels 不会自动建标签)
try {
await github.rest.issues.getLabel({ owner, repo, name: NEEDS });
} catch (e) {
try {
await github.rest.issues.createLabel({
owner, repo, name: NEEDS, color: 'd93f0b',
description: '缺少有效的 TRACE 日志',
});
} catch (e2) { /* 并发下可能已被建出 */ }
}
await github.rest.issues.addLabels({ owner, repo, issue_number: number, labels: [NEEDS] });
// 已经提示过就不再刷屏
const comments = await github.paginate(github.rest.issues.listComments, {
owner, repo, issue_number: number,
});
if (comments.some((c) => (c.body || '').includes(MARKER))) return;
const reasons = [];
if (empty) reasons.push('- 日志字段为空');
else if (!hasTrace) reasons.push('- 日志里没有 `TRACE` 字样(默认级别 `info` 不输出 TRACE,需先开启)');
else if (tooShort) reasons.push('- 日志内容过短,疑似未提供完整日志');
const comment = [
MARKER,
`@${issue.user.login} 这条反馈缺少有效的 **TRACE 级别日志**,已标记为 \`${NEEDS}\`:`,
'',
reasons.join('\n'),
'',
'请按以下任一方式开启 TRACE 后复现,再 **编辑本 issue** 把完整日志补到「TRACE 日志 / 错误堆栈」一栏:',
'',
'- **WebUI**:「日志」页 → 服务端日志级别切到 `TRACE` → 显示过滤用「开发」预设 → 复现 → 导出当前视图。',
'- **环境变量**:`SNOWLUMA_LOG_LEVEL=trace` 启动后复现。',
'',
'补齐后机器人会自动移除该标记。若你以附件形式上传了 `.log` 文件,请在正文里也贴一段关键日志(机器人只能识别正文)。',
].join('\n');
await github.rest.issues.createComment({ owner, repo, issue_number: number, body: comment });

34
.github/workflows/stale-needs-logs.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
name: 关闭长期缺日志的反馈
# needs-logs 的 issue 若长期不补 TRACE 日志,先标 stale,再自动关闭。
# 补齐日志后 issue-require-logs 会移除 needs-logs,这里 only-labels 过滤即跳过。
on:
schedule:
- cron: '0 2 * * *'
workflow_dispatch:
permissions:
issues: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
only-labels: 'needs-logs'
days-before-stale: 7
days-before-close: 7
stale-issue-label: 'stale'
close-issue-reason: 'not_planned'
ascending: true
# 不处理 PR
days-before-pr-stale: -1
days-before-pr-close: -1
stale-issue-message: >
这条反馈因长期缺少有效的 TRACE 日志被标记为 `stale`。
若 7 天内仍未补充日志,将自动关闭。补充后请编辑 issue 贴上日志或留言。
close-issue-message: >
因长期缺少定位所需的 TRACE 日志,已自动关闭。
如果问题仍然存在,欢迎补齐 TRACE 日志后重新打开本 issue 或新开一个。

6
.gitignore vendored
View File

@@ -11,7 +11,13 @@ dist/
/config/
/data/
# per-package runtime data dirs (e.g. packages/core/data/<uin>/*.db written by
# IdentityService during tests) — not just the root /data/
**/data/
logs/
# macOS metadata
.DS_Store
# test coverage output
coverage/

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.10.0",
"version": "1.10.3",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -16,6 +16,9 @@
"dev:web": "pnpm --filter webui dev",
"test": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"test:common": "pnpm --filter @snowluma/common test",
"test:all": "pnpm -r --if-present test",
"coverage": "pnpm --filter @snowluma/common test -- --coverage",
"typecheck": "pnpm -r --if-present typecheck",
"lint": "eslint .",
"lint:fix": "eslint . --fix",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.10.0",
"version": "1.10.3",
"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).",

View File

@@ -49,6 +49,13 @@ export type HookManagerDeps = {
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state. */
autoLoadOnDiscovery?: boolean;
/** Optional hook fired whenever the set of HookProcessInfo observable to
* `listProcesses()` changes — new process discovered, process gone, or
* any session's status mutated. Used by the WebUI SSE wiring to push a
* fresh processes snapshot to connected clients without REST polling.
* Exceptions thrown by the callback are caught and logged; they do not
* break the watcher / session event loops. */
onSessionsChanged?: () => void;
log?: Logger;
};
@@ -76,6 +83,7 @@ export class HookManager {
private readonly ownsPipeWatcher: boolean;
private readonly listProcessesNative: () => HookProcessBaseInfo[];
private readonly autoLoadOnDiscovery: boolean;
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
private readonly sessions = new Map<number, HookSession>();
private readonly startPromise: Promise<void>;
@@ -85,6 +93,7 @@ export class HookManager {
constructor(deps: HookManagerDeps) {
this.bridgeManager = deps.bridgeManager;
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
this.onSessionsChangedRaw = deps.onSessionsChanged;
this.log = deps.log ?? createLogger('Hook');
this.injector = deps.injector ?? {
@@ -193,11 +202,13 @@ export class HookManager {
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
});
}
this.notifySessionsChanged();
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.notifyProcessGone();
this.notifySessionsChanged();
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
@@ -253,6 +264,12 @@ export class HookManager {
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
});
// status-changed fires on EVERY internal status mutation, including the
// ones reached via login / disconnected / refresh — subscribing here
// alone covers every transition the WebUI processes view cares about.
session.on('status-changed', () => {
this.notifySessionsChanged();
});
session.on('disposed', () => {
this.sessions.delete(pid);
});
@@ -261,6 +278,19 @@ export class HookManager {
return session;
}
/** Fire the optional sessions-changed hook with exceptions isolated.
* A throwing subscriber must not abort the watcher's emit loop or break
* a HookSession event handler in flight. */
private notifySessionsChanged(): void {
if (this.disposed) return;
if (!this.onSessionsChangedRaw) return;
try {
this.onSessionsChangedRaw();
} catch (err) {
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
}
}
private assertValidPid(pid: number): void {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
}

View File

@@ -4,6 +4,7 @@ import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
export type HookSessionDeps = {
@@ -131,17 +132,7 @@ export class HookSession extends EventEmitter {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
// Adopt a DLL that survived a SnowLuma restart.
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
await this.reconcilePipeUp();
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}
@@ -149,18 +140,7 @@ export class HookSession extends EventEmitter {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
if (!this.connected) {
// Nothing to tear down; just keep status visible.
if (this.injected) this.setStatus('connecting', this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
'',
);
if (wasLoggedIn) this.emit('disconnected', true);
this.reconcilePipeDown();
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
}
@@ -227,10 +207,7 @@ export class HookSession extends EventEmitter {
this._method = this.injectResult.method;
}
}
this.setStatus(
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
'',
);
this.applyStatus();
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
@@ -281,24 +258,14 @@ export class HookSession extends EventEmitter {
private async refreshInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
if (pipeUp) {
// Adopt an unknown DLL the same way onPipeUp would.
if (!this.injected) {
this.injected = true;
this._method = this._method || 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
// Same pipe-up / pipe-down reconcilers the watcher drives, chosen by
// a fresh poll. This collapses what used to be a hand-copied pair of
// onPipeUp/onPipeDown bodies — and fixes the drift where the down
// branch reported 'disconnected' even for a never-logged-in session.
if (this.pipeWatcher.isPipeLive(this.pid)) {
await this.reconcilePipeUp();
} else {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(this.injected ? 'disconnected' : 'available', '');
if (wasLoggedIn) this.emit('disconnected', true);
this.reconcilePipeDown();
}
} catch (error) {
this._error = errMsg(error);
@@ -308,6 +275,55 @@ export class HookSession extends EventEmitter {
return this.toInfo();
}
// ─────────────── settled-status reconcilers ───────────────
/** Push the settled status derived from the live flags. `wasLoggedIn`
* defaults to the current `loggedIn`; callers that just tore the client
* down pass the value captured *before* teardown (teardown clears it). */
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
this.setStatus(statusFor({
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
wasLoggedIn,
}), error);
}
/** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a
* stale client, then (re)connect if needed or just settle the status.
* Shared by onPipeUp and refresh's pipe-up branch. */
private async reconcilePipeUp(): Promise<void> {
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.applyStatus();
}
}
/** Pipe is down (or the client closed): tear down, settle the status,
* and emit the disconnect notification iff we owed BridgeManager one
* (i.e. we had reached login). Shared by onPipeDown, refresh's pipe-down
* branch, and the client 'close' handler. */
private reconcilePipeDown(): void {
if (!this.connected) {
// Nothing live to tear down. A session that never connected can't owe
// a disconnect, and we must NOT clobber a diagnostic the failed
// connect/load already set — settle the status keeping `_error`, or
// (when not even injected) leave the status untouched entirely.
if (this.injected) this.applyStatus(this.loggedIn, this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.applyStatus(wasLoggedIn);
if (wasLoggedIn) this.emit('disconnected', true);
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
@@ -327,15 +343,19 @@ export class HookSession extends EventEmitter {
try {
await client.connectAll({ recv: true });
this.connected = true;
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
const loginState = client.getLoginState();
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) this.handleLoginState(loginState);
else this.applyStatus();
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient();
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
this.applyStatus(false, this._error);
}
}
@@ -355,16 +375,7 @@ export class HookSession extends EventEmitter {
void this.serialize(async () => {
if (this.disposed) return;
if (this.client !== client) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (!this.injected) {
this.setStatus('available', '');
} else if (wasLoggedIn) {
this.setStatus('disconnected', '');
} else {
this.setStatus('connecting', '');
}
if (wasLoggedIn) this.emit('disconnected', true);
this.reconcilePipeDown();
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
});
}
@@ -388,10 +399,14 @@ export class HookSession extends EventEmitter {
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
if (this.loggedIn) {
this.setStatus('online', '');
} else if (this.connected) {
this.setStatus('loaded', this._error);
// Only the connected/logged-in states are ours to set here; when fully
// down we leave the status the teardown path already settled.
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
// observed on a live client, and teardown clears `loggedIn` before
// `connected`), so statusFor lands 'online' here rather than the
// disconnected/connecting branch.
if (this.connected || this.loggedIn) {
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
}
if (!this.loggedIn || !this.sender) return;

View File

@@ -0,0 +1,31 @@
import type { HookProcessStatus } from './types';
/**
* The flags that fully determine a HookSession's *settled* status.
* `wasLoggedIn` carries the one bit of history the derivation needs:
* on ANY injected-but-not-connected path (connect failure, pipe close,
* refresh-while-down), the session reads `disconnected` only if it had
* reached login, otherwise it's still `connecting`. Capture it from
* `loggedIn` *before* tearing the client down, since teardown clears it.
*/
export interface HookFlags {
injected: boolean;
connected: boolean;
loggedIn: boolean;
wasLoggedIn: boolean;
}
/**
* Single source of truth for the five *settled* HookProcessStatus values
* — `available` / `connecting` / `loaded` / `online` / `disconnected`.
*
* Pure: status is a function of the flags alone. The two *out-of-band*
* states `loading` (injection in flight) and `error` (carries a message)
* are set explicitly by HookSession and are deliberately NOT derivable
* here.
*/
export function statusFor(flags: HookFlags): HookProcessStatus {
if (!flags.injected) return 'available';
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
}

View File

@@ -2,6 +2,8 @@ import { existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { listSnowlumaPipePidsSync } from './qq-hook-client';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle {
@@ -98,6 +100,17 @@ export function getNativeHookLoadError(): string | null {
}
export function listHookProcesses(): HookProcessBaseInfo[] {
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
// means QQ ran with our dylib already mapped, so the dylib's listener
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
// in the runtime dir as a known process (the watcher's subsequent
// connectable-probe gates the pipe-up emit, so a stale dangling socket
// here doesn't drive a false connect).
if (process.platform === 'darwin') {
return [...listSnowlumaPipePidsSync()]
.sort((a, b) => a - b)
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
}
const addon = getNativeHookAddon();
if (!addon) return [];
return [...new Set(addon.getAllMainProcess())]

View File

@@ -1,5 +1,5 @@
import { EventEmitter } from 'events';
import { promises as fs } from 'fs';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
@@ -85,12 +85,59 @@ interface PendingAck {
wantReply: boolean;
}
/**
* Sync directory scan for `mojo.<pid>.control.sock` socket files in the
* runtime dir, returning the pid set. Used by the darwin path of
* `listHookProcesses()` — on macOS the DYLD_INSERT injection model means
* there is no native enumerate-QQ-processes addon; the existence of our
* dylib's listener socket IS the proof that a QQ process is hooked. The
* sync variant is needed because the watcher's `listProcesses` dep is sync.
*
* Mirrors `listLiveLinuxPipePids` (the async + connectable-probe variant)
* but skips the connectable probe — the existence of the socket file is
* sufficient signal for "process exists with our dylib mapped". The async
* variant still gates the subsequent `pipe-up` emit via a real connect.
*/
export function listSnowlumaPipePidsSync(
runtimeDir = linuxRuntimeDir(),
): Set<number> {
const result = new Set<number>();
let names: string[];
try {
names = readdirSync(runtimeDir);
} catch {
return result;
}
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
if (!m) continue;
const pid = Number(m[1]);
if (Number.isInteger(pid) && pid > 0) result.add(pid);
}
return result;
}
function linuxRuntimeDir(): string {
// Name kept for historical reasons (the function predates the macOS port);
// applies to every non-win32 platform. The fallback order mirrors each
// platform hook's runtime_dir(): explicit override first, then the OS-
// native ephemeral-dir convention.
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
if (explicit && explicit.length > 0) return explicit;
const xdg = process.env.XDG_RUNTIME_DIR;
if (xdg && xdg.length > 0) return xdg;
// Mirrors hook_stub.cpp runtime_dir() fallback.
// macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/
// qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS
// (under /var/folders/.../T) so this is the right place — Linux's
// /tmp/snowluma-<uid> doesn't exist on a stock Mac.
if (process.platform === 'darwin') {
const tmpdir = process.env.TMPDIR;
if (tmpdir && tmpdir.length > 0) {
const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir;
return path.join(trimmed, 'snowluma-hook');
}
}
// Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort.
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
return `/tmp/snowluma-${uid}`;

View File

@@ -0,0 +1,173 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookManager } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
// Regression cover for the WebUI SSE wiring: HookManager must call its
// optional `onSessionsChanged` callback every time the observable set of
// HookProcessInfo (what `listProcesses()` would return) changes, so the
// /api/state/stream handler can push a fresh processes snapshot to the
// browser without REST polling.
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
interface Harness {
manager: HookManager;
pipeWatcher: PipeWatcher;
setProcesses: (next: number[]) => void;
setLivePipes: (next: number[]) => void;
onSessionsChanged: ReturnType<typeof vi.fn>;
clientFactory: ReturnType<typeof vi.fn>;
}
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
const clientFactory = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => { /* succeed without doing anything */ };
(c as any).close = () => { (c as any).isClosed = true; };
return c as unknown as QqHookClient;
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink;
const onSessionsChanged = vi.fn();
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: clientFactory,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
onSessionsChanged,
});
return {
manager,
pipeWatcher,
onSessionsChanged,
clientFactory,
setProcesses: (next) => { pids = next; },
setLivePipes: (next) => { live = new Set(next); },
};
}
describe('HookManager.onSessionsChanged', () => {
it('fires when the watcher discovers a new QQ process', async () => {
const ctx = makeManager({ processes: [] });
await ctx.pipeWatcher.start();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports a process is gone', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
// Inject so the session is in 'connecting' state; the next pipe-up
// makes attemptConnect succeed and status flips to 'loaded'.
await ctx.manager.loadProcess(4242);
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setLivePipes([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
const ctx = makeManager({ processes: [] });
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
await ctx.pipeWatcher.start();
ctx.setProcesses([4242]);
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await flush();
// A second tick still fires the callback — it wasn't unregistered by
// the prior throw.
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([4242, 5555]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
const pids = [4242];
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
const manager = new HookManager({
bridgeManager: {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: vi.fn(() => {
const c = new EventEmitter() as any;
c.isClosed = false; c.isLoggedIn = false;
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
c.connectAll = async () => undefined;
c.close = () => { c.isClosed = true; };
return c;
}),
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
await pipeWatcher.tickNow();
await flush();
const list = await manager.listProcesses();
expect(list).toHaveLength(1);
expect(list[0].pid).toBe(4242);
manager.dispose();
});
});

View File

@@ -347,6 +347,95 @@ describe('HookSession — process gone', () => {
});
});
describe('HookSession — refresh drift fix', () => {
// refresh while the pipe is down on a connected-but-never-logged-in
// session now reports 'connecting' (matching what onPipeDown gives for the
// same state), not the old spurious 'disconnected'. Pre-refactor, refresh's
// down branch ignored wasLoggedIn and always reported 'disconnected'.
it('refresh-while-down + never logged in → connecting (not disconnected), no disconnect emit', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('loaded'); // connected, never logged in
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
ctx.setPipeLive(false);
const info = await ctx.session.refresh();
expect(info.status).toBe('connecting'); // drift fix: was 'disconnected'
expect(discSpy).not.toHaveBeenCalled(); // never logged in ⇒ nothing owed
});
it('refresh-while-down after login still → disconnected + emits disconnected(true)', async () => {
// The flip is scoped to the never-logged-in case; a real session that
// had reached login must still settle to 'disconnected' and notify.
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
expect(ctx.session.status).toBe('online');
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
ctx.setPipeLive(false);
const info = await ctx.session.refresh();
expect(info.status).toBe('disconnected');
expect(discSpy).toHaveBeenCalledWith(true);
});
});
describe('HookSession — pipe-down must not clobber a settled error', () => {
// Regression net for the phase-2 reconcilePipeDown !connected short-circuit:
// a pipe-down tick on a session that never reached a live connection must
// not wipe a diagnostic error or emit a spurious status-changed.
it('onPipeDown after a failed connect keeps the error and does not re-emit', async () => {
const ctx = makeSession({ pipeLive: true, clientFailsConnect: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('connecting');
expect(ctx.session.error).toBe('connect failed');
const statusSpy = vi.fn();
ctx.session.on('status-changed', statusSpy);
ctx.session.onPipeDown();
await flush();
expect(ctx.session.status).toBe('connecting');
expect(ctx.session.error).toBe('connect failed'); // not wiped to ''
expect(statusSpy).not.toHaveBeenCalled(); // no spurious emit
});
it('onPipeDown after a failed load leaves the error status intact', async () => {
const injector = {
inject: vi.fn(() => { throw new Error('inject boom'); }),
unload: vi.fn(),
};
const session = new HookSession(1234, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
await session.load();
expect(session.status).toBe('error');
expect(session.error).toBe('inject boom');
session.onPipeDown();
await flush();
expect(session.status).toBe('error'); // not flipped to 'available'
expect(session.error).toBe('inject boom'); // not wiped
});
});
describe('HookSession — packet forwarding', () => {
// These tests cover the field-rename + filter logic that used to live
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means

View File

@@ -0,0 +1,56 @@
import { describe, it, expect } from 'vitest';
import { statusFor, type HookFlags } from '../src/hook-status';
import type { HookProcessStatus } from '../src/types';
const F = (o: Partial<HookFlags>): HookFlags => ({
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
});
describe('statusFor — settled HookProcessStatus derivation', () => {
it('not injected → available (regardless of other flags)', () => {
expect(statusFor(F({ injected: false }))).toBe('available');
// !injected dominates: stale connected/loggedIn bits must not leak through.
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
});
it('injected, connected, loggedIn → online', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
});
it('injected, connected, not loggedIn → loaded', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
});
it('injected, not connected, had logged in → disconnected', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
});
it('injected, not connected, never logged in → connecting', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
});
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
const base = { injected: true, connected: false, loggedIn: false };
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
});
it('covers exactly the five settled states across the flag space', () => {
const seen = new Set<HookProcessStatus>();
for (const injected of [false, true]) {
for (const connected of [false, true]) {
for (const loggedIn of [false, true]) {
for (const wasLoggedIn of [false, true]) {
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
}
}
}
}
expect([...seen].sort()).toEqual(
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
);
// The two out-of-band states are never produced by the pure derivation.
expect(seen.has('loading')).toBe(false);
expect(seen.has('error')).toBe(false);
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.10.0",
"version": "1.10.3",
"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).",
@@ -16,6 +16,10 @@
"types": "./src/logger.ts",
"default": "./src/logger.ts"
},
"./coerce": {
"types": "./src/coerce.ts",
"default": "./src/coerce.ts"
},
"./hex": {
"types": "./src/hex.ts",
"default": "./src/hex.ts"

View File

@@ -0,0 +1,30 @@
// Scalar coercion primitives for normalizing untrusted JSON config into
// typed values with fallbacks. Zero dependencies — these were duplicated
// verbatim across notifications/config and webui/ui-config; this is their
// single home. Input tolerance is deliberate (numeric strings coerce), but
// validity is strict (a wrong type yields the caller's fallback, never a
// silent 0/'' — except where the primitive's contract says otherwise).
/** True only for a plain, non-null, non-array object. */
export function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/** The value when it is a real boolean, else the fallback. Strings/numbers
* are NOT coerced — `'true'` and `1` both yield the fallback. */
export function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
/** A finite number (numeric strings coerced) clamped to `[min, max]`, else
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
export 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));
}
/** `clampNum` truncated toward zero — clamp first, then drop the fraction. */
export function clampInt(value: unknown, min: number, max: number, fallback: number): number {
return Math.trunc(clampNum(value, min, max, fallback));
}

View File

@@ -0,0 +1,78 @@
import { describe, it, expect } from 'vitest';
import { isObject, boolOr, clampNum, clampInt } from '../src/coerce';
describe('isObject', () => {
it('is true only for plain non-null non-array objects', () => {
expect(isObject({})).toBe(true);
expect(isObject({ a: 1 })).toBe(true);
expect(isObject(null)).toBe(false);
expect(isObject([])).toBe(false);
expect(isObject('x')).toBe(false);
expect(isObject(42)).toBe(false);
expect(isObject(undefined)).toBe(false);
});
});
describe('boolOr', () => {
it('returns the value only when it is a real boolean, else the fallback', () => {
expect(boolOr(true, false)).toBe(true);
expect(boolOr(false, true)).toBe(false);
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
expect(boolOr(1, false)).toBe(false);
expect(boolOr(undefined, true)).toBe(true);
expect(boolOr(null, true)).toBe(true);
});
});
describe('clampNum', () => {
it('passes finite numbers through, clamped to [min,max]', () => {
expect(clampNum(5, 0, 10, -1)).toBe(5);
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
});
it('coerces numeric strings', () => {
expect(clampNum('7', 0, 10, -1)).toBe(7);
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
});
it('falls back on non-finite / non-numeric input', () => {
expect(clampNum('abc', 0, 10, 3)).toBe(3);
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
expect(clampNum(null, 0, 10, 3)).toBe(3);
expect(clampNum({}, 0, 10, 3)).toBe(3);
});
it('preserves fractional precision within bounds', () => {
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
});
});
describe('clampInt', () => {
it('is clampNum truncated toward zero', () => {
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
expect(clampInt(5, 0, 10, -1)).toBe(5);
});
it('clamps before truncating', () => {
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
});
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
// primitive (future callers may use fractional bounds).
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
});
it('falls back on non-finite input', () => {
expect(clampInt('abc', 0, 10, 4)).toBe(4);
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
});
});

View File

@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
describe('hex', () => {
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
expect(toHex(b)).toBe('000fa0ff');
expect(toHexUpper(b)).toBe('000FA0FF');
expect(toHex(Uint8Array.of())).toBe('');
});
it('hexPreview appends "..." only past maxBytes', () => {
const b = Uint8Array.from([1, 2, 3, 4, 5]);
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
});
it('fromHex round-trips toHex and rejects odd-length input', () => {
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
expect(fromHex(toHex(b)).equals(b)).toBe(true);
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
expect(() => fromHex('abc')).toThrow();
});
});

View File

@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest';
import { renderParamsVerbose, summarizeParams } from '../src/log-summary';
describe('summarizeParams', () => {
it('renders null/undefined as {}', () => {
expect(summarizeParams(null)).toBe('{}');
expect(summarizeParams(undefined)).toBe('{}');
});
it('renders a top-level non-object via String() WITHOUT quotes', () => {
// The reported change-request: a top-level primitive is NOT JSON-quoted.
expect(summarizeParams('hello')).toBe('hello');
expect(summarizeParams(123)).toBe('123');
});
it('collapses a top-level array to [len=N]', () => {
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
});
it('quotes string fields, collapses nested values, truncates long strings', () => {
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
.toBe('a=1 b="x" c={...} e=[len=2]');
expect(summarizeParams({ s: 'x'.repeat(50) }))
.toBe(`s="${'x'.repeat(40)}..."`);
});
it('caps total output and appends "..." on overflow', () => {
const big: Record<string, number> = {};
for (let i = 0; i < 60; i++) big['key' + i] = i;
const out = summarizeParams(big);
expect(out.startsWith('key0=0')).toBe(true);
expect(out.endsWith('...')).toBe(true);
});
});
describe('renderParamsVerbose', () => {
it('redacts token / password / secret keys at any depth', () => {
const out = renderParamsVerbose({ token: 'abc', password: 'p', nested: { secret: 's' }, ok: 'v' });
expect(out).toContain('token:"***"');
expect(out).toContain('password:"***"');
expect(out).toContain('secret:"***"');
expect(out).toContain('ok:"v"');
});
it('truncates long strings with a Unicode ellipsis + byte count (not ASCII dots)', () => {
// The reported change-request: the marker is `…<N B>` (U+2026), not `...<N B>`.
const out = renderParamsVerbose({ blob: 'a'.repeat(500) });
expect(out).toContain('…<500B>');
expect(out).not.toContain('...<500B>');
});
it('guards against circular references', () => {
const o: Record<string, unknown> = { a: 1 };
o.self = o;
expect(renderParamsVerbose(o)).toContain('"[circular]"');
});
it('renders nested structure with primitives intact', () => {
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
});
});

View File

@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest';
import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context';
describe('request-context', () => {
it('nextRequestId increments monotonically and stays a positive integer', () => {
const a = nextRequestId();
const b = nextRequestId();
expect(a).toBeGreaterThan(0);
expect(b).toBe(a + 1);
});
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
expect(currentRequestId()).toBeUndefined();
runWithRequestId(42, () => {
expect(currentRequestId()).toBe(42);
runWithRequestId(99, () => {
expect(currentRequestId()).toBe(99);
});
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
});
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
await runWithRequestId(7, async () => {
await Promise.resolve();
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
});
});
it('returns the callback result', () => {
expect(runWithRequestId(1, () => 'value')).toBe('value');
});
});

16
packages/core/config/.gitignore vendored Normal file
View File

@@ -0,0 +1,16 @@
# Per-instance runtime state written by the dev server / production daemon.
# `runtime.json` is the only tracked file (the deploy-time overrides for
# webuiPort, hookAutoLoad, etc); everything else here is operator-private:
# * webui.json — admin password hash + rotation state
# * consent.json — EULA/PRIVACY acceptance per agreement version
# * notifications.json — per-account webhook destinations
# * onebot_<uin>.json — per-uin OneBot transport binding (HTTP/WS ports etc)
# * ui.json — WebUI panel layout per operator
#
# Without this ignore file, every `pnpm dev:mode` / `node dist/index.mjs`
# leaves a 5-file untracked surface in `packages/core/config/` that pollutes
# `git status` and would accidentally commit local creds if `git add -A` is used.
*
!.gitignore
!runtime.json

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.10.0",
"version": "1.10.3",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",

View File

@@ -232,6 +232,13 @@ export class ContactsApi {
return requests;
}
/** The approval msgseq captured from a private "qun.invite" card for this
* group, or undefined if none was seen. `set_group_add_request` uses it to
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
getGroupInviteCardSequence(groupId: number): number | undefined {
return this.ctx.identity.getGroupInviteCardSequence(groupId);
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
const resp = await FetchDownloadRkeys.invoke(this.ctx);

View File

@@ -14,7 +14,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
@@ -202,6 +202,46 @@ function previewFromElements(elements: MessageElement[]): string {
return '';
}
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
return {
userUin: node.userUin,
nickname: node.nickname,
elements,
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
innerForward: node.innerForward,
};
}
function stripFileSource(element: MessageElement): MessageElement {
const next: MessageElement = { ...element };
delete next.url;
return next;
}
function isCachedFileUsableInTarget(
cached: UploadedFileMeta | undefined,
groupId?: number,
userId?: number,
): boolean {
if (!cached) return true;
if (groupId !== undefined) {
return cached.scope === 'group' && cached.groupId === groupId;
}
if (userId !== undefined) {
return cached.scope === 'private' && cached.userId === userId;
}
return true;
}
function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta): string {
return (element.fileName ?? cached?.fileName ?? '').trim();
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -210,6 +250,101 @@ export class ForwardApi {
return resId;
}
private async downloadSourceFromCachedFile(cached: UploadedFileMeta): Promise<string> {
if (cached.scope === 'group' && cached.groupId !== undefined) {
return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId);
}
if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) {
return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash);
}
throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it');
}
private async uploadForwardFileSource(
source: string,
name: string,
groupId?: number,
userId?: number,
): Promise<MessageElement> {
if (groupId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
const element: MessageElement = {
type: 'file',
fileId: uploaded.fileId,
};
const fileName = cached?.fileName || name;
if (fileName) element.fileName = fileName;
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
return element;
}
if (userId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false);
if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id');
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
const element: MessageElement = {
type: 'file',
fileId: uploaded.fileId,
};
const fileName = cached?.fileName || name;
const fileHash = uploaded.fileHash ?? cached?.fileHash ?? '';
if (fileName) element.fileName = fileName;
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
if (fileHash) element.fileHash = fileHash;
return element;
}
throw new Error('forward file source requires group_id or user_id');
}
private async prepareForwardFileElement(
element: MessageElement,
groupId?: number,
userId?: number,
): Promise<MessageElement> {
if (element.type !== 'file') return element;
const source = (element.url ?? '').trim();
if (source && !element.fileId) {
const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId);
return {
...stripFileSource(element),
...uploaded,
};
}
if (element.fileId) {
const cached = this.ctx.recallUploadedFile(element.fileId);
if (isCachedFileUsableInTarget(cached, groupId, userId)) return element;
const sourceFromCache = await this.downloadSourceFromCachedFile(cached!);
const uploaded = await this.uploadForwardFileSource(
sourceFromCache,
fileNameForUpload(element, cached),
groupId,
userId,
);
return {
...stripFileSource(element),
...uploaded,
};
}
return element;
}
private async prepareForwardFiles(
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<ForwardNodePayload[]> {
return Promise.all(nodes.map(async (node) => {
const elements = await Promise.all(node.elements.map(
element => this.prepareForwardFileElement(element, groupId, userId),
));
return cloneNodeWithElements(node, elements);
}));
}
/**
* Recursive upload with NapCat-style piggyback. Each invocation:
* 1. Walks `nodes`. For any node whose `innerForward` is set,
@@ -304,8 +439,10 @@ export class ForwardApi {
}
}
const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId);
// Encode this level's msgBody.
const msgBody = await Promise.all(processedNodes.map(
const msgBody = await Promise.all(uploadReadyNodes.map(
node => buildForwardPushBody(bridge, node, groupId, userUid),
));
@@ -349,7 +486,7 @@ export class ForwardApi {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(resId, processedNodes.map(node => ({
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],

View File

@@ -54,8 +54,26 @@ export class GroupAdminApi {
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
}
leave(groupId: number): Promise<void> {
return LeaveGroup.invoke(this.ctx, { groupId });
async leave(groupId: number): Promise<void> {
await LeaveGroup.invoke(this.ctx, { groupId });
// The server doesn't push a member-decrease back to the member who left of
// its own accord, so synthesize the self group_member_leave here — otherwise
// downstream never sees notice.group_decrease and keeps a "zombie" group in
// its cache (#133). Also drop the group from our own roster.
const selfUin = Number(this.ctx.identity.uin) || 0;
const selfUid = this.ctx.identity.selfUid ?? '';
await this.ctx.events.emit({
kind: 'group_member_leave',
time: Math.floor(Date.now() / 1000),
selfUin,
groupId,
userUin: selfUin,
operatorUin: selfUin,
userUid: selfUid,
operatorUid: selfUid,
leaveType: 'leave',
});
this.ctx.identity.forgetGroup(groupId);
}
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {

View File

@@ -241,6 +241,7 @@ export class GroupFileApi {
name = '',
folderId = '/',
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
@@ -316,11 +317,11 @@ export class GroupFileApi {
// the chat shows nothing. The publish step goes via a dedicated OIDB
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
// caller opts out via `uploadFile=false` (treat that as "I only
// wanted the slot allocated, hold the chat post"). Routes through
// `this.publish` so tests can mock at the same Api boundary.
if (uploadFile) {
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a
// caller only needs a valid file_id embedded elsewhere, e.g. a
// forward-message long-msg payload. Routes through `this.publish` so
// tests can mock at the same Api boundary.
if (publishFile) {
try {
await this.publish(groupId, fileId);
} catch (err) {
@@ -341,6 +342,7 @@ export class GroupFileApi {
source: string,
name = '',
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
@@ -482,7 +484,7 @@ export class GroupFileApi {
// which only knows about elems[]. NapCat does the same atomic
// upload+send dance — without it the file sits on the server and
// the recipient sees nothing.
if (uploadFile) {
if (publishFile) {
try {
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
fileId,

View File

@@ -3,7 +3,7 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sen
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import {
@@ -26,6 +26,8 @@ export class Bridge implements BridgeInterface {
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
private readonly sysMsgDedup_ = new SysMsgDedup();
constructor(identity: IdentityService) {
this.identity = identity;
@@ -62,7 +64,7 @@ export class Bridge implements BridgeInterface {
}
},
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_));
}
dispose(): void {

View File

@@ -4,6 +4,7 @@ import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
@@ -30,12 +31,22 @@ async function main() {
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
// WebUI state-push wiring: HookManager + BridgeManager edges publish
// `processes` / `qq-list` / `connections` invalidations into a bus the
// /api/state/stream SSE handler subscribes to (no REST polling required).
const stateWiring = createStateWiring();
const hookManager = new HookManager({
bridgeManager,
autoLoadOnDiscovery,
onSessionsChanged: stateWiring.onSessionsChanged,
});
if (autoLoadOnDiscovery) {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
oneBotManager.bind(bridgeManager);
stateWiring.bindBridgeManager(bridgeManager);
// Global notification subsystem (account up/down → webhook). Bound AFTER
// OneBotManager so the nickname fallback is already populated when it observes.
@@ -52,6 +63,7 @@ async function main() {
host: runtimeConfig.webuiHost,
tlsEnabled: runtimeConfig.webuiTls?.enabled,
trustProxy: runtimeConfig.trustProxy,
stateBus: stateWiring.bus,
});
} catch (err) {
log.error('Failed to start WebUI: ', err);
@@ -65,6 +77,7 @@ async function main() {
oneBotManager.dispose();
notificationManager.dispose();
hookManager.dispose();
stateWiring.dispose();
await closeLogger();
process.exit(0);
};

View File

@@ -7,6 +7,7 @@
//
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
@@ -92,21 +93,9 @@ export function renderTemplate(template: string, vars: Record<string, string>):
});
}
// ─── Normalization helpers (replicated from ui-config conventions) ──────────
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
function clampInt(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.trunc(Math.min(max, Math.max(min, n)));
}
// ─── Normalization helpers ──────────────────────────────────────────────────
// isObject / boolOr / clampInt come from @snowluma/common/coerce. strOr is
// notifications-only (string truncation to maxLen), so it stays here.
function strOr(value: unknown, fallback: string, maxLen: number): string {
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;

View File

@@ -0,0 +1,104 @@
/**
* Connection-status diff loop. OneBot adapters don't have an internal
* event-emitter for connection state (listening / connected / client-count
* changes), so this loop polls `getConnectionStatuses()` and publishes
* `connections` to the StateBus when the JSON-serialised snapshot changes
* vs the previous tick.
*
* Cheap (500ms default cadence, 1-3 accounts, ~hundreds of bytes), only
* fires the StateBus when state actually moves — so the SSE handler only
* pushes a fresh `connections` frame when the user would actually see
* something update.
*/
import type { StateBus } from './state-bus';
export interface ConnectionDiffLoopOptions {
bus: StateBus;
/** Read the current adapter-status snapshot for every live UIN. */
getSnapshot: () => unknown;
/** Optional projector — return the "comparable" subset of the snapshot.
* The full snapshot is what the SSE handler ships to the WebUI; this
* projection is what the diff loop compares between ticks. Use it to
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
* `detail` strings) that would otherwise produce a publish every tick
* under any active webhook — defeating the loop's whole purpose.
* Default: identity. */
pickComparable?: (snapshot: unknown) => unknown;
/** Poll cadence in milliseconds; default 500. */
intervalMs?: number;
}
export interface ConnectionDiffLoopHandle {
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
dispose(): void;
}
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
const intervalMs = opts.intervalMs ?? 500;
let lastSerialized = '';
let haveBaseline = false;
let disposed = false;
// One-shot diagnostic latch: a projector that starts throwing only after
// a shape regression would otherwise wedge the baseline silently — no
// publishes, no log, no symptom besides "the dashboard's connections
// card stops updating". Surface it ONCE so the failure is visible.
let warnedProjectorThrew = false;
const tick = (): void => {
if (disposed) return;
let snap: unknown;
try {
snap = opts.getSnapshot();
} catch {
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
// next one will retry. Don't reset the baseline so we don't
// spuriously republish when the snapshot starts working again.
return;
}
let comparable: unknown;
try {
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
} catch (err) {
// A buggy projector must not crash the diff loop or wedge baseline.
// But silent wedge is its own bug class — log the FIRST occurrence
// so an operator can find it without re-running the loop locally.
if (!warnedProjectorThrew) {
warnedProjectorThrew = true;
// Static logger import avoided to keep the loop self-contained;
// stderr is good enough for a once-per-process latch.
// eslint-disable-next-line no-console
console.error('[connection-diff-loop] pickComparable threw — connections SSE diff will wedge until restart:', err);
}
return;
}
const serialized = JSON.stringify(comparable);
if (!haveBaseline) {
// First successful observation. The SSE handler's sendAllInitial
// already shipped a `connections` frame to every connected client
// on connect, so the baseline is what they already have — emitting
// it again would be a duplicate. Just store it.
lastSerialized = serialized;
haveBaseline = true;
return;
}
if (serialized === lastSerialized) return;
lastSerialized = serialized;
opts.bus.publish('connections');
};
const timer = setInterval(tick, intervalMs);
// Don't pin the Node event loop: the loop is permanent for the server
// lifetime by design, but tests / a future hot-reload scenario must be
// able to exit cleanly without an outstanding interval ref. Mirrors the
// tokenJanitor pattern in server.ts.
timer.unref?.();
return {
dispose(): void {
if (disposed) return;
disposed = true;
clearInterval(timer);
},
};
}

View File

@@ -21,6 +21,9 @@ import { coerceSettingsPatch } from './system-settings';
import { buildBackup, planRestore, validateBackup } from './backup';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { findAvailablePort } from './port';
import {
@@ -80,14 +83,20 @@ const CONSENT_ALLOWLIST = new Set([
'/api/logout',
]);
// Endpoints that may authenticate via `?token=` query parameter. Only the
// SSE log stream is here because EventSource cannot set custom headers; all
// other endpoints MUST use the Authorization header so tokens never leak
// into access logs / Referer / browser history.
const TOKEN_QUERY_ALLOWLIST = new Set([
// Endpoints that may authenticate via `?token=` query parameter. Reserved
// for SSE streams: EventSource cannot set custom headers, so these MUST
// accept the token via query. All other endpoints use the Authorization
// header so tokens never leak into access logs / Referer / browser history.
//
// Exported so the regression test can lock the invariant — a missing entry
// here silently 401s the EventSource and the whole push channel goes dark,
// which has happened (see /api/state/stream's first cut).
export const SSE_TOKEN_QUERY_PATHS: ReadonlySet<string> = new Set([
'/api/logs/stream',
'/api/debug/stream',
'/api/state/stream',
]);
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
// uin = QQ number; 5–12 digits. Used to construct config file paths,
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
@@ -313,7 +322,7 @@ export async function initWebUI(
oneBotManager: OneBotManager,
hookManager?: HookManager,
notificationManager?: NotificationManager,
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {},
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
): Promise<{ port: number }> {
// Resolve the client IP for per-IP rate limiting from the configured
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
@@ -322,6 +331,54 @@ export async function initWebUI(
const trustProxyMode = parseTrustProxy(listener.trustProxy);
const getClientIp = makeClientIpResolver(trustProxyMode);
// Connection-status diff loop: OneBot adapters don't emit events for
// listening/connected/client-count changes, so we poll the snapshot at
// 500ms and publish 'connections' to the StateBus when it actually
// moves. One loop per server lifetime, lives until process exit (the
// setInterval is .unref'd inside the loop so it doesn't pin the event
// loop on shutdown).
//
// `pickComparable` strips `adapter.detail` — that's a localised human
// string assembled with HH:MM:SS timestamps from the last webhook
// delivery; including it in the diff would make every webhook event
// produce a publish (defeating the diff). We compare ONLY name + kind +
// status, which captures every transition the dashboard actually
// renders differently. The SSE handler still ships the FULL snapshot
// (with `detail`) — it's only the diff key that's pruned.
//
// Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送
// 14:53:01") only refreshes on the next SSE push or on the 30s REST
// reconcile — not in real time. The user's original reported bugs were
// about process / account edges (which DO push instantly); refreshing
// adapter detail strings at sub-second cadence wasn't required. If it
// becomes one, surface client-count as a structured field on
// AdapterStatus and include it in the comparable.
if (listener.stateBus) {
// Handle deliberately discarded — initWebUI has no shutdown path; the
// loop's setInterval is .unref'd so it doesn't pin the event loop.
startConnectionDiffLoop({
bus: listener.stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: (snap) => {
if (!Array.isArray(snap)) return snap;
return (snap as Array<{ uin: string; nickname?: string; adapters?: unknown[] }>).map((acc) => ({
uin: acc.uin,
nickname: acc.nickname,
// Empty fallback when `adapters` is not an array — never the
// raw value, which could re-introduce volatile fields verbatim
// if the snapshot shape ever drifts.
adapters: Array.isArray(acc.adapters)
? acc.adapters.map((a: unknown) => {
const o = a as { name?: string; kind?: string; status?: string };
return { name: o.name, kind: o.kind, status: o.status };
})
: [],
}));
},
intervalMs: 500,
});
}
// Actual bound port (set just before serve; findAvailablePort may bump it).
// Read by GET /api/system/settings so the panel shows what's really live.
let boundPort = desiredPort;
@@ -926,6 +983,77 @@ export async function initWebUI(
return c.json({ list: oneBotManager.getConnectionStatuses() });
});
// Combined SSE feed for the dashboard's three live resources — processes,
// qq-list, connections. Replaces the 3s REST polling tick in
// app-layout.tsx; the REST endpoints above stay for the initial fetch
// before SSE connects and for the slow (30s) reconciliation fallback.
//
// On connect: one frame per resource with the current snapshot. After
// that: a fresh snapshot per resource only when the StateBus signals a
// change (HookSession status-changed, BridgeManager session edges, the
// connection-status diff loop). 50ms per-resource debounce coalesces a
// burst (e.g. multiple HookSessions flipping status simultaneously).
const stateBus = listener.stateBus;
app.get('/api/state/stream', (c) => {
if (!stateBus) {
// Build without state-wiring (e.g. a future headless mode) — clients
// fall back to the REST endpoints. Treat as endpoint-not-here.
return c.text('state stream not configured', 503);
}
const liveBus = stateBus;
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let binding: { dispose(): void } | undefined;
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
binding?.dispose();
try { controller.close(); } catch { /* ignore */ }
};
const raw = (chunk: Uint8Array) => {
if (closed) return;
try { controller.enqueue(chunk); } catch { teardown(); }
};
const pushFrame = createFramePusher({
desiredSize: () => controller.desiredSize,
enqueue: raw,
encode: (s) => encoder.encode(s),
});
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
send({ kind: 'ready' });
const handle = bindStateStream({
bus: liveBus,
snapshot: async (resource: StateResource): Promise<unknown> => {
if (resource === 'processes') {
if (!hookManager) return [];
return hookManager.listProcesses();
}
if (resource === 'qq-list') {
return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
}
return oneBotManager.getConnectionStatuses();
},
send: (frame) => send(frame),
debounceMs: 50,
});
binding = handle;
// Prime with the initial snapshot; if the client never sees the
// bus publish (idle system) it still has the current state.
void handle.sendAllInitial();
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
});
app.get('/api/logs', (c) => {
const limit = Number(c.req.query('limit') ?? 300);
return c.json({ list: getRecentLogs(limit) });

View File

@@ -0,0 +1,67 @@
/**
* StateBus — pure pub/sub for WebUI state-resource invalidations.
*
* Three resources are tracked: `processes`, `qq-list`, `connections`. A
* publisher (HookSession status change, BridgeManager session start/close,
* the connection-status diff loop) calls `publish(resource)` to signal "the
* snapshot for THIS resource is stale; whoever cares should re-read". The
* `/api/state/stream` SSE handler subscribes, debounces, and pushes fresh
* snapshots to connected WebUI clients.
*
* Intentionally pure pub/sub (no debounce, no snapshot caching): debounce
* and snapshot reads live with the subscriber so different consumers can
* coalesce on different cadences. Snapshot semantics on fan-out: the
* subscriber set is FROZEN at the start of each publish, so a listener
* that subscribes during the fan-out only sees the FOLLOWING publish, and
* a listener that unsubscribes mid-fan-out does not prevent its peers
* from completing.
*/
export type StateResource = 'processes' | 'qq-list' | 'connections';
export type StateListener = (resource: StateResource) => void;
export class StateBus {
private readonly listeners = new Set<StateListener>();
private disposed = false;
/** Subscribe to every publish; returns an unsubscribe handle. Calling
* the handle more than once is a no-op. */
subscribe(listener: StateListener): () => void {
if (this.disposed) return () => undefined;
this.listeners.add(listener);
let active = true;
return () => {
if (!active) return;
active = false;
this.listeners.delete(listener);
};
}
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
* Iterates a frozen snapshot of the subscriber set so add/remove during
* the emit don't change which listeners see THIS publish; subscriber
* exceptions are isolated and do not abort the fan-out. */
publish(resource: StateResource): void {
if (this.disposed) return;
// Snapshot the current subscribers — any subscribe()/unsubscribe()
// called by a listener during the fan-out takes effect only for the
// NEXT publish, not this one.
const snapshot = [...this.listeners];
for (const fn of snapshot) {
try {
fn(resource);
} catch {
// Subscriber-internal failure is its own problem. The bus's job
// is to keep delivery moving — surfacing an error here would
// partially abort the fan-out and create skip-the-listener bugs.
}
}
}
/** Drop every subscriber and refuse future subscribes / publishes. */
dispose(): void {
this.disposed = true;
this.listeners.clear();
}
}

View File

@@ -0,0 +1,128 @@
/**
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
* connection with one frame per resource.
*
* Decoupled from the HTTP layer so the route handler in server.ts can drop
* its responsibility down to "open a ReadableStream, hand its enqueue to
* bindStateStream, abort tears it down". Pure logic = unit-testable with
* fake timers; no Response/controller mocking needed.
*
* Per-resource debounce, not global: an 'qq-list' churn during a slow
* 'processes' burst must not delay the qq-list frame, and a 'connections'
* diff loop running at 500ms must not coalesce 10 unrelated processes
* events into one. Each resource is its own timer.
*/
import type { StateBus, StateResource } from './state-bus';
export interface StateStreamFrame {
resource: StateResource;
data: unknown;
}
export interface BindStateStreamOptions {
bus: StateBus;
/** Read the current snapshot for one resource. May be sync or async. */
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
/** Receive a fresh frame; called once per debounced publish.
* Exceptions are caught — a dead controller must not abort the bus
* subscription or break sibling resources. */
send: (frame: StateStreamFrame) => void;
/** Coalesce window in milliseconds; default 50. */
debounceMs?: number;
}
export interface StateStreamHandle {
/** Emit one frame per resource using the current snapshot. Use on connect. */
sendAllInitial(): Promise<void>;
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
* produce nothing through this binding. */
dispose(): void;
}
const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections'];
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false;
const flush = async (resource: StateResource): Promise<void> => {
if (disposed) return;
inFlight.add(resource);
try {
let data: unknown;
try {
data = await opts.snapshot(resource);
} catch {
// Per-resource snapshot failure (e.g. listProcesses threw): skip
// this frame so siblings keep flowing. The next publish for the
// same resource gets a fresh attempt.
return;
}
if (disposed) return;
try {
opts.send({ resource, data });
} catch {
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
}
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one
// follow-up flush. Re-uses the debounce so a sustained publish
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
}
};
const schedule = (resource: StateResource): void => {
if (disposed) return;
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
return;
}
const existing = timers.get(resource);
if (existing) clearTimeout(existing);
const t = setTimeout(() => {
timers.delete(resource);
void flush(resource);
}, debounceMs);
timers.set(resource, t);
};
const unsubscribe = opts.bus.subscribe(schedule);
return {
async sendAllInitial(): Promise<void> {
if (disposed) return;
// Fire all three in parallel. Each resource's snapshot is independent
// so a slow listProcesses() doesn't gate qq-list/connections. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
},
dispose(): void {
if (disposed) return;
disposed = true;
unsubscribe();
for (const t of timers.values()) clearTimeout(t);
timers.clear();
pending.clear();
},
};
}

View File

@@ -0,0 +1,73 @@
/**
* State-wiring — couples the publisher edges (HookManager session events,
* BridgeManager session-started / session-closed) to a fresh StateBus so the
* `/api/state/stream` SSE handler can push snapshot invalidations to the
* WebUI without REST polling.
*
* Decoupling rationale:
* - HookManager owns the per-process state-machine; it knows when a
* session's `listProcesses()` view changes. We feed it `onSessionsChanged`
* (callable from outside the bridge package) so this file is the ONLY
* place that imports both the bus and HookManager's dep shape.
* - BridgeManager fires `session-started` / `session-closed` listeners on
* account edges (the OneBot instance list mutates around these). We add
* listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager.
*
* `dispose()` unwires everything so a test (or a future hot-reload) can
* recreate the wiring without leaking listeners.
*/
import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager';
export interface StateWiring {
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
* 'connections'. Can be called at most once per wiring (subsequent calls
* add duplicate listeners). */
bindBridgeManager(bm: BridgeManager): void;
/** Drop every listener + neuter the bus so further publishes do nothing. */
dispose(): void;
}
export function createStateWiring(): StateWiring {
const bus = new StateBus();
let disposed = false;
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
if (disposed) return;
bus.publish(resource);
};
return {
bus,
onSessionsChanged: () => publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
// Account appeared: the qq-list response gains an entry and the
// connections response gains the new account's adapter row. Two
// distinct resource invalidations, in source-of-truth order
// (account exists → only then can adapters be enumerated for it).
bm.addSessionStartedListener(() => {
publish('qq-list');
publish('connections');
});
// Account disappeared: same two resources shrink, same order so a
// racy WebUI receiving both events independently sees the qq-list
// shrink before it tries to render connections for a uin that's
// about to vanish.
bm.addSessionClosedListener(() => {
publish('qq-list');
publish('connections');
});
},
dispose(): void {
if (disposed) return;
disposed = true;
bus.dispose();
},
};
}

View File

@@ -1,3 +1,4 @@
import { boolOr, clampInt, clampNum, isObject } from '@snowluma/common/coerce';
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
@@ -308,10 +309,8 @@ function defaultPages(): UiPages {
}
// ─── Normalization helpers ─────────────────────────────────────────────────
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
// isObject / boolOr / clampNum / clampInt come from @snowluma/common/coerce.
// oneOf (enum), isFiniteNum, and hexOr (CSS color) are ui-specific and stay.
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
@@ -319,25 +318,11 @@ function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback
: 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;

View File

@@ -124,7 +124,9 @@ export interface MockBridge {
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
forgetGroup: ReturnType<typeof vi.fn>;
};
events: { emit: ReturnType<typeof vi.fn> };
apis: MockApiHub;
sendRawPacket: ReturnType<typeof vi.fn>;
fetchFriendList: ReturnType<typeof vi.fn>;
@@ -154,8 +156,10 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
forgetGroup: vi.fn(),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
events: overrides.events ?? { emit: vi.fn(async () => undefined) },
apis: overrides.apis ?? mockApiHub(),
sendRawPacket: vi.fn(async () => defaultResp),
fetchFriendList: vi.fn(async () => []),

View File

@@ -24,6 +24,7 @@
// split.
import { describe, it, expect, vi } from 'vitest';
import { gunzipSync } from 'zlib';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
@@ -44,8 +45,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: buildSendElemsMock,
}));
import { protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
@@ -60,6 +62,13 @@ function uploadResponseWithResId(resId: string) {
};
}
function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
const env = protobuf_decode<SendLongMsgReq>(rawBytes);
const payload = env.info?.payload;
if (!(payload instanceof Uint8Array)) throw new Error('payload missing on SendLongMsgReq');
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
}
describe('actions/forward — file segment inside forward node', () => {
it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => {
// Group case: the file element rides on elems[] as transElem(24).
@@ -120,18 +129,19 @@ describe('actions/forward — file segment inside forward node', () => {
expect(ctx).toMatchObject({ forwardFake: true });
expect(ctx?.groupId).toBeUndefined();
// Spot-check that the upload body carries the file metadata. The
// payload is gzipped + protobuf-wrapped, so we just verify the
// raw filename string survived — that's enough to confirm the
// FileExtra branch ran (a "missing file" regression would drop
// these bytes entirely).
expect(captured).toBeDefined();
const flat = Buffer.from(captured!).toString('binary');
// The filename gets gzipped, so we can't substring-search; instead
// assert the body is large enough that the FileExtra wasn't elided.
// (A name-only forward with no msgContent runs ~80-100 bytes; with
// the FileExtra blob it's noticeably larger.)
expect(flat.length).toBeGreaterThan(80);
const longMsg = decodeLongMsgRequest(captured!);
const body = longMsg.action?.[0]?.actionData?.msgBody?.[0]?.body;
expect(body?.msgContent).toBeInstanceOf(Uint8Array);
expect(body?.richText?.notOnlineFile ?? undefined).toBeUndefined();
const fileExtra = protobuf_decode<FileExtra>(body!.msgContent as Uint8Array);
expect(fileExtra.file).toMatchObject({
fileUuid: 'pfid-1',
fileName: 'invoice.pdf',
fileHash: 'srv-hash-abc',
});
expect(fileExtra.file?.fileSize).toBe(4096n);
});
it('c2c forward falls back to the upload metadata cache when inline fields are missing', async () => {
@@ -165,4 +175,190 @@ describe('actions/forward — file segment inside forward node', () => {
expect(recallUploadedFile).toHaveBeenCalledWith('pfid-cached');
});
it('group forward pre-uploads file sources into the target group without publishing a separate file message', async () => {
buildSendElemsMock.mockClear();
const upload = vi.fn(async () => ({ fileId: 'gfid-from-base64' }));
const publish = vi.fn();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-source')) as any,
apis: {
...mockBridge().apis,
groupFile: {
...mockBridge().apis.groupFile,
upload,
publish,
},
},
recallUploadedFile: vi.fn((id: string) => id === 'gfid-from-base64' ? {
fileId: 'gfid-from-base64',
scope: 'group' as const,
groupId: 12345,
fileName: 'note.txt',
fileSize: 3,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
rememberedAt: 0,
} : undefined),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any],
}], 12345);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
expect(publish).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([expect.objectContaining({
type: 'file',
fileId: 'gfid-from-base64',
fileName: 'note.txt',
fileSize: 3,
})]);
});
it('private forward pre-uploads file sources without sending a standalone c2c file message', async () => {
buildSendElemsMock.mockClear();
const uploadPrivate = vi.fn(async () => ({ fileId: 'pfid-from-base64', fileHash: 'phash' }));
const sendC2cFile = vi.fn();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-c2c-source')) as any,
apis: {
...mockBridge().apis,
message: {
...mockBridge().apis.message,
sendC2cFile,
},
groupFile: {
...mockBridge().apis.groupFile,
uploadPrivate,
},
},
recallUploadedFile: vi.fn((id: string) => id === 'pfid-from-base64' ? {
fileId: 'pfid-from-base64',
scope: 'private' as const,
userId: 67890,
fileName: 'note.txt',
fileSize: 3,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'phash',
rememberedAt: 0,
} : undefined),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any],
}], undefined, 67890);
expect(uploadPrivate).toHaveBeenCalledWith(67890, 'base64://AQID', 'note.txt', true, false);
expect(sendC2cFile).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([expect.objectContaining({
type: 'file',
fileId: 'pfid-from-base64',
fileName: 'note.txt',
fileSize: 3,
fileHash: 'phash',
})]);
});
it('private file forward keeps the long-msg upload under the self uid namespace', async () => {
buildSendElemsMock.mockClear();
let captured: Uint8Array | undefined;
const bridge = mockBridge({
sendRawPacket: vi.fn(async (_cmd: string, body: Uint8Array) => {
captured = body;
return uploadResponseWithResId('res-c2c-target-uid');
}) as any,
resolveUserUid: vi.fn(async () => 'target-uid'),
recallUploadedFile: vi.fn((id: string) => id === 'pfid-1' ? {
fileId: 'pfid-1',
scope: 'private' as const,
userId: 67890,
fileName: 'invoice.pdf',
fileSize: 4096,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'srv-hash',
rememberedAt: 0,
} : undefined),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'pfid-1' } as any],
}], undefined, 67890);
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
expect(captured).toBeDefined();
const request = protobuf_decode<SendLongMsgReq>(captured!);
expect(request.info?.uid?.uid).toBe('self-uid');
});
it('group forward re-uploads a cached private file_id into the target group scope', async () => {
buildSendElemsMock.mockClear();
const getPrivateUrl = vi.fn(async () => 'https://download.test/private-file');
const upload = vi.fn(async () => ({ fileId: 'gfid-reuploaded' }));
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-cross-scope')) as any,
apis: {
...mockBridge().apis,
groupFile: {
...mockBridge().apis.groupFile,
getPrivateUrl,
upload,
},
},
recallUploadedFile: vi.fn((id: string) => {
if (id === 'pfid-cached') {
return {
fileId: 'pfid-cached',
scope: 'private' as const,
userId: 67890,
fileName: 'cached.txt',
fileSize: 5,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'cached-hash',
rememberedAt: 0,
};
}
if (id === 'gfid-reuploaded') {
return {
fileId: 'gfid-reuploaded',
scope: 'group' as const,
groupId: 12345,
fileName: 'cached.txt',
fileSize: 5,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
rememberedAt: 1,
};
}
return undefined;
}),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'pfid-cached' } as any],
}], 12345);
expect(getPrivateUrl).toHaveBeenCalledWith(67890, 'pfid-cached', 'cached-hash');
expect(upload).toHaveBeenCalledWith(12345, 'https://download.test/private-file', 'cached.txt', '/', true, false);
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([expect.objectContaining({
type: 'file',
fileId: 'gfid-reuploaded',
fileName: 'cached.txt',
fileSize: 5,
})]);
});
});

View File

@@ -88,13 +88,24 @@ describe('apis/group-admin', () => {
expect(env.body?.rejectAddRequest ?? 0).toBe(0);
});
it('leave sends 0x1097_1 with the groupUin', async () => {
it('leave sends 0x1097_1, emits a self group_member_leave, and forgets the group (#133)', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).leave(12345);
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
const env = protobuf_decode<OidbBase<OidbLeaveGroup>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345 });
// The server never pushes a member-decrease for our own voluntary leave, so
// the bridge synthesizes it (self user_id/operator_id) and drops the group.
expect(bridge.events.emit).toHaveBeenCalledWith(expect.objectContaining({
kind: 'group_member_leave',
groupId: 12345,
userUin: 10001,
operatorUin: 10001,
leaveType: 'leave',
}));
expect(bridge.identity.forgetGroup).toHaveBeenCalledWith(12345);
});
it('setAdmin resolves UID and sends 0x1096_1', async () => {

View File

@@ -170,6 +170,28 @@ describe('apis/group-file', () => {
expect(publishSpy).not.toHaveBeenCalled();
});
it('upload can PUT bytes without publishing a separate group file message', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-forward',
uploadIp: '127.0.0.1',
uploadPort: 443,
fileKey: new Uint8Array([1]),
checkKey: new Uint8Array([2]),
} as any,
},
}),
));
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, 'base64://AQID', 'forward.txt', '/', true, false);
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(publishSpy).not.toHaveBeenCalled();
});
it('upload returns success even when the chat post fails (file is still uploaded)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
@@ -233,6 +255,7 @@ describe('apis/group-file', () => {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
forgetGroup: vi.fn(),
},
});
vi.mocked(bridge.resolveUserUid)
@@ -297,6 +320,28 @@ describe('apis/group-file', () => {
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
});
it('uploadPrivate can PUT bytes without publishing a separate c2c file message', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid-forward',
fileAddon: 'phash-forward',
rtpMediaPlatformUploadAddress: [
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
],
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
} as any,
},
}),
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, 'base64://AQID', 'forward.txt', true, false);
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
});
it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');

View File

@@ -283,6 +283,113 @@ describe('pipeline — runNtv2Upload', () => {
}))).rejects.toThrow(/image fast-upload not available/);
});
// ─────────── forceFullOnFastPath (video stale-resource fallback, #145) ───────────
// Bridge whose sendRawPacket returns a different OIDB response per call,
// so we can model "round 1 fast-paths the main file, round 2 demands the
// bytes after we disable fast-upload".
function makeSequencedBridge(responses: Buffer[]) {
let call = 0;
const sendRawPacket = vi.fn<(cmd: string, body: Uint8Array) => Promise<SendPacketResult>>(
async () => {
const responseData = responses[Math.min(call, responses.length - 1)]!;
call += 1;
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
},
);
return { sendRawPacket };
}
it('forceFullOnFastPath: re-requests with fast-upload disabled when the flagged main file is fast-pathed', async () => {
const bridge = makeSequencedBridge([
// Round 1: server fast-paths the main file (no uKey) but demands nothing.
encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } /* no uKey */ } }),
// Round 2 (fast-upload disabled): server now hands back a uKey.
encodeOidbResponse({
upload: {
uKey: 'fresh-ukey',
ipv4s: [{ ipv4: '1.2.3.4', port: 80 }],
msgInfo: { msgInfoBody: [], extBizInfo: {} },
},
}),
]);
const upload = await runNtv2Upload(baseParams({
bridge,
label: 'video',
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
forceFullOnFastPath: true,
}],
}));
// Two OIDB requests went out; the second omits tryFastUploadCompleted
// (proton drops `false`), which the server reads as "no fast-upload".
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
const firstReq: any = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[0]![1] as Uint8Array);
const secondReq: any = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[1]![1] as Uint8Array);
expect(firstReq.body.upload.tryFastUploadCompleted).toBe(true);
expect(secondReq.body.upload.tryFastUploadCompleted ?? false).toBe(false);
// The forced full upload PUT ran, and the returned upload is round 2's.
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(upload.uKey).toBe('fresh-ukey');
});
it('forceFullOnFastPath: no retry when the flagged file gets a uKey on the first try', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: { uKey: 'ukey-1', msgInfo: { msgInfoBody: [], extBizInfo: {} } },
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top', cmdId: 1003, bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true,
}],
}));
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('forceFullOnFastPath: no retry for a fast-pathed forward (no bytes to upload)', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top', cmdId: 1003, bytes: new Uint8Array(0),
md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true,
}],
}));
// bytes.length === 0 → nothing to distrust; the fast-path stands.
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).not.toHaveBeenCalled();
});
it('a fast-pathed sub-file WITHOUT the flag (e.g. thumb) does not trigger a retry', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
// Main fully uploaded (has uKey); thumb fast-pathed (no subFileInfos).
upload: { uKey: 'main-ukey', msgInfo: { msgInfoBody: [], extBizInfo: {} } },
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [
{ source: 'top', cmdId: 1001, bytes: new Uint8Array([1]), md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true },
{ source: 0, cmdId: 1002, bytes: new Uint8Array([2]), md5: new Uint8Array(16), sha1: new Uint8Array(20) /* no flag */ },
],
}));
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
});
it('silently skips a sub-file with empty bytes when no fastOnlyError is configured', async () => {
// This mirrors the video-thumb path where bytes are always synthesised
// (FALLBACK_THUMB) so we don't expect the check to fire even if the

View File

@@ -80,6 +80,16 @@ describe('video-upload', () => {
expect(uploads[1]!.fastOnlyError).toBeUndefined();
});
it('main file distrusts a server fast-path (forceFullOnFastPath); thumb does not (#145)', async () => {
// Group/c2c video resources expire server-side: a fast-path hit can
// reference a stale object the receiver shows as "资源已过期", so the
// main file forces a fresh full upload. The thumb stays fast-path-OK.
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
expect(uploads[0]!.forceFullOnFastPath).toBe(true);
expect(uploads[1]!.forceFullOnFastPath).toBeUndefined();
});
it('uploadInfo carries TWO entries (main mp4 + thumb jpg) with subFileType 0 and 100', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploadInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;

View File

@@ -0,0 +1,168 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { StateBus } from '../src/webui/state-bus';
import { startConnectionDiffLoop } from '../src/webui/connection-diff-loop';
describe('startConnectionDiffLoop', () => {
beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it('does NOT publish when the snapshot is stable tick after tick', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => [{ uin: '12345', nickname: 'me', adapters: [] }],
intervalMs: 500,
});
vi.advanceTimersByTime(2_000); // 4 ticks
expect(seen).toEqual([]);
handle.dispose();
});
it('first tick baselines the snapshot (no publish); only the second tick with a different value publishes', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
let snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'listening' }] }];
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => snap,
intervalMs: 500,
});
vi.advanceTimersByTime(500); // first observation — baseline, no publish
expect(seen).toEqual([]);
snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'connected' }] }];
vi.advanceTimersByTime(500);
expect(seen).toEqual(['connections']);
// Next tick: stable again → no extra publish.
vi.advanceTimersByTime(500);
expect(seen).toEqual(['connections']);
handle.dispose();
});
it('publishes once per CHANGE, not once per tick the snapshot differs from initial', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
const versions = [
[{ uin: '1', nickname: 'a', adapters: [] }], // baseline (no publish on first observation)
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }],
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }],
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'connected' }] }],
];
let i = 0;
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => versions[Math.min(i, versions.length - 1)] ?? [],
intervalMs: 500,
});
vi.advanceTimersByTime(500); // i=0 baseline
i = 1; vi.advanceTimersByTime(500); // change #1
i = 2; vi.advanceTimersByTime(500); // stable vs i=1
i = 3; vi.advanceTimersByTime(500); // change #2
expect(seen).toEqual(['connections', 'connections']);
handle.dispose();
});
it('dispose() stops further ticks, no publish even after a change', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
let snap: object[] = [];
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => snap,
intervalMs: 500,
});
handle.dispose();
snap = [{ uin: '1', nickname: 'a', adapters: [] }];
vi.advanceTimersByTime(5_000);
expect(seen).toEqual([]);
});
it('pickComparable() strips volatile fields so detail-only changes do NOT publish', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
// Reproduces the real-world bug: HttpPostAdapter.describeStatus()
// embeds HH:MM:SS in `detail`; every webhook delivery rotates that
// string every second. WITHOUT pickComparable, the loop would publish
// every tick under any active webhook. WITH it (stripping `detail`),
// only level changes publish.
let snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'ok', detail: '上次推送 14:00:00' }] }];
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => snap,
pickComparable: (s) => {
if (!Array.isArray(s)) return s;
return (s as Array<{ uin: string; adapters?: unknown[] }>).map((acc) => ({
uin: acc.uin,
adapters: Array.isArray(acc.adapters)
? acc.adapters.map((a: unknown) => {
const o = a as { name?: string; kind?: string; status?: string };
return { name: o.name, kind: o.kind, status: o.status };
})
: acc.adapters,
}));
},
intervalMs: 500,
});
vi.advanceTimersByTime(500); // baseline
expect(seen).toEqual([]);
// detail changes every second; raw JSON differs each tick.
for (let t = 1; t <= 10; t++) {
snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'ok', detail: `上次推送 14:00:${String(t).padStart(2, '0')}` }] }];
vi.advanceTimersByTime(500);
}
expect(seen).toEqual([]); // ZERO publishes — detail is not comparable
// Now a REAL state change (status level) → publish exactly once.
snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'down', detail: '连接失败' }] }];
vi.advanceTimersByTime(500);
expect(seen).toEqual(['connections']);
handle.dispose();
});
it('a throwing pickComparable() is isolated — loop keeps ticking, no publish', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => [{ uin: '1' }],
pickComparable: () => { throw new Error('projector boom'); },
intervalMs: 500,
});
vi.advanceTimersByTime(2_000);
expect(seen).toEqual([]);
handle.dispose();
});
it('survives a throwing snapshot() — keeps trying on the next tick', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
let mode: 'throw' | 'stable' | 'changed' = 'throw';
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => {
if (mode === 'throw') throw new Error('getConnectionStatuses failed');
if (mode === 'stable') return [{ uin: '1', adapters: [] }];
return [{ uin: '1', adapters: [{ kind: 'ws', status: 'connected' }] }];
},
intervalMs: 500,
});
vi.advanceTimersByTime(500); // throws — skipped, no publish
expect(seen).toEqual([]);
mode = 'stable';
vi.advanceTimersByTime(500); // first SUCCESSFUL read — baseline, no publish
expect(seen).toEqual([]);
mode = 'changed';
vi.advanceTimersByTime(500); // real change → publish
expect(seen).toEqual(['connections']);
handle.dispose();
});
});

View File

@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest';
import { SSE_TOKEN_QUERY_PATHS } from '../src/webui/server';
// Regression lock for a class of bug that has bricked an SSE endpoint
// before: EventSource cannot set Authorization headers, so every SSE
// path MUST appear in this allowlist or the auth middleware computes
// `queryToken = ''` and 401s every connect. A missing entry is silent —
// the only symptom is "live updates don't work, refresh fixes it" — so
// keep this list short and verified.
describe('SSE_TOKEN_QUERY_PATHS', () => {
it('contains every SSE stream the WebUI subscribes to', () => {
expect(SSE_TOKEN_QUERY_PATHS.has('/api/logs/stream')).toBe(true);
expect(SSE_TOKEN_QUERY_PATHS.has('/api/debug/stream')).toBe(true);
expect(SSE_TOKEN_QUERY_PATHS.has('/api/state/stream')).toBe(true);
});
it('does NOT carry any non-stream endpoint — token-via-query is reserved for SSE', () => {
// The auth middleware accepts `?token=...` for these paths only; any
// bearer-only endpoint listed here would leak tokens via access logs.
for (const path of SSE_TOKEN_QUERY_PATHS) {
expect(path.endsWith('/stream')).toBe(true);
}
});
});

View File

@@ -0,0 +1,119 @@
import { describe, expect, it, vi } from 'vitest';
import { StateBus, type StateResource } from '../src/webui/state-bus';
describe('StateBus', () => {
it('delivers a publish to a single subscriber with the resource kind', () => {
const bus = new StateBus();
const seen: StateResource[] = [];
bus.subscribe((r) => seen.push(r));
bus.publish('processes');
bus.publish('qq-list');
bus.publish('connections');
expect(seen).toEqual(['processes', 'qq-list', 'connections']);
});
it('fans out one publish to every subscriber', () => {
const bus = new StateBus();
const a = vi.fn();
const b = vi.fn();
const c = vi.fn();
bus.subscribe(a);
bus.subscribe(b);
bus.subscribe(c);
bus.publish('processes');
expect(a).toHaveBeenCalledExactlyOnceWith('processes');
expect(b).toHaveBeenCalledExactlyOnceWith('processes');
expect(c).toHaveBeenCalledExactlyOnceWith('processes');
});
it('returns an unsubscribe handle that stops future emits without touching the others', () => {
const bus = new StateBus();
const a = vi.fn();
const b = vi.fn();
const unsubA = bus.subscribe(a);
bus.subscribe(b);
bus.publish('processes');
unsubA();
bus.publish('qq-list');
expect(a).toHaveBeenCalledExactlyOnceWith('processes');
expect(b).toHaveBeenCalledTimes(2);
expect(b.mock.calls).toEqual([['processes'], ['qq-list']]);
});
it('is idempotent on double-unsubscribe', () => {
const bus = new StateBus();
const a = vi.fn();
const unsubA = bus.subscribe(a);
unsubA();
unsubA();
bus.publish('processes');
expect(a).not.toHaveBeenCalled();
});
it('isolates subscriber exceptions — one throwing listener does not block the others or future publishes', () => {
const bus = new StateBus();
const before = vi.fn();
const thrower = vi.fn(() => { throw new Error('boom'); });
const after = vi.fn();
bus.subscribe(before);
bus.subscribe(thrower);
bus.subscribe(after);
expect(() => bus.publish('processes')).not.toThrow();
expect(before).toHaveBeenCalledExactlyOnceWith('processes');
expect(after).toHaveBeenCalledExactlyOnceWith('processes');
bus.publish('qq-list');
expect(before).toHaveBeenCalledTimes(2);
expect(after).toHaveBeenCalledTimes(2);
});
it('dispose() drops every subscriber and silently swallows further publishes', () => {
const bus = new StateBus();
const a = vi.fn();
bus.subscribe(a);
bus.dispose();
bus.publish('processes');
expect(a).not.toHaveBeenCalled();
});
it('a subscriber that subscribes a second time inside its own callback observes the FOLLOWING publish, not this one', () => {
const bus = new StateBus();
const second = vi.fn();
const first = vi.fn(() => { bus.subscribe(second); });
bus.subscribe(first);
bus.publish('processes');
expect(first).toHaveBeenCalledExactlyOnceWith('processes');
// The just-added subscriber must not receive the in-flight publish — that
// would surprise SSE handlers that subscribe lazily during an emit fan-out.
expect(second).not.toHaveBeenCalled();
bus.publish('qq-list');
expect(second).toHaveBeenCalledExactlyOnceWith('qq-list');
});
it('a subscriber that unsubscribes a peer mid-emit lets the survivor still receive THIS publish', () => {
const bus = new StateBus();
const order: string[] = [];
let unsubB!: () => void;
bus.subscribe(() => { order.push('a'); unsubB(); });
unsubB = bus.subscribe(() => { order.push('b'); });
bus.subscribe(() => { order.push('c'); });
bus.publish('processes');
// Snapshot semantics: the fan-out iterates a copy, so peer-unsubscribe
// does not skip any other listener that was attached when publish started.
expect(order).toEqual(['a', 'b', 'c']);
order.length = 0;
bus.publish('qq-list');
expect(order).toEqual(['a', 'c']);
});
});

View File

@@ -0,0 +1,249 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { StateBus, type StateResource } from '../src/webui/state-bus';
import { bindStateStream } from '../src/webui/state-stream';
interface CapturedFrame {
resource: StateResource;
data: unknown;
}
function makeSnapshotFn(table: Partial<Record<StateResource, unknown>>) {
return vi.fn(async (resource: StateResource): Promise<unknown> => table[resource]);
}
describe('bindStateStream', () => {
beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it('sendAllInitial emits one frame per resource with the snapshot data', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({
'processes': [{ pid: 4242, name: 'qq', status: 'available' }],
'qq-list': [{ uin: '12345', nickname: 'me' }],
'connections': [{ uin: '12345', nickname: 'me', adapters: [] }],
});
const handle = bindStateStream({
bus,
snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
await handle.sendAllInitial();
expect(snapshot).toHaveBeenCalledTimes(3);
expect(new Set(sent.map((f) => f.resource))).toEqual(new Set(['processes', 'qq-list', 'connections']));
const procFrame = sent.find((f) => f.resource === 'processes');
expect(procFrame?.data).toEqual([{ pid: 4242, name: 'qq', status: 'available' }]);
handle.dispose();
});
it('a single bus publish reaches send() exactly once after debounceMs', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({ 'processes': [{ pid: 9999 }] });
const handle = bindStateStream({
bus,
snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
expect(sent).toHaveLength(0); // still debounced
await vi.advanceTimersByTimeAsync(49);
expect(sent).toHaveLength(0);
await vi.advanceTimersByTimeAsync(2);
expect(sent).toEqual([{ resource: 'processes', data: [{ pid: 9999 }] }]);
handle.dispose();
});
it('coalesces a burst of publishes for the SAME resource into one send', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({ 'processes': 'fresh' });
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
for (let i = 0; i < 20; i++) bus.publish('processes');
await vi.advanceTimersByTimeAsync(51);
expect(sent).toEqual([{ resource: 'processes', data: 'fresh' }]);
// Snapshot was only invoked once for the whole burst.
expect(snapshot).toHaveBeenCalledExactlyOnceWith('processes');
handle.dispose();
});
it('each resource has its own independent debounce timer', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({
'processes': 'p',
'qq-list': 'q',
'connections': 'c',
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
await vi.advanceTimersByTimeAsync(30);
bus.publish('qq-list');
await vi.advanceTimersByTimeAsync(25); // processes fires at t=50 (5ms after this), qq-list pending till t=80
expect(sent.map((f) => f.resource)).toEqual(['processes']);
await vi.advanceTimersByTimeAsync(30);
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list']);
bus.publish('connections');
await vi.advanceTimersByTimeAsync(51);
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list', 'connections']);
handle.dispose();
});
it('dispose() stops further sends, both pending and future', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({ 'processes': 'x' });
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
handle.dispose();
await vi.advanceTimersByTimeAsync(200);
expect(sent).toEqual([]);
// Subsequent publishes are dead too.
bus.publish('processes');
await vi.advanceTimersByTimeAsync(200);
expect(sent).toEqual([]);
});
it('snapshot() rejection is isolated — the failed resource is skipped and others keep flowing', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = vi.fn(async (resource: StateResource): Promise<unknown> => {
if (resource === 'processes') throw new Error('listProcesses failed');
if (resource === 'qq-list') return [{ uin: '1' }];
return [];
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
bus.publish('qq-list');
await vi.advanceTimersByTimeAsync(60);
// qq-list went through; processes didn't (snapshot threw).
expect(sent.find((f) => f.resource === 'qq-list')?.data).toEqual([{ uin: '1' }]);
expect(sent.find((f) => f.resource === 'processes')).toBeUndefined();
handle.dispose();
});
it('serialises overlapping flushes for the same resource — the LAST sent frame reflects the LATEST publish (no stale overwrite)', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
// Variable-latency snapshot: 1st call sleeps 200ms (slow), 2nd call
// sleeps 10ms (fast). Without single-flight, the second publish would
// race-overlap and send BEFORE the first, leaving the client's last
// observed frame as the older snapshot.
let call = 0;
const versions = ['snap-T0', 'snap-T60'];
const snapshot = vi.fn(async (_resource: StateResource): Promise<unknown> => {
const i = call++;
const sleep = i === 0 ? 200 : 10;
await new Promise<void>((r) => setTimeout(r, sleep));
return versions[i] ?? `snap-#${i}`;
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes'); // schedules timer1 → fires at 50, snapshot A (200ms)
await vi.advanceTimersByTimeAsync(60);
bus.publish('processes'); // arrives WHILE flush A is mid-snapshot
await vi.advanceTimersByTimeAsync(60); // hits 120: timer2 should have fired, flush B observed_after A completes
await vi.advanceTimersByTimeAsync(300); // settle everything
// Exactly two frames; the LAST one must reflect the most recent snapshot.
expect(sent).toHaveLength(2);
expect(sent[sent.length - 1]).toEqual({ resource: 'processes', data: 'snap-T60' });
// For single-flight: snapshot is called once per flush (no overlap),
// so the SECOND snapshot read sees the latest state.
expect(call).toBe(2);
handle.dispose();
});
it('multiple publishes during an in-flight flush coalesce into ONE follow-up flush, not N', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let call = 0;
const snapshot = vi.fn(async (_resource: StateResource): Promise<unknown> => {
call++;
await new Promise<void>((r) => setTimeout(r, 100));
return `snap-#${call}`;
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
await vi.advanceTimersByTimeAsync(55);
// flush A in flight (100ms more). Send 5 publishes during the in-flight window.
for (let i = 0; i < 5; i++) bus.publish('processes');
await vi.advanceTimersByTimeAsync(200);
await vi.advanceTimersByTimeAsync(200);
// 1 initial flush + 1 coalesced follow-up = 2 frames, NOT 6.
expect(sent).toHaveLength(2);
expect(call).toBe(2);
handle.dispose();
});
it('send() throw is isolated — the next publish still reaches a healthy send()', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let mode: 'throw' | 'ok' = 'throw';
const snapshot = makeSnapshotFn({ 'processes': 'x' });
const handle = bindStateStream({
bus, snapshot,
send: (f) => {
if (mode === 'throw') throw new Error('controller dead');
sent.push(f);
},
debounceMs: 50,
});
bus.publish('processes');
await vi.advanceTimersByTimeAsync(60);
expect(sent).toEqual([]);
mode = 'ok';
bus.publish('processes');
await vi.advanceTimersByTimeAsync(60);
expect(sent).toEqual([{ resource: 'processes', data: 'x' }]);
handle.dispose();
});
});

View File

@@ -0,0 +1,82 @@
import { describe, expect, it, vi } from 'vitest';
import { StateBus } from '../src/webui/state-bus';
import { createStateWiring } from '../src/webui/state-wiring';
import { BridgeManager } from '../src/bridge/manager';
describe('createStateWiring', () => {
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
const wiring = createStateWiring();
expect(wiring.bus).toBeInstanceOf(StateBus);
const sub = vi.fn();
wiring.bus.subscribe(sub);
wiring.onSessionsChanged();
expect(sub).toHaveBeenCalledExactlyOnceWith('processes');
});
it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
const seen: string[] = [];
wiring.bus.subscribe((r) => seen.push(r));
// Real onHookLogin path — fires the session-started listener internally
// exactly once (per uin).
bm.onHookLogin(4242, '12345', {} as never);
expect(seen).toEqual(['qq-list', 'connections']);
});
it('publishes "qq-list" + "connections" on session-closed', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
bm.onHookLogin(4242, '12345', {} as never);
const sub = vi.fn();
wiring.bus.subscribe(sub);
bm.onPidDisconnected(4242);
// Order is qq-list first (account list shrinks) then connections
// (adapter status list shrinks). Two distinct resource invalidations.
expect(sub).toHaveBeenCalledTimes(2);
expect(sub).toHaveBeenNthCalledWith(1, 'qq-list');
expect(sub).toHaveBeenNthCalledWith(2, 'connections');
});
it('dispose() unwires onSessionsChanged + BridgeManager listeners (no further publishes)', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
const sub = vi.fn();
wiring.bus.subscribe(sub);
wiring.dispose();
// onSessionsChanged becomes a no-op.
wiring.onSessionsChanged();
expect(sub).not.toHaveBeenCalled();
// BridgeManager listener fires nothing into a disposed bus.
bm.onHookLogin(4242, '12345', {} as never);
expect(sub).not.toHaveBeenCalled();
});
it('survives a BridgeManager listener throw — the OTHER listeners on the same BridgeManager keep working', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
// A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws.
const peer = vi.fn(() => { throw new Error('peer down'); });
bm.addSessionStartedListener(peer);
const sub = vi.fn();
wiring.bus.subscribe(sub);
expect(() => bm.onHookLogin(4242, '12345', {} as never)).not.toThrow();
// The state-wiring listener still ran (BridgeManager isolates exceptions
// per listener).
expect(sub).toHaveBeenCalledWith('qq-list');
expect(sub).toHaveBeenCalledWith('connections');
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.10.0",
"version": "1.10.3",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.10.0",
"version": "1.10.3",
"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>'`.",

View File

@@ -2,6 +2,21 @@ import { defineAction, groupAction, registerActions, f } from '../action-kit';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
// NapCat/LLOneBot omit `busid` from their `get_group_file_url` schema entirely,
// so whatever value a client tacks on is silently ignored. Mirror that here:
// accept any value, coerce when it's a usable non-negative integer, else fall
// back to the canonical 102. Restores the legacy `asNumber(busid) || 102`
// semantics that a strict `f.int({min:0}).default(102)` regressed (a *present*
// non-numeric busid was rejected with `expected an integer`). See issue #147.
function busidOr102(raw: unknown): number {
const n = typeof raw === 'number' && Number.isFinite(raw)
? Math.trunc(raw)
: typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))
? Math.trunc(Number(raw))
: NaN;
return Number.isInteger(n) && n >= 0 ? n : 102;
}
export const actions = [
groupAction({
name: 'upload_group_file',
@@ -45,13 +60,11 @@ export const actions = [
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) },
// busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it,
// so a present null/empty/non-numeric value must not 400 the request (#147).
params: { file_id: f.string({ allowEmpty: false }), busid: f.raw() },
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, p.busid) });
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, busidOr102(p.busid)) });
},
}),
@@ -159,13 +172,20 @@ export const actions = [
summary: '获取私聊文件下载链接',
readOnly: true,
returns: '{ url: string }',
// NapCat's `get_private_file_url` requires only file_id — it re-derives the
// file hash by decoding its composite file_id and reading file10MMd5 off the
// original message. SnowLuma's file_id is the bare fileUUID, so it relies on
// the file_hash that it already emits alongside file_id in the received file
// segment (event-converter/to-segment.ts). To stay drop-in for NapCat-style
// clients that only persist file_id, both user_id and file_hash are now
// optional; file_hash falls through empty when absent. See issue #147.
params: {
user_id: f.uint(),
user_id: f.uint().optional(),
file_id: f.string({ allowEmpty: false }),
file_hash: f.string({ allowEmpty: false }),
file_hash: f.string().default(''),
},
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id, p.file_id, p.file_hash) });
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id ?? 0, p.file_id, p.file_hash) });
},
}),
];

View File

@@ -1,8 +1,11 @@
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, JsonValue } from '../types';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { defineAction, groupAction, registerActions, f } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
const log = createLogger('OneBot');
/**
* Re-sign image URLs in a stored message event at read time. `get_msg`
* returns a copy persisted when the message first arrived, and image rkeys
@@ -89,7 +92,10 @@ export const actions = [
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');
if (!data) {
log.warn('[get_msg] miss message_id=%d', p.message_id);
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
}
const result: JsonObject = { ...data };
delete result.post_type;
delete result.self_id;

View File

@@ -21,9 +21,16 @@ const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, swallow: false, cooldownSeconds: 5 };
/** Upper bound on the `#sl` reply cooldown — a year is effectively "off but sane". */
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = {
enabled: true,
swallow: false,
cooldownSeconds: 5,
trigger: '#sl',
};
/** Upper bound on the status-command reply cooldown — a year is effectively "off but sane". */
const STATUS_COMMAND_COOLDOWN_MAX = 31_536_000;
/** Max length of a user-customised trigger word (UTF-16 code units). */
export const STATUS_COMMAND_TRIGGER_MAX_LENGTH = 32;
function makeDefaultStatusCommand(): StatusCommandConfig {
return { ...DEFAULT_STATUS_COMMAND };
@@ -113,6 +120,7 @@ function toJsonObject(config: OneBotConfig): JsonObject {
enabled: config.statusCommand.enabled,
swallow: config.statusCommand.swallow,
cooldownSeconds: config.statusCommand.cooldownSeconds,
trigger: config.statusCommand.trigger,
},
notifications: { channelIds: config.notifications?.channelIds ?? [] },
};
@@ -250,6 +258,9 @@ function parseStatusCommand(sources: JsonObject[]): StatusCommandConfig {
asNumber(raw.cooldownSeconds, DEFAULT_STATUS_COMMAND.cooldownSeconds),
);
}
if (typeof raw.trigger === 'string' && raw.trigger.trim().length > 0 && !/[\r\n]/.test(raw.trigger)) {
out.trigger = raw.trigger.trim().slice(0, STATUS_COMMAND_TRIGGER_MAX_LENGTH);
}
}
return out;
}

View File

@@ -7,6 +7,9 @@ import type {
MessageIdResolver,
} from './index';
import { resolveReplyId } from './utils';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('OneBot');
export async function elementsToJson(
elements: MessageElement[],
@@ -19,10 +22,17 @@ export async function elementsToJson(
): Promise<JsonArray> {
const result: JsonArray = [];
for (const element of elements) {
result.push(await elementToSegment(
element, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
));
// One malformed element shouldn't drop the whole message — skip it (with a
// breadcrumb) and keep converting the rest.
try {
result.push(await elementToSegment(
element, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
));
} catch (err) {
log.warn('segment convert skipped type=%s (%s)', element.type,
err instanceof Error ? err.message : String(err));
}
}
return result;
}

View File

@@ -189,7 +189,7 @@ export class OneBotInstance {
if (!cfg.enabled) return false;
const postType = event.post_type;
if (postType !== 'message' && postType !== 'message_sent') return false;
if (!matchesStatusCommand(event.message)) return false;
if (!matchesStatusCommand(event.message, cfg.trigger)) return false;
const isGroup = event.message_type === 'group';
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);

View File

@@ -9,6 +9,7 @@ export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
resolveContactArk?: (contactType: string, contactId: number) => string | null | Promise<string | null>;
musicSignUrl?: string;
}
@@ -291,6 +292,13 @@ export async function segmentToElement(type: string, data: Record<string, unknow
// Contact card — map to json card
const contactType = String(data.type ?? 'qq');
const contactId = String(data.id ?? '');
const numericId = intOr(contactId, 0);
const normalizedContactType = contactType.trim().toLowerCase();
if (numericId > 0 && options?.resolveContactArk && (normalizedContactType === 'qq' || normalizedContactType === 'group')) {
const ark = await options.resolveContactArk(contactType, numericId);
if (!ark) throw new Error(`contact ark unavailable for ${contactType}:${numericId}`);
return { type: 'json', text: ark };
}
const jsonData = JSON.stringify({
app: 'com.tencent.contact.lua',
view: 'contact',

View File

@@ -210,30 +210,103 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const targetId = hashMessageIdInt32(replySeq, session, eventName);
if (ref.messageStore.findEvent(targetId)) return; // already have the full event
if (ref.messageStore.findEvent(targetId)) return; // Tier 0: already have the full event
// Tier 1: fetch the quoted message from the server, keyed under the exact id
// the reply resolves to (replySeq is origSeqs[0] == the quoted message's own
// head.sequence, so this matches how it was/would be stored). A c2c message
// the bot itself sent converts with user_id=self but is still keyed under the
// reply's session (the peer), so get_msg(targetId) hits.
try {
let fetched: GroupMessage | FriendMessage | null;
let fetched: GroupMessage | FriendMessage | null = null;
if (isGroup) {
fetched = await ref.bridge.apis.message.getGroupMessageBySeq(session, replySeq, ref.selfId);
} else {
const friendUid = await ref.bridge.resolveUserUid(session);
if (!friendUid) return;
fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId);
if (friendUid) {
fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId);
}
}
if (fetched) {
const json = await convertEvent(ref.converterCtx, fetched);
if (json) {
json.message_id = targetId;
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json);
return;
}
}
if (!fetched) return;
const json = await convertEvent(ref.converterCtx, fetched);
if (!json) return;
// Key under the exact id the reply resolves to (and the reply's session) so
// get_msg(targetId) hits regardless of who sent the quoted message: a c2c
// message the bot itself sent converts with user_id=self and would
// otherwise key under a different session than the reply's peer.
json.message_id = targetId;
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json);
} catch (err) {
log.warn('reply-target backfill failed (%s)', err instanceof Error ? err.message : String(err));
log.warn('reply-target backfill tier-1 failed (%s)', err instanceof Error ? err.message : String(err));
}
// Tier 2: reconstruct from the quoted message's own elements, which the push
// embeds in SrcMsg.elems — no server round-trip. Covers messages the server
// won't return (expired, self-c2c, file-only) but whose content rode along.
const quotedSender = reply?.replySenderUin ?? (isGroup ? 0 : session);
if (reply?.replyElements?.length) {
try {
const segments = await elementsToOneBotSegments(
reply.replyElements, isGroup, session,
ref.converterCtx.imageUrlResolver, ref.converterCtx.mediaUrlResolver,
ref.converterCtx.messageIdResolver, ref.converterCtx.mediaSegmentSink,
) as JsonArray;
const fallback = buildBackfillEvent(targetId, replySeq, quotedSender,
reply.replyTime ?? 0, segments, ref.selfId, isGroup, session);
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback);
return;
} catch (err) {
log.warn('reply-target backfill tier-2 failed (%s)', err instanceof Error ? err.message : String(err));
}
}
// Tier 3: minimal `[引用消息]` placeholder so get_msg(reply_id) never returns
// "message not found" — an approval bot that fires get_msg right after seeing
// the reply gets a well-formed (if sparse) event instead of an error.
const placeholder = buildBackfillEvent(targetId, replySeq, quotedSender,
reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }],
ref.selfId, isGroup, session);
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder);
}
// Build a stored-message event for a backfilled reply target (Tier 2/3).
function buildBackfillEvent(
messageId: number,
msgSeq: number,
senderUin: number,
timestamp: number,
segments: JsonArray,
selfId: number,
isGroup: boolean,
sessionId: number,
): JsonObject {
const common = {
time: timestamp || Math.floor(Date.now() / 1000),
self_id: selfId,
post_type: 'message' as const,
message_id: messageId,
message_seq: msgSeq,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
};
if (isGroup) {
return {
...common,
message_type: 'group',
sub_type: 'normal',
group_id: sessionId,
user_id: senderUin,
sender: { user_id: senderUin, nickname: '', card: '', role: 'member', sex: 'unknown', age: 0 },
anonymous: null,
};
}
return {
...common,
message_type: 'private',
sub_type: 'friend',
user_id: senderUin,
sender: { user_id: senderUin, nickname: '', sex: 'unknown', age: 0 },
};
}
// Persist a converted history event so reply / get_msg / future listing resolve
@@ -375,6 +448,13 @@ async function cacheSelfSentMessage(
}
}
function resolveContactArk(ref: OneBotInstanceContext, contactType: string, contactId: number): Promise<string> | null {
const normalized = contactType.trim().toLowerCase();
if (normalized === 'qq') return ref.bridge.apis.contacts.getBuddyRecommendArk(contactId, '');
if (normalized === 'group') return ref.bridge.apis.contacts.getGroupRecommendArk(contactId);
return null;
}
export async function sendPrivateMessage(
ref: OneBotInstanceContext,
userId: number,
@@ -419,6 +499,7 @@ export async function sendPrivateMessage(
return null;
},
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin),
resolveContactArk: (contactType, contactId) => resolveContactArk(ref, contactType, contactId),
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
@@ -522,6 +603,7 @@ export async function sendGroupMessage(
return null;
},
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId),
resolveContactArk: (contactType, contactId) => resolveContactArk(ref, contactType, contactId),
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');

View File

@@ -15,6 +15,18 @@ export async function handleGroupAddRequest(
if (!groupId) throw new Error('invalid group_id in flag');
if (!targetUid) throw new Error('invalid request target in flag');
// Bot self-invited via a private "qun.invite" card: the only sequence the
// server accepts at 0x10c8_1 is that card's jumpUrl msgseq, with eventType=2
// / filtered=false. The fetchGroupRequests tuple below fails this case with
// 120161001 ("handle async message fail"). See issue #125.
if (requestType === 'invite') {
const cardSequence = bridge.apis.contacts.getGroupInviteCardSequence(groupId);
if (cardSequence) {
await bridge.apis.groupAdmin.setAddRequest(groupId, cardSequence, 2, approve, reason, false);
return;
}
}
const requests = await bridge.apis.contacts.fetchGroupRequests();
const matching = requests.find((r) => {
if (r.groupId !== groupId) return false;

View File

@@ -1,32 +1,24 @@
import type { JsonObject, JsonValue } from '../types';
/**
* Hardcoded trigger for the built-in status command — exact match,
* case-insensitive, after trimming. Intentionally NOT configurable: the
* `statusCommand.enabled` toggle is the only knob (the gate is on/off, not
* the word).
*/
export const STATUS_COMMAND_TRIGGER = '#sl';
/**
* True iff `message` is exactly the trigger: a single `text` segment (or a
* bare string for string-format adapters) whose trimmed, lowercased content
* equals {@link STATUS_COMMAND_TRIGGER}.
* True iff `message` matches the given trigger using exact match.
*
* Reads the segment array rather than `raw_message` to avoid CQ-encoding
* ambiguity, and rejects mixed-segment messages (`#sl` + image/at/reply) so
* only a pure `#sl` triggers — no `startsWith`, so `#slogan` never matches.
* Only a single text segment (or a bare string) is accepted — mixed-segment
* messages (e.g. `#sl` + image) never match.
*/
export function matchesStatusCommand(message: JsonValue | undefined): boolean {
export function matchesStatusCommand(
message: JsonValue | undefined,
trigger: string,
): boolean {
if (typeof message === 'string') {
return normalize(message) === STATUS_COMMAND_TRIGGER;
return normalize(message) === normalize(trigger);
}
if (!Array.isArray(message) || message.length !== 1) return false;
const seg = message[0];
if (!isObject(seg) || seg.type !== 'text') return false;
const data = isObject(seg.data) ? seg.data : null;
const text = data && typeof data.text === 'string' ? data.text : '';
return normalize(text) === STATUS_COMMAND_TRIGGER;
return normalize(text) === normalize(trigger);
}
function normalize(s: string): string {
@@ -58,7 +50,7 @@ export interface StatusInfo {
uptimeMs: number;
}
/** Render the public-safe `#sl` reply: version + platform/arch + uptime. */
/** Render the status reply. */
export function buildStatusText(info: StatusInfo): string {
return [
'SnowLuma 状态',

View File

@@ -1,6 +1,6 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import { shapeEventForAdapter, type DispatchPayload, type EventReportOptions } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
export interface NetworkAdapterContext {
@@ -58,6 +58,39 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
/** Report live connection health for the WebUI dashboard. */
abstract describeStatus(): AdapterStatus;
// ── meta-event framing: shared by the connection-oriented adapters ─────
//
// Lifecycle (connect/enable/disable) and heartbeat meta events don't flow
// through `OneBotNetworkManager.emitEvent` (no pre-serialized DispatchPayload),
// so each connection-oriented adapter shapes them per its report options and
// serializes on the spot. The shape+serialize policy lives here once; the
// adapters only own the transport (which socket(s) to `safeSend` to).
/** Shape one meta event for `options` and serialize it to a wire frame, or
* `null` when the shaper drops it (e.g. a self-message under
* `reportSelfMessage:false`). */
protected metaFrame(event: JsonObject, options: EventReportOptions): string | null {
const shaped = shapeEventForAdapter(event, options);
return shaped === null ? null : JSON.stringify(shaped);
}
/** The bootstrap meta frames an event client receives on (re)connect:
* `connect`, `enable`, then a `heartbeat`, shaped for `options`. Frames the
* shaper drops are omitted. */
protected bootstrapMetaFrames(options: EventReportOptions): string[] {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
const frames: string[] = [];
for (const event of events) {
const frame = this.metaFrame(event, options);
if (frame !== null) frames.push(frame);
}
return frames;
}
// ── reload: shared hot-reload state machine (template method) ──────────
//
// All four adapters reconcile a live config swap identically: decide

View File

@@ -3,7 +3,6 @@ import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
@@ -153,16 +152,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private sendBootstrapMetaEvents(socket: WebSocket): void {
if (this.role !== 'Event' && this.role !== 'Universal') return;
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame);
}
}

View File

@@ -4,7 +4,6 @@ import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
@@ -45,9 +44,8 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
const lifecycle = this.ctx.buildLifecycleEvent('disable');
for (const conn of this.connections.values()) {
if (conn.role === 'Api') continue;
const shaped = shapeEventForAdapter(lifecycle, conn.options);
if (!shaped) continue;
safeSend(conn.socket, JSON.stringify(shaped));
const frame = this.metaFrame(lifecycle, conn.options);
if (frame) safeSend(conn.socket, frame);
}
this.isEnabled = false;
@@ -142,16 +140,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame);
}
}

View File

@@ -64,19 +64,22 @@ export interface OneBotNetworks {
}
/**
* Built-in `#sl` status command. The trigger word is hardcoded (`#sl`,
* exact match, case-insensitive); only these toggles are configurable.
* Built-in status command settings. The trigger word is configurable;
* defaults to `#sl` with exact case-insensitive matching.
*/
export interface StatusCommandConfig {
/** Master on/off. Default `true` — built-in, but freely disableable. */
/** Master on/off. Default `true`. */
enabled: boolean;
/**
* When `true`, a matched `#sl` is NOT forwarded to downstream adapters
* (it is still cached, logged, and replied to). Default `false` (pass-through).
* When `true`, a matched status command is NOT forwarded to downstream
* adapters (it is still cached, logged, and replied to). Default `false`.
*/
swallow: boolean;
/** Per-conversation reply cooldown in seconds. `0` disables it. Default `5`. */
cooldownSeconds: number;
/** Trigger word. Default `'#sl'`. Non-empty, max 32 chars. */
trigger: string;
}
/** Per-UIN OneBot configuration. */

View File

@@ -145,7 +145,30 @@ describe('backfillReplyTarget', () => {
expect(store.storeEvent).not.toHaveBeenCalled();
});
it('does not store when the server has nothing at that sequence', async () => {
it('reconstructs from replyElements when the server has nothing (tier 2)', async () => {
const store = fakeStore(false);
const getGroupMessageBySeq = vi.fn(async () => null);
const ref = {
selfId: SELF, converterCtx, messageStore: store,
bridge: { apis: { message: { getGroupMessageBySeq } }, resolveUserUid: vi.fn() },
} as any;
const event = {
kind: 'group_message', time: 1, selfUin: SELF, groupId: 700, senderUin: 900,
senderNick: '', senderCard: '', senderRole: 'member', msgSeq: 999, msgId: 2,
elements: [{ type: 'reply', replySeq: 123, replySenderUin: 800, replyElements: [{ type: 'text', text: 'quoted' }] }],
} as any;
await backfillReplyTarget(ref, event);
const targetId = hashMessageIdInt32(123, 700, GROUP_MESSAGE_EVENT);
expect(store.storeEvent).toHaveBeenCalledOnce();
expect(store.storeEvent).toHaveBeenCalledWith(
targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'group', user_id: 800 }),
);
});
it('stores a [引用消息] placeholder when server fetch and replyElements both miss (tier 3)', async () => {
const store = fakeStore(false);
const getGroupMessageBySeq = vi.fn(async () => null);
const ref = {
@@ -156,6 +179,11 @@ describe('backfillReplyTarget', () => {
await backfillReplyTarget(ref, groupEvent(123));
expect(getGroupMessageBySeq).toHaveBeenCalledOnce();
expect(store.storeEvent).not.toHaveBeenCalled();
const targetId = hashMessageIdInt32(123, 700, GROUP_MESSAGE_EVENT);
expect(store.storeEvent).toHaveBeenCalledOnce();
expect(store.storeEvent).toHaveBeenCalledWith(
targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'group' }),
);
});
});

View File

@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig } from '../src/config';
import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig, STATUS_COMMAND_TRIGGER_MAX_LENGTH } from '../src/config';
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
@@ -25,7 +25,7 @@ describe('makeDefaultOneBotConfig', () => {
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
expect(config.networks.wsClients).toEqual([]);
expect(config.musicSignUrl).toBe('');
expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' });
expect(config.notifications).toEqual({ channelIds: [] });
});
});
@@ -60,7 +60,7 @@ describe('loadOneBotConfig', () => {
expect(onDisk.httpServers).toBeUndefined();
expect(onDisk.wsServers).toBeUndefined();
// statusCommand is materialised with defaults on a fresh install.
expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' });
});
it('fills statusCommand defaults and clamps a negative cooldown', () => {
@@ -150,6 +150,75 @@ describe('loadOneBotConfig', () => {
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
});
it('fills new statusCommand fields with defaults when absent', () => {
const uin = '10042';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `onebot_${uin}.json`),
JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
statusCommand: { enabled: false },
}),
);
const config = loadOneBotConfig(uin);
expect(config.statusCommand.enabled).toBe(false); // from file
expect(config.statusCommand.trigger).toBe('#sl'); // default
});
it('clamps trigger length and rejects empty trigger', () => {
const uin = '10043';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `onebot_${uin}.json`),
JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
statusCommand: { trigger: '' },
}),
);
const config = loadOneBotConfig(uin);
expect(config.statusCommand.trigger).toBe('#sl'); // empty → default
});
it('truncates trigger to max 32 chars', () => {
const uin = '10049';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `onebot_${uin}.json`),
JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
statusCommand: { trigger: 'a'.repeat(100) },
}),
);
const config = loadOneBotConfig(uin);
expect(config.statusCommand.trigger.length).toBe(32);
});
it('rejects trigger containing newline, falls back to default', () => {
const uin = '10050';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `onebot_${uin}.json`),
JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
statusCommand: { trigger: '#sl\nbot' },
}),
);
const config = loadOneBotConfig(uin);
expect(config.statusCommand.trigger).toBe('#sl');
});
it('aligns MAX_LENGTH constant with expected value', () => {
expect(STATUS_COMMAND_TRIGGER_MAX_LENGTH).toBe(32);
});
it('does not write to disk by default (read-only contract)', () => {
const uin = '10006';
const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`);

View File

@@ -8,7 +8,7 @@ import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MentionExtraSend } from '@snowluma/proto-defs/action';
import type { MarketFacePbReserve } from '@snowluma/proto-defs/element';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
import type { NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
describe('parseMessage', () => {
describe('plain text', () => {
@@ -275,8 +275,16 @@ describe('parseMessage', () => {
thumbUrl: 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
}], { bridge, groupId: 123456 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
expect(bridge.sendRawPacket).toHaveBeenCalledWith('OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
// The video main file carries real bytes but the server fast-paths it
// (fileExist:true, no uKey) — #145's forceFullOnFastPath re-issues the
// OIDB request with fast-upload disabled, so two packets go out.
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.sendRawPacket).toHaveBeenNthCalledWith(1, 'OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
expect(bridge.sendRawPacket).toHaveBeenNthCalledWith(2, 'OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
const firstReq = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[0]![1] as Uint8Array);
const secondReq = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[1]![1] as Uint8Array);
expect(firstReq.body.upload.tryFastUploadCompleted).toBe(true);
expect(secondReq.body.upload.tryFastUploadCompleted ?? false).toBe(false);
expect(protoElems).toHaveLength(1);
expect(protoElems[0].commonElem?.serviceType).toBe(48);
expect(protoElems[0].commonElem?.businessType).toBe(21);

View File

@@ -0,0 +1,211 @@
// Phase-0 safety net for the bootstrap-meta deepening: characterize the
// CURRENT observable behavior the refactor must preserve —
// 1. event-filter `shapeEventForAdapter` shaping rules (the policy that
// the lifted `metaFrame` primitive will wrap),
// 2. ws-client emits exactly [connect, enable, heartbeat] on socket open,
// shaped per options, honoring the role guard,
// 3. ws-server emits the same triplet to an Event connection, and on
// close() broadcasts a single `disable` lifecycle to non-Api conns.
//
// Mirrors ws-client-stale-close.test.ts: `@snowluma/websocket`'s native
// addon isn't built in a plain checkout, so WebSocket + WebSocketServer are
// faked via vi.hoisted + vi.mock and driven explicitly.
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { FakeWebSocket, FakeWebSocketServer, clientInstances, servers } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { EventEmitter } = require('node:events') as typeof import('node:events');
const clientInstances: FakeWebSocket[] = [];
const servers: FakeWebSocketServer[] = [];
class FakeWebSocket extends EventEmitter {
public readyState = 1; // OPEN
public readonly sent: string[] = [];
public readonly url: string;
constructor(url = '', _opts?: unknown) {
super();
this.url = url;
clientInstances.push(this);
}
send(payload: string, cb?: (err?: Error | null) => void): void {
this.sent.push(payload);
cb?.(null);
}
close(): void { this.readyState = 3; }
simulateOpen(): void { this.emit('open'); }
}
class FakeWebSocketServer extends EventEmitter {
public closed = false;
constructor(_opts: unknown) {
super();
servers.push(this);
}
close(): void { this.closed = true; }
/** Drive a client connection through the adapter's 'connection' handler. */
simulateConnection(socket: FakeWebSocket, request: unknown): void {
this.emit('connection', socket, request);
}
}
return { FakeWebSocket, FakeWebSocketServer, clientInstances, servers };
});
vi.mock('@snowluma/websocket', () => ({
WebSocket: FakeWebSocket,
WebSocketServer: FakeWebSocketServer,
}));
import { shapeEventForAdapter, resolveReportOptions } from '../src/event-filter';
import { WsClientAdapter } from '../src/network/ws-client-adapter';
import { WsServerAdapter } from '../src/network/ws-server-adapter';
import type { NetworkAdapterContext } from '../src/network/adapter';
import type { JsonObject, WsClientNetwork, WsServerNetwork } from '../src/types';
// Distinguishable meta events so the bootstrap triplet is identifiable on the
// wire (the real ctx builds real OneBot meta_event objects).
function ctx(): NetworkAdapterContext {
return {
uin: '10001',
api: { processRequest: async () => '' } as never,
buildLifecycleEvent: (sub) => ({ post_type: 'meta_event', meta_event_type: 'lifecycle', sub_type: sub }),
buildHeartbeatEvent: () => ({ post_type: 'meta_event', meta_event_type: 'heartbeat', interval: 5000 }),
};
}
const parse = (s: string) => JSON.parse(s) as JsonObject;
describe('event-filter shapeEventForAdapter — shaping policy (characterization)', () => {
const arrayOpts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
const stringOpts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
const selfOpts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
it('passes meta_event (and any non-message) through unchanged', () => {
const meta = { post_type: 'meta_event', meta_event_type: 'heartbeat' } as JsonObject;
expect(shapeEventForAdapter(meta, arrayOpts)).toEqual(meta);
expect(shapeEventForAdapter(meta, stringOpts)).toEqual(meta);
});
it('drops message_sent when reportSelfMessage is false, keeps it when true', () => {
const sent = { post_type: 'message_sent', message: [{ type: 'text', data: { text: 'hi' } }], raw_message: 'hi' } as JsonObject;
expect(shapeEventForAdapter(sent, arrayOpts)).toBeNull();
expect(shapeEventForAdapter(sent, selfOpts)).toEqual(sent);
});
it('string format collapses an array message to its raw_message', () => {
const msg = { post_type: 'message', message: [{ type: 'text', data: { text: 'hi' } }], raw_message: 'hi' } as JsonObject;
expect(shapeEventForAdapter(msg, arrayOpts)).toEqual(msg); // untouched in array mode
const shaped = shapeEventForAdapter(msg, stringOpts);
expect(shaped?.message).toBe('hi'); // array → raw string
});
});
describe('WsClientAdapter — bootstrap meta on open (characterization)', () => {
beforeEach(() => { clientInstances.length = 0; });
function cfg(over: Partial<WsClientNetwork> = {}): WsClientNetwork {
return { enabled: true, url: 'ws://127.0.0.1:8080/', role: 'Universal', reconnectIntervalMs: 1000, ...over } as WsClientNetwork;
}
it('sends exactly [connect, enable, heartbeat] when the socket opens', () => {
const adapter = new WsClientAdapter('ws', cfg(), ctx());
adapter.open();
clientInstances[0].simulateOpen();
const frames = clientInstances[0].sent.map(parse);
expect(frames).toEqual([
{ post_type: 'meta_event', meta_event_type: 'lifecycle', sub_type: 'connect' },
{ post_type: 'meta_event', meta_event_type: 'lifecycle', sub_type: 'enable' },
{ post_type: 'meta_event', meta_event_type: 'heartbeat', interval: 5000 },
]);
});
it('does NOT send bootstrap when role is Api-only', () => {
const adapter = new WsClientAdapter('ws', cfg({ role: 'Api' }), ctx());
adapter.open();
clientInstances[0].simulateOpen();
expect(clientInstances[0].sent).toEqual([]);
});
it('drops a bootstrap frame that shapes to null, and threads options through the shaper', () => {
// Force the heartbeat to shape to null when reportSelfMessage is false by
// making it a message_sent event. This pins TWO invariants the lift must
// keep: (1) a frame whose shape returns null is skipped, (2) the adapter's
// options actually reach shapeEventForAdapter (else the drop wouldn't be
// conditional on reportSelfMessage).
const selfMsgHeartbeatCtx = (): NetworkAdapterContext => ({
...ctx(),
buildHeartbeatEvent: () => ({ post_type: 'message_sent', message: [{ type: 'text', data: { text: 'x' } }], raw_message: 'x' }),
});
const dropper = new WsClientAdapter('ws', cfg({ reportSelfMessage: false }), selfMsgHeartbeatCtx());
dropper.open();
clientInstances.at(-1)!.simulateOpen();
expect(clientInstances.at(-1)!.sent.map(parse).map((f) => f.sub_type)).toEqual(['connect', 'enable']);
clientInstances.length = 0;
const keeper = new WsClientAdapter('ws', cfg({ reportSelfMessage: true }), selfMsgHeartbeatCtx());
keeper.open();
clientInstances.at(-1)!.simulateOpen();
expect(clientInstances.at(-1)!.sent).toHaveLength(3); // kept when self-reporting → options threaded
});
});
describe('WsServerAdapter — bootstrap on connect + disable on close (characterization)', () => {
beforeEach(() => { servers.length = 0; clientInstances.length = 0; });
function cfg(over: Partial<WsServerNetwork> = {}): WsServerNetwork {
return { enabled: true, host: '127.0.0.1', port: 8080, path: '/', role: 'Event', accessToken: '', ...over } as WsServerNetwork;
}
const req = { headers: {}, url: '/' };
it('sends the bootstrap triplet to a new Event connection', () => {
const adapter = new WsServerAdapter('wss', cfg(), ctx());
adapter.open();
const sock = new FakeWebSocket();
servers[0].simulateConnection(sock, req);
const frames = sock.sent.map(parse);
expect(frames.map((f) => f.meta_event_type)).toEqual(['lifecycle', 'lifecycle', 'heartbeat']);
expect(frames.map((f) => f.sub_type)).toEqual(['connect', 'enable', undefined]);
});
it('broadcasts a single disable lifecycle to connected event clients on close()', () => {
const adapter = new WsServerAdapter('wss', cfg(), ctx());
adapter.open();
const sock = new FakeWebSocket();
servers[0].simulateConnection(sock, req);
sock.sent.length = 0; // drop the bootstrap frames; we only care about close
adapter.close();
const frames = sock.sent.map(parse);
expect(frames).toEqual([
{ post_type: 'meta_event', meta_event_type: 'lifecycle', sub_type: 'disable' },
]);
});
it('skips Api connections for both bootstrap and the close disable broadcast', () => {
// Role is classified per request path (no fixed config.role): /event → Event,
// /api → Api. Pins that Api conns receive neither the bootstrap triplet nor
// the disable broadcast — the close()-side Api guard the lift reroutes.
const adapter = new WsServerAdapter('wss', cfg({ role: undefined }), ctx());
adapter.open();
const eventSock = new FakeWebSocket();
const apiSock = new FakeWebSocket();
servers[0].simulateConnection(eventSock, { headers: {}, url: '/event' });
servers[0].simulateConnection(apiSock, { headers: {}, url: '/api' });
expect(apiSock.sent).toEqual([]); // Api gets no bootstrap
expect(eventSock.sent).toHaveLength(3); // Event gets the triplet
eventSock.sent.length = 0;
adapter.close();
expect(apiSock.sent).toEqual([]); // Api skipped on close too
expect(eventSock.sent.map(parse)).toEqual([
{ post_type: 'meta_event', meta_event_type: 'lifecycle', sub_type: 'disable' },
]);
});
});

View File

@@ -8,6 +8,7 @@ const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
getGroupInviteCardSequence: 'contacts',
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
@@ -72,6 +73,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
fetchGroupRequests: vi.fn(async () => [
fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }),
]),
getGroupInviteCardSequence: vi.fn(() => null),
apis: { groupAdmin: { setAddRequest } } as any,
});

View File

@@ -1,6 +1,5 @@
import { describe, it, expect } from 'vitest';
import {
STATUS_COMMAND_TRIGGER,
buildStatusText,
formatUptime,
matchesStatusCommand,
@@ -12,25 +11,26 @@ function textSeg(text: string): JsonValue {
return [{ type: 'text', data: { text } }] as unknown as JsonValue;
}
const ANY_TRIGGER = '#sl';
describe('matchesStatusCommand', () => {
it('matches a single text segment equal to the trigger', () => {
expect(matchesStatusCommand(textSeg('#sl'))).toBe(true);
expect(matchesStatusCommand(textSeg('#sl'), ANY_TRIGGER)).toBe(true);
});
it('is case-insensitive and trims surrounding whitespace', () => {
expect(matchesStatusCommand(textSeg('#SL'))).toBe(true);
expect(matchesStatusCommand(textSeg(' #Sl '))).toBe(true);
expect(matchesStatusCommand(textSeg('#SL'), ANY_TRIGGER)).toBe(true);
expect(matchesStatusCommand(textSeg(' #Sl '), ANY_TRIGGER)).toBe(true);
});
it('matches a bare string (string-format adapters)', () => {
expect(matchesStatusCommand('#sl' as unknown as JsonValue)).toBe(true);
expect(matchesStatusCommand(' #SL ' as unknown as JsonValue)).toBe(true);
expect(matchesStatusCommand('#sl' as unknown as JsonValue, ANY_TRIGGER)).toBe(true);
expect(matchesStatusCommand(' #SL ' as unknown as JsonValue, ANY_TRIGGER)).toBe(true);
});
it('does NOT match as a prefix — only exact', () => {
expect(matchesStatusCommand(textSeg('#slogan'))).toBe(false);
expect(matchesStatusCommand(textSeg('#sl help'))).toBe(false);
expect(matchesStatusCommand(textSeg('你好 #sl'))).toBe(false);
expect(matchesStatusCommand(textSeg('#slogan'), ANY_TRIGGER)).toBe(false);
expect(matchesStatusCommand(textSeg('#sl help'), ANY_TRIGGER)).toBe(false);
});
it('rejects mixed-segment messages', () => {
@@ -38,18 +38,20 @@ describe('matchesStatusCommand', () => {
{ type: 'text', data: { text: '#sl' } },
{ type: 'image', data: { file: 'x.png' } },
] as unknown as JsonValue;
expect(matchesStatusCommand(mixed)).toBe(false);
expect(matchesStatusCommand(mixed, ANY_TRIGGER)).toBe(false);
});
it('rejects non-text leading segments and empty/garbage input', () => {
expect(matchesStatusCommand([{ type: 'at', data: { qq: '1' } }] as unknown as JsonValue)).toBe(false);
expect(matchesStatusCommand([] as unknown as JsonValue)).toBe(false);
expect(matchesStatusCommand(undefined)).toBe(false);
expect(matchesStatusCommand(123 as unknown as JsonValue)).toBe(false);
expect(matchesStatusCommand([{ type: 'at', data: { qq: '1' } }] as unknown as JsonValue, ANY_TRIGGER)).toBe(false);
expect(matchesStatusCommand([] as unknown as JsonValue, ANY_TRIGGER)).toBe(false);
expect(matchesStatusCommand(undefined, ANY_TRIGGER)).toBe(false);
expect(matchesStatusCommand(123 as unknown as JsonValue, ANY_TRIGGER)).toBe(false);
});
it('exposes the hardcoded trigger', () => {
expect(STATUS_COMMAND_TRIGGER).toBe('#sl');
it('works with custom trigger words', () => {
expect(matchesStatusCommand(textSeg('/status'), '/status')).toBe(true);
expect(matchesStatusCommand(textSeg('.ping'), '.ping')).toBe(true);
expect(matchesStatusCommand(textSeg('/status'), '#sl')).toBe(false);
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.10.0",
"version": "1.10.3",
"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).",

View File

@@ -119,6 +119,10 @@ export interface OidbSpecialTitleBody {
targetUid?: pb<1, string>;
specialTitle?: pb<5, string>;
expireTime?: pb<6, int_32>;
// The server requires uinName (tag 7) set to the same title, else it accepts
// the request (errorCode 0) but silently never applies it. Both NapCat and
// Lagrange send uinName = title (Lagrange 0x8FC body @7, NapCat Oidb.0x8FC_2).
uinName?: pb<7, string>;
}
export interface OidbSpecialTitle {
groupUin?: pb<1, uint_32>;

View File

@@ -1,8 +1,7 @@
// Recommend-contact ARK card protobufs, RE'd from QQNT wrapper.linux.node.
//
// Buddy: OidbSvcTrpcTcp.0x9130_0 (getBuddyRecommendContactArkJson) — encoder
// `buddy_recommend_contact_ark_json.cc::EncodeRequest` writes {1:uin,
// 2:phone,3:jump_url}; decoder reads {1:ark json}.
// Buddy: OidbSvcTrpcTcp.0x12b6_0 (getBuddyRecommendContactArkJson) —
// request writes {1:uin, 2:phone, 3:jump_url}; response reads {1:ark}.
// Group: OidbSvcTrpcTcp.0x8b7_5 (getGroupRecommendContactArkJson) — encoder
// `group_get_ark_json_worker.cc::EncodeRequest` writes {1:reqType=1,
// 2:groupCode,5:flag=1}; response (group_info_mgr.cc `[gp_get_ark_json]`)
@@ -12,12 +11,12 @@
import type { pb, uint_32 } from '@snowluma/proton';
export interface OidbBuddyRecommendArkReq {
uin?: pb<1, uint_32>;
phoneNum?: pb<2, string>;
jumpUrl?: pb<3, string>;
uin?: pb<1, uint_32>;
phoneNumber?: pb<2, string>;
jumpUrl?: pb<3, string>;
}
export interface OidbBuddyRecommendArkResp {
arkJson?: pb<1, string>;
ark?: pb<1, string>;
}
export interface OidbGroupRecommendArkReq {

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.10.0",
"version": "1.10.3",
"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>'`.",

View File

@@ -105,6 +105,24 @@ function makeReplyElem(element: MessageElement): ProtoElem {
return { srcMsg };
}
// The replied sender, encoded as a mention element placed right after srcMsg.
// QQ NT's group reply wire shape expects this; without it a following
// user-supplied @ is silently not honored by the server (issue #129).
async function makeReplyMentionElem(ctx: SendContext, uin: number): Promise<ProtoElem | null> {
if (ctx.groupId === undefined || uin <= 0) return null;
const member = ctx.bridge.identity.findGroupMember(ctx.groupId, uin);
let uid = member?.uid ?? '';
if (!uid) uid = await ctx.bridge.identity.resolveUid(uin, ctx.groupId).catch(() => '');
if (!uid) return null;
const name = member?.card?.trim() || member?.nickname?.trim() || String(uin);
// uin=0 matches QQ NT's native reply auto-mention (the real uid lives in
// `uid`). It does not itself notify — the user's own @ does — and the receive
// side strips a type=2/uin=0 mention as structural (#127), so the bot's own
// replies don't surface a spurious @ either.
const extra = protobuf_encode<MentionExtraSend>({ type: 2, uin: 0, field5: 0, uid });
return { text: { str: `@${name} `, pbReserve: extra } };
}
function makeDeflatedPayload(content: string): Uint8Array {
const deflated = deflateSync(Buffer.from(content, 'utf8'));
const payload = new Uint8Array(deflated.length + 1);
@@ -378,6 +396,12 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
*/
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
const result: ProtoElem[] = [];
// A user-supplied @ that lands immediately after a reply's srcMsg isn't
// honored by the QQ NT group server (the @ shows but never notifies, #129).
// When a reply and an @ coexist, emit the replied sender as a trailing
// mention right after srcMsg (mirrors Lagrange ForwardEntity.PackElement),
// which restores the wire shape the server expects.
const hasUserAt = elements.some((e) => e.type === 'at');
for (const elem of elements) {
switch (elem.type) {
@@ -398,7 +422,13 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'reply':
if (elem.replySeq) result.push(makeReplyElem(elem));
if (elem.replySeq) {
result.push(makeReplyElem(elem));
if (hasUserAt && ctx?.groupId !== undefined && elem.replySenderUin) {
const replyMention = await makeReplyMentionElem(ctx, elem.replySenderUin);
if (replyMention) result.push(replyMention);
}
}
break;
case 'json':

View File

@@ -14,6 +14,7 @@ export interface MessageElement {
replySenderUin?: number; // For reply: original sender's UIN
replyTime?: number; // For reply: original message timestamp
replyRandom?: number; // For reply: original message random/msgId
replyElements?: MessageElement[]; // Decoded elements of the quoted message (SrcMsg.elems) — lets a backfill reconstruct it for get_msg without a server round-trip
url?: string;
thumbUrl?: string;
subType?: number;

View File

@@ -18,6 +18,17 @@ const log = createLogger('Highway');
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
// Per-chunk transport retry. A large file uploads as many sequential
// one-shot TCP connections; QQ's highway edge nodes (and proxies/NAT on the
// path) sporadically FIN a fresh connection before responding, so a single
// transient close among a 48 MB file's ~48 chunks must not abort the whole
// upload (issue #118). Only transport failures retry — a decoded highway
// error_code is a definitive server reject and is never retried.
const HIGHWAY_MAX_CHUNK_ATTEMPTS = 3;
const HIGHWAY_RETRY_BASE_MS = 300;
const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
export const PRIVATE_IMAGE_CMD_ID = 1003;
export const GROUP_IMAGE_CMD_ID = 1004;
@@ -261,14 +272,45 @@ export async function uploadHighwayHttp(
);
const frame = packHighwayFrame(head, chunk);
const socket = await tcpConnect(session.host, session.port);
let responseBody: Uint8Array;
try {
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
} finally {
socket.destroy();
// Retry the connect + POST for this chunk on transient transport errors
// (peer FIN before response, ECONNRESET, connect refused/timeout). Each
// attempt uses a fresh connection; re-sending the same offset range is
// idempotent on the server.
let responseBody: Uint8Array | undefined;
for (let attempt = 1; ; attempt++) {
let socket: net.Socket;
try {
socket = await tcpConnect(session.host, session.port);
} catch (err) {
if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) {
throw new Error(
`highway connect failed after ${attempt} attempts ` +
`(cmdId=${commandId} offset=${offset}/${bytes.length}): ${String(err)}`,
);
}
await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt);
continue;
}
try {
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
break;
} catch (err) {
if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) {
throw new Error(
`highway upload transport failed after ${attempt} attempts ` +
`(cmdId=${commandId} chunk=${chunkSize}/${bytes.length} offset=${offset}): ${String(err)}`,
);
}
log.trace('chunk offset=%d attempt %d failed (%s), retrying', offset, attempt, String(err));
await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt);
} finally {
socket.destroy();
}
}
// Unreachable: the retry loop only exits via break (responseBody set) or
// throw — the guard just narrows the type for the compiler.
if (!responseBody) throw new Error('highway upload: missing response');
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
if (resp?.errorCode && resp.errorCode !== 0) {

View File

@@ -51,6 +51,16 @@ export interface MediaSubFileUpload {
* Omit if the caller guarantees bytes always exist (e.g. video thumb
* always has FALLBACK_THUMB bytes). */
fastOnlyError?: string;
/** When true and the server fast-paths THIS sub-file (returns no uKey)
* even though we hold real bytes for it, `runNtv2Upload` re-issues the
* whole OIDB request with `tryFastUploadCompleted: false` to force a
* fresh full upload. Video sets this on the main file: group/c2c video
* resources expire server-side, so a fast-path hit can reference a
* stale object the receiver renders as "资源已过期". The thumb leaves
* this off — a cached thumb is harmless and not worth re-pushing the
* whole (potentially 100 MB) main video for. Forwarding paths carry no
* bytes (`bytes.length === 0`), so this never fires for them. */
forceFullOnFastPath?: boolean;
}
export interface NtV2UploadParams {
@@ -120,94 +130,135 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
? moduleLog.child({ uin: uinNum })
: moduleLog;
// Build the full body once. Pulling this in here means each format file
// only specifies the seven fields that actually vary.
const body: NTV2UploadRichMediaReq = {
reqHead: {
common: { requestId: params.requestId, command: 100 },
scene: {
requestType: 2,
businessType: params.businessType,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
// Send one OIDB request and return its decoded `upload` body. `tryFast`
// toggles `tryFastUploadCompleted`: true asks the server to reuse a
// cached resource (skip the bytes); false forces it to allocate a fresh
// upload session and hand back a uKey. NOTE: proton only emits a plain
// `pb<bool>` when it's `true`, so `tryFast === false` omits field 2 —
// the server reads that as "don't fast-upload" (the opt-in default).
const requestUpload = async (tryFast: boolean): Promise<NTV2UploadRespBody> => {
const body: NTV2UploadRichMediaReq = {
reqHead: {
common: { requestId: params.requestId, command: 100 },
scene: {
requestType: 2,
businessType: params.businessType,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
client: { agentType: 2 },
},
upload: {
uploadInfo: params.uploadInfo,
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
clientSeq: 0,
noNeedCompatMsg: false,
},
upload: {
uploadInfo: params.uploadInfo,
tryFastUploadCompleted: tryFast,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error(`${label} upload response body missing`);
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
}
const upload = uploadBody.upload;
if (!upload) throw new Error(`${label} upload response body missing`);
return upload;
};
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error(`${label} upload response body missing`);
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
}
const upload = uploadBody.upload;
if (!upload) throw new Error(`${label} upload response body missing`);
// Highway PUTs. Session is lazily fetched and cached — video does two
// PUTs (main + thumb) and shouldn't pay for two sessions.
// PUTs (main + thumb) and shouldn't pay for two sessions, and a forced
// retry shouldn't re-fetch it either.
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
session ??= await fetchHighwaySession(bridge);
return session;
};
let didPut = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
// Either the server fast-pathed this sub-file (no uKey) or msgInfo is
// missing entirely; either way nothing to push.
if (!uKey || !upload.msgInfo) continue;
// Run whatever PUTs the given `upload` response asks for. Returns true
// when a sub-file flagged `forceFullOnFastPath` was fast-pathed by the
// server (no uKey) while we hold real bytes for it — the caller uses
// that to force a non-fast-upload retry.
const runPuts = async (upload: NTV2UploadRespBody): Promise<boolean> => {
let didPut = false;
let staleFastPath = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
// No uKey: the server fast-pathed this sub-file (or msgInfo is absent
// entirely). When we actually hold bytes for it, the server is
// reusing a cached resource — surface it, and flag a stale fast-path
// when the caller asked us to distrust it for this sub-file.
if (!uKey || !upload.msgInfo) {
if (!uKey && upload.msgInfo && sub.bytes.length > 0) {
log.debug('%s fast-upload hit for sub=%s (server reusing cached resource)', label, String(sub.source));
if (sub.forceFullOnFastPath) staleFastPath = true;
}
continue;
}
if (sub.bytes.length === 0) {
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
continue;
if (sub.bytes.length === 0) {
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
continue;
}
if (!target) continue;
const extend = buildHighwayExtend(
uKey,
upload.msgInfo,
target.ipv4s ?? [],
sub.sha1,
sub.subFileIndex ?? 0,
);
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
const t0 = Date.now();
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
log.debug('%s PUT done in %dms', label, Date.now() - t0);
didPut = true;
}
if (!target) continue;
if (!didPut) {
log.debug('%s fast-upload hit (server already had bytes)', label);
}
return staleFastPath;
};
const extend = buildHighwayExtend(
uKey,
upload.msgInfo,
target.ipv4s ?? [],
sub.sha1,
sub.subFileIndex ?? 0,
);
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
const t0 = Date.now();
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
log.debug('%s PUT done in %dms', label, Date.now() - t0);
didPut = true;
}
let upload = await requestUpload(true);
const staleFastPath = await runPuts(upload);
if (!didPut) {
log.debug('%s fast-upload hit (server already had bytes)', label);
// A flagged sub-file (video main) was fast-pathed to a server resource
// that may have expired. Re-issue without fast-upload so the server
// allocates a fresh resource and demands the bytes, then redo the PUTs
// against that response — the returned `upload` (and its msgInfo) must
// be the one we actually pushed bytes to.
if (staleFastPath) {
log.debug('%s forcing full upload — fast-path resource may be stale/expired', label);
upload = await requestUpload(false);
const stillFastPathed = await runPuts(upload);
if (stillFastPathed) {
log.debug('%s server still fast-pathed after forcing full upload — resource may remain stale', label);
}
}
return upload;

View File

@@ -443,6 +443,12 @@ export async function uploadVideoMsgInfo(
sha1: video.sha1Blocks,
subFileIndex: 0,
fastOnlyError: 'video fast-upload not available (server requires bytes)',
// Distrust a server fast-path for the main video: group/c2c video
// resources expire server-side, so reusing a cached object can show
// "资源已过期" on the receiver even though the send "succeeded".
// When we hold the real bytes, force a fresh full upload instead.
// (Forwarding carries no bytes, so this never fires there.) See #145.
forceFullOnFastPath: true,
},
{
source: 0, // upload.subFileInfos[0]

View File

@@ -105,6 +105,10 @@ export class IdentityService {
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private readonly groups_ = new Map<number, QQGroupInfo>();
// groupUin → approval msgseq from a private "qun.invite" card's jumpUrl.
// The 0x10c8 approval for a bot self-invite needs THIS sequence (with
// eventType=2); the MSF invite push never carries it. See issue #125.
private readonly groupInviteCardSeqs_ = new Map<number, number>();
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
private readonly uinByUid = new Map<string, number>();
@@ -341,6 +345,20 @@ export class IdentityService {
this.hydrateActiveMembersForGroups(groups.map((group) => group.groupId));
}
/**
* Drop a single group from the roster after the bot leaves/is removed, so
* `get_group_list` and member lookups stop returning a group we're no longer
* in (#133). Removes the in-memory entry and marks the DB row inactive so it
* doesn't resurrect on the next load (the server refetch won't include it).
*/
forgetGroup(groupId: number): void {
this.groups_.delete(groupId);
this.runWrite('forget group', () => {
this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE group_id = ?')
.run(nowSeconds(), groupId);
});
}
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
this.setGroupMembersInMemory(groupId, members);
for (const member of members) this.rememberUidUin(member.uid, member.uin);
@@ -381,6 +399,17 @@ export class IdentityService {
})));
}
/** Remember the approval msgseq carried by a private "qun.invite" card's
* jumpUrl, keyed by group. `set_group_add_request` reads it back to approve
* a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence);
}
getGroupInviteCardSequence(groupUin: number): number | undefined {
return this.groupInviteCardSeqs_.get(groupUin);
}
rememberGroupRequests(requests: GroupRequestInfo[]): void {
for (const request of requests) {
this.rememberUidUin(request.targetUid, request.targetUin);

View File

@@ -2,7 +2,37 @@ import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
/**
* A private "qun.invite" ark card (someone DMs the bot a group-invite card)
* carries the only sequence the server accepts when the bot later approves the
* invite via 0x10c8 — the `msgseq` embedded in its `mqqapi://group/invite_join`
* jumpUrl, applied with eventType=2 / filtered=false. The MSF invite push
* (PkgType 87) never carries it. Parse it out so `set_group_add_request` can
* use it. See issue #125.
*/
function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: number } | null {
if (!jsonText.includes('group/invite_join')) return null;
const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/);
if (!m) return null;
const query = m[0].split('?')[1] ?? '';
const params = new URLSearchParams(query);
const groupUin = Number(params.get('groupcode') ?? 0);
const sequence = Number(params.get('msgseq') ?? 0);
if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) return null;
if (groupUin <= 0 || sequence <= 0) return null;
return { groupUin, sequence };
}
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const elements = decodeRichBody(ctx.body, false);
// Stash the approval msgseq from a private group-invite card so a later
// `set_group_add_request` can approve a bot self-invite (issue #125).
for (const el of elements) {
if (el.type === 'json' && typeof el.text === 'string') {
const card = parseGroupInviteCard(el.text);
if (card) ctx.identity.rememberGroupInviteCardSequence(card.groupUin, card.sequence);
}
}
const ev: FriendMessage = {
kind: 'friend_message',
time: ctx.head.timestamp,
@@ -10,7 +40,7 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements: decodeRichBody(ctx.body, false),
elements,
senderNick: '',
};
if (ctx.responseHead?.forward?.friendName) {

View File

@@ -21,6 +21,9 @@ import { decodeGroupMessage } from './decoders/group-message';
import { decodeTempMessage } from './decoders/temp-message';
import { PkgType } from './enums';
import { MsgPushRegistry } from './registry';
import { SysMsgDedup } from './sysmsg-dedup';
export { SysMsgDedup } from './sysmsg-dedup';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from './fetch-c2c-history';
@@ -80,11 +83,15 @@ function describeUndecodedBody(body: PushMsgBody | undefined): string {
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
}
export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] {
export function parseMsgPush(
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
): QQEventVariant[] {
const ctx = buildContext(pkt, identity);
if (!ctx) return [];
const events = registry.decode(ctx);
return events.filter((ev) => {
const out = events.filter((ev) => {
if (!MESSAGE_KINDS.has(ev.kind)) return true;
// C2C control/system signal (#102): QQ NT routes these via OnRecvSysMsg and
// never shows them as a bubble. Drop by (msgType, c2cCmd) regardless of body
@@ -111,4 +118,21 @@ export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEven
}
return false;
});
// #137: mirror QQ NT `sys_msg_mgr.cc::ProcessRecvSysMsg` global-key dedup.
// The server pushes some system notices twice (e.g. inviting an official
// robot → two `group_member_increase`); the kernel drops the duplicate by
// (peer, seq, random) before any listener sees it, but we read the raw
// OlPush, so we replicate the drop. Scoped to system pushes only — chat
// messages have their own NT dedup path and the forward re-parse re-runs
// this without a tracker. A push that decodes to a message kind, or to
// nothing, is never deduped here.
if (dedup && out.length > 0 && out.every((ev) => !MESSAGE_KINDS.has(ev.kind))) {
if (dedup.seenDuplicate(ctx.head, ctx.fromUin)) {
log.debug('dropped duplicate system push (kinds=%s seq=%d from=%d msgType=%d msgId=%d)',
out.map((ev) => ev.kind).join(','), ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.msgId);
return [];
}
}
return out;
}

View File

@@ -9,9 +9,8 @@ import type {
NotOnlineImage,
QFaceExtra,
QSmallFaceExtra,
SrcMsgPbReserve,
} from '@snowluma/proto-defs/element';
import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
import type { FileExtra, MessageBody, PushMsgBody as PushMsgBodyFull, RichText } from '@snowluma/proto-defs/message';
import { decompressData, makeImageUrl } from './helpers';
type ElemDecoded = Elem;
@@ -22,7 +21,7 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean):
const elements: MessageElement[] = [];
if (body?.richText) {
const rt = body.richText;
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[], isGroup));
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
extractRichtextExtras(rt, elements, isGroup);
}
if (body?.msgContent && body.msgContent.length > 0) {
@@ -31,9 +30,30 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean):
return elements;
}
function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement[] {
function convertElements(elems: ElemDecoded[]): MessageElement[] {
const result: MessageElement[] = [];
let skipNext = false;
// [#146] A QQ mini-program / ark share (B站 video, QQ 小程序, …) arrives as a
// `lightApp`/`richMsg` card element plus a plain `text` element carrying QQ's
// graceful-degradation compat string ("当前QQ版本不支持此应用,请升级") — the text
// protocol-old clients render instead of the card. The text element has NO wire
// marker distinguishing it (confirmed on-target: no pbReserve / attr6Buf), and
// the receiver binary contains none of these strings, so QQ does NOT match by
// content. Instead QQ NT's kernel codec (msg_codec_mgr) collapses the message
// to a single ark element — the sibling text is never emitted (verified by RE:
// wrapper.linux.node has no fallback strings; NapCat maps kernel elements 1:1
// with no ark-aware skip yet surfaces only the card). We mirror that structural
// rule: when a card is present, drop sibling plain `text`. `@`/reply/face etc.
// are not plain text and survive. `richMsg` covers json (svc=1) and xml (svc=35)
// cards alike.
const hasCard = elems.some((e) => e.lightApp || e.richMsg);
// [#127] A QQ NT reply carries the replied sender as a structural auto-mention
// (MentionExtra.type=2, uin=0) right after srcMsg, followed by a blank
// separator text. Both are part of the reply wire shape, not user content —
// drop them so they aren't reported as a spurious @ + empty segment. A real
// user @ carries a non-zero MentionExtra.uin, so it's preserved.
let sawReply = false;
let dropNextBlankText = false;
for (const elem of elems) {
if (skipNext) { skipNext = false; continue; }
@@ -46,12 +66,49 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement
// Lagrange's `Sequence = reserve.FriendSequence ?? OrigSeqs[0]`
// (ForwardEntity.cs). Group replies keep origSeqs[0] (the shared group seq).
if (elem.srcMsg) {
let replySeq = elem.srcMsg.origSeqs?.[0] ?? 0;
if (!isGroup && elem.srcMsg.pbReserve && elem.srcMsg.pbReserve.length > 0) {
const reserve = protobuf_decode<SrcMsgPbReserve>(elem.srcMsg.pbReserve);
if (reserve.friendSequence) replySeq = reserve.friendSequence;
// The reply resolves to srcMsg.origSeqs[0] — for BOTH group (shared group
// seq) and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals
// the quoted message's head.sequence, i.e. the seq its message_id is
// hashed from. reserve.friendSequence is a small friend-relationship
// counter that does NOT match (e.g. 25 vs a head.sequence of 12707), so
// the earlier `friendSequence` override made reply.id != the quoted
// message_id: get_msg(reply_id) missed and a quoted File's content came
// back empty.
const src = elem.srcMsg;
const replySeq = src.origSeqs?.[0] ?? 0;
if (replySeq > 0) {
const reply: MessageElement = { type: 'reply', replySeq };
if (src.senderUin) reply.replySenderUin = Number(src.senderUin);
if (src.time) reply.replyTime = src.time;
// Decode the quoted message's own elements (SrcMsg.elems, field 5) so a
// backfill can reconstruct it locally if it isn't in the store / server.
if (src.elemsRaw?.length) {
const decoded: ElemDecoded[] = [];
for (const raw of src.elemsRaw) {
try { decoded.push(protobuf_decode<Elem>(raw)); } catch { /* skip corrupt elem */ }
}
if (decoded.length) reply.replyElements = convertElements(decoded);
}
// A C2C quoted FILE lives in RichText.notOnlineFile (message level), not
// in elems[] — recover it from sourceMsg (field 9) when elems carried no
// file, so a quoted file's content survives into get_msg (#124).
if (src.sourceMsg?.length && !reply.replyElements?.some((e) => e.type === 'file')) {
try {
const pmsg = protobuf_decode<PushMsgBodyFull>(src.sourceMsg);
const nof = pmsg?.body?.richText?.notOnlineFile;
if (nof?.fileName) {
(reply.replyElements ??= []).push({
type: 'file',
fileName: nof.fileName,
fileSize: nof.fileSize !== undefined ? Number(nof.fileSize) : 0,
fileId: nof.fileUuid ?? '',
});
}
} catch { /* sourceMsg decode is best-effort */ }
}
result.push(reply);
}
if (replySeq > 0) result.push({ type: 'reply', replySeq });
sawReply = true;
}
// Text (with possible @ detection)
@@ -64,6 +121,17 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
// [#127] drop the reply's structural auto-mention (type=2, uin=0) and the
// blank separator text right after it; keep real @s (non-zero uin).
if (sawReply && mention && mention.type === 2 && (mention.uin ?? 0) === 0) {
dropNextBlankText = true;
continue;
}
if (dropNextBlankText) {
dropNextBlankText = false;
if (!hasMention && (t.str ?? '').trim() === '') continue;
}
if (hasAttr6 || hasMention) {
const me: MessageElement = { type: 'at', text: t.str ?? '' };
if (hasAttr6) {
@@ -77,6 +145,9 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement
result.push(me);
} else {
const text = t.str ?? '';
// [#146] drop QQ's ark-compat fallback text — structurally, like the
// kernel codec: a card message collapses to just the card element.
if (text && hasCard) continue;
if (text) result.push({ type: 'text', text });
}
}

View File

@@ -0,0 +1,59 @@
import type { MsgPushHead } from './context';
/**
* Mirrors QQ NT's system-message dedup so SnowLuma stops double-reporting the
* duplicate sys pushes the server emits for some events (#137: inviting an
* official robot pushes the `group_member_increase` notice twice → two
* `notice.group_increase`; a normal member is pushed once).
*
* RE of `wrapper.linux.node` — `sys_msg_mgr.cc::ProcessRecvSysMsg`
* (`sub_37BADE0`): every received system message is keyed and looked up in a
* per-account set; an already-seen key is logged ("on recv sys msg, ignore dup
* msg … global_key={}", sys_msg_mgr.cc:467) and the whole message is dropped
* before the UI / JS listeners ever see it. The key (`sub_37BC4E0`) is
*
* global_key = `{peerUid}_{chatType}_{msg_seq}_{random}`
*
* whose per-message discriminators are `msg_seq` (attr 40003 = contentHead
* field 5) and `random` (attr 40002 = contentHead field 4) — exactly
* {@link MsgPushHead.sequence} and {@link MsgPushHead.msgId} here
* (`msg_header_codec_helper.cc` sub_37C8AD0). Kernel-based bots (NapCat /
* LLOneBot) receive events *after* this dedup; SnowLuma reads the raw OlPush
* *before* it, so we replicate it here.
*
* We dedup at the push level (drop the whole duplicate, like NT) using the
* fields already on the head plus `fromUin` for peer scoping (a stand-in for
* peerUid — `msg_seq` can be per-conversation, so the peer keeps two groups'
* pushes from colliding; `random`/`msgId` makes the collision astronomically
* unlikely anyway). A push with no server identity (`sequence` or `msgId` 0) is
* never deduped — without a real per-message id we cannot distinguish a true
* duplicate from two distinct events, and dropping then would be a regression.
*/
export class SysMsgDedup {
private readonly seen = new Set<string>();
// Fixed-capacity ring of keys for O(1) bounded eviction (oldest-out). System
// pushes are low-frequency, so a duplicate always lands within a few entries
// of its original — eviction only matters far beyond the dup window.
private readonly ring: (string | undefined)[];
private cursor = 0;
constructor(private readonly capacity = 1024) {
this.ring = new Array<string | undefined>(capacity);
}
/**
* Returns true if a system push with this identity was already seen (caller
* should drop it); otherwise records it and returns false.
*/
seenDuplicate(head: Pick<MsgPushHead, 'msgType' | 'subType' | 'sequence' | 'msgId'>, fromUin: number): boolean {
if (head.sequence === 0 || head.msgId === 0) return false;
const key = `${head.msgType}:${head.subType}:${fromUin}:${head.sequence}:${head.msgId}`;
if (this.seen.has(key)) return true;
const evicted = this.ring[this.cursor];
if (evicted !== undefined) this.seen.delete(evicted);
this.ring[this.cursor] = key;
this.seen.add(key);
this.cursor = (this.cursor + 1) % this.capacity;
return false;
}
}

View File

@@ -1,8 +1,7 @@
// 0x9130_0 — getBuddyRecommendContactArkJson: ask the server to build a
// 0x12b6_0 — getBuddyRecommendContactArkJson: ask the server to build a
// "recommend contact" ARK share card for a friend (by uin). Returns the
// ark JSON string the card is rendered from. RE'd from QQNT
// buddy_recommend_contact_ark_json.cc (EncodeRequest writes uin/phone/jump_url;
// DecodeResponse reads field 1 = ark json). uin-form OIDB (envelope reserved=1).
// ark JSON string the card is rendered from. The request body writes
// uin/phone/jump_url; response body field 1 is the ark string.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
@@ -12,22 +11,22 @@ import type {
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace GetBuddyRecommendArk {
export const command = 0x9130;
export const command = 0x12B6;
export const subCommand = 0;
export const uinForm = true;
export const uinForm = false;
export interface Params { userId: number; phoneNumber?: string }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbBuddyRecommendArkReq => ({
uin: p.userId,
phoneNum: p.phoneNumber ?? '',
phoneNumber: p.phoneNumber || '-',
// Client-side jump_url the kernel hard-codes alongside the uin; the
// server echoes it into the card. Mirrors the NT template exactly.
jumpUrl: `mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=${p.userId}`,
});
export const deserialize = (_ctx: Deps, body: OidbBuddyRecommendArkResp): string => body.arkJson ?? '';
export const deserialize = (_ctx: Deps, body: OidbBuddyRecommendArkResp): string => body.ark ?? '';
export const encode = (env: OidbBase<OidbBuddyRecommendArkReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbBuddyRecommendArkReq>>(env);

View File

@@ -20,6 +20,9 @@ export namespace SetSpecialTitle {
targetUid: await ctx.resolveUserUid(p.userId, p.groupId),
specialTitle: p.title,
expireTime: -1,
// Must mirror specialTitle, or the server accepts the request (errorCode 0)
// but silently never applies the title (see OidbSpecialTitleBody note).
uinName: p.title,
},
});

View File

@@ -82,6 +82,69 @@ describe('decodeRichBody / forward LightApp', () => {
expect(typeof (out[0] as any).text).toBe('string');
});
// [#146] A QQ mini-program / ark share (e.g. a B站 video card) arrives as a
// `lightApp` ark element followed by a plain `text` element carrying QQ's
// graceful-degradation compat string ("当前QQ版本不支持此应用,请升级") — the
// text the protocol attaches for clients too old to render the ark. QQ NT and
// the kernel-backed bridges (NapCat) drop it and surface only the card. The
// captured wire is exactly: [lightApp, text(fallback), generalFlags, {}, extraInfo].
it('[#146] drops QQ ark-compat fallback text sibling of a mini-app card', () => {
const ark = {
app: 'com.tencent.miniapp_01',
prompt: '[QQ小程序]【危机合约】平民3人50',
meta: { detail_1: { appid: '1109937557', title: '哔哩哔哩', desc: '【危机合约】平民3人50' } },
};
const body: MessageBody = {
richText: {
elems: [
{ lightApp: { data: lightAppBytes(ark) } } as any,
{ text: { str: '当前QQ版本不支持此应用,请升级' } } as any,
{ generalFlags: {} } as any,
{} as any,
{ extraInfo: {} } as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out).toHaveLength(1);
expect(out[0]!.type).toBe('json');
expect(JSON.parse((out[0] as any).text).meta.detail_1.title).toBe('哔哩哔哩');
});
// RE of wrapper.linux.node confirmed QQ's kernel codec (msg_codec_mgr) has no
// fallback strings and collapses a card message to a single ark element —
// ANY sibling plain text is dropped, not just the known compat string. We
// mirror that structural rule rather than content-matching (which would break
// when Tencent reworded the string). NapCat shows the same: it maps kernel
// elements 1:1, and the kernel already dropped the text.
it('[#146] drops any sibling plain text beside a card (structural, matches QQ kernel)', () => {
const body: MessageBody = {
richText: {
elems: [
{ lightApp: { data: lightAppBytes({ app: 'com.tencent.miniapp_01', meta: {} }) } } as any,
{ text: { str: '快看这个视频' } } as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out.map((e) => e.type)).toEqual(['json']);
});
// Scope guard: only PLAIN text is dropped beside a card. A real @ mention
// (non-zero uin) is not plain text and must survive.
it('[#146] keeps a genuine @ mention beside a card', () => {
const body: MessageBody = {
richText: {
elems: [
{ lightApp: { data: lightAppBytes({ app: 'com.tencent.miniapp_01', meta: {} }) } } as any,
{ text: { str: '@someone', attr6Buf: new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0]) } } as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out.map((e) => e.type)).toEqual(['json', 'at']);
});
it('falls back to {type:"json"} when com.tencent.multimsg is missing resid (malformed)', () => {
const body: MessageBody = {
richText: {
@@ -165,13 +228,15 @@ describe('decodeRichBody / market face', () => {
});
});
// Reply identity for c2c: a friend's reply carries the per-sender
// clientSequence in srcMsg.origSeqs[0], but the *canonical* replied-to sequence
// (the one the original message is keyed by) is srcMsg.pbReserve.friendSequence.
// Reading origSeqs[0] made get_msg on the quoted message miss ("无法解析申请信息").
describe('decodeRichBody / reply uses friendSequence for c2c', () => {
const CLIENT_SEQ = 23188; // origSeqs[0] — per-sender clientSequence
const FRIEND_SEQ = 888; // pbReserve.friendSequence — canonical replied-to seq
// Reply identity for c2c: the replied-to sequence is srcMsg.origSeqs[0] for BOTH
// group and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals the
// quoted message's head.sequence — i.e. the seq its message_id is hashed from —
// while pbReserve.friendSequence is a small friend-relationship counter that does
// NOT match (e.g. 25 vs a head.sequence of 12707). Reading friendSequence made
// reply.id != the quoted message_id, so get_msg(reply_id) missed.
describe('decodeRichBody / reply uses origSeqs[0] for c2c', () => {
const CLIENT_SEQ = 23188; // origSeqs[0] — the quoted message's head.sequence
const FRIEND_SEQ = 888; // pbReserve.friendSequence — a small unrelated counter, ignored
function replyBody(): MessageBody {
return {
@@ -188,8 +253,9 @@ describe('decodeRichBody / reply uses friendSequence for c2c', () => {
};
}
it('c2c: replySeq = friendSequence, not origSeqs[0]', () => {
expect(decodeRichBody(replyBody(), false)).toContainEqual({ type: 'reply', replySeq: FRIEND_SEQ });
it('c2c: replySeq = origSeqs[0], not friendSequence (#114/#124)', () => {
expect(decodeRichBody(replyBody(), false)).toContainEqual({ type: 'reply', replySeq: CLIENT_SEQ });
expect(FRIEND_SEQ).not.toBe(CLIENT_SEQ); // guard: the two must differ for this to mean anything
});
it('group: replySeq = origSeqs[0] (friendSequence ignored)', () => {

View File

@@ -0,0 +1,118 @@
// Regression for #137: inviting an official robot (e.g. 2854207029) into a
// group makes QQ push the `group_member_increase` notice TWICE, so SnowLuma
// reported two `notice.group_increase` while a normal member produced one.
// QQ NT dedups system messages in `sys_msg_mgr.cc::ProcessRecvSysMsg` by a
// global key whose per-message discriminators are msg_seq (contentHead field 5
// = head.sequence) and random (contentHead field 4 = head.msgId); kernel-based
// bots see events only after that dedup. SnowLuma reads the raw OlPush, so
// parseMsgPush must replicate the drop for system pushes — but only when given
// a dedup tracker (the live path), and never for chat messages.
import { describe, expect, it } from 'vitest';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { protobuf_encode } from '@snowluma/proton';
import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import type { GroupChange } from '@snowluma/proto-defs/notify';
import type { IdentityService } from '../../src/identity-service';
import { parseMsgPush, SysMsgDedup } from '../../src/msg-push';
const identity = { findUinByUid: () => null, findFriend: () => undefined } as unknown as IdentityService;
function pushPacket(message: PushMsgBody): PacketInfo {
return {
pid: 0,
uin: '2000000001',
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: protobuf_encode<PushMsg>({ message }),
};
}
// A type-33 group member-increase push (the #137 shape). `memberUid` is a
// numeric string so resolveUidToUin returns it without touching identity.
function memberIncreasePush(opts: { groupId: number; memberUin: number; sequence: number; msgId: number }): PacketInfo {
return pushPacket({
responseHead: { fromUin: opts.groupId, fromUid: '' },
contentHead: { msgType: 33, subType: 0, sequence: opts.sequence, timestamp: 1781540572, msgId: opts.msgId },
body: { msgContent: protobuf_encode<GroupChange>({ groupUin: opts.groupId, memberUid: String(opts.memberUin) }) },
});
}
describe('SysMsgDedup', () => {
it('flags the second push with the same (msgType, subType, fromUin, seq, msgId)', () => {
const d = new SysMsgDedup();
const head = { msgType: 33, subType: 0, sequence: 500, msgId: 12345 };
expect(d.seenDuplicate(head, 700)).toBe(false);
expect(d.seenDuplicate(head, 700)).toBe(true);
});
it('treats a different seq, msgId, type, or peer as a distinct push', () => {
const d = new SysMsgDedup();
const base = { msgType: 33, subType: 0, sequence: 500, msgId: 12345 };
expect(d.seenDuplicate(base, 700)).toBe(false);
expect(d.seenDuplicate({ ...base, sequence: 501 }, 700)).toBe(false);
expect(d.seenDuplicate({ ...base, msgId: 99999 }, 700)).toBe(false);
expect(d.seenDuplicate({ ...base, msgType: 34 }, 700)).toBe(false);
expect(d.seenDuplicate(base, 701)).toBe(false);
});
it('never dedups a push with no server identity (seq or msgId 0)', () => {
const d = new SysMsgDedup();
expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 0, msgId: 0 }, 700)).toBe(false);
expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 0, msgId: 0 }, 700)).toBe(false);
expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 5, msgId: 0 }, 700)).toBe(false);
expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 0, msgId: 5 }, 700)).toBe(false);
});
it('evicts the oldest key once capacity is exceeded (bounded memory)', () => {
const d = new SysMsgDedup(2);
const k = (sequence: number) => ({ msgType: 33, subType: 0, sequence, msgId: 1 });
expect(d.seenDuplicate(k(1), 1)).toBe(false); // [1]
expect(d.seenDuplicate(k(2), 1)).toBe(false); // [1,2]
expect(d.seenDuplicate(k(3), 1)).toBe(false); // [2,3] — evicts 1
expect(d.seenDuplicate(k(1), 1)).toBe(false); // 1 was evicted → seen as new again
expect(d.seenDuplicate(k(3), 1)).toBe(true); // 3 still tracked
});
});
describe('parseMsgPush — system-push dedup (#137)', () => {
it('drops the second identical official-robot member-increase push', () => {
const dedup = new SysMsgDedup();
const push = () => memberIncreasePush({ groupId: 700, memberUin: 2854207029, sequence: 800, msgId: 555 });
const first = parseMsgPush(push(), identity, dedup);
expect(first).toHaveLength(1);
expect(first[0]).toMatchObject({ kind: 'group_member_join', groupId: 700, userUin: 2854207029 });
const second = parseMsgPush(push(), identity, dedup);
expect(second).toEqual([]);
});
it('keeps both pushes when no dedup tracker is supplied (forward re-parse path)', () => {
const push = () => memberIncreasePush({ groupId: 700, memberUin: 2854207029, sequence: 800, msgId: 555 });
expect(parseMsgPush(push(), identity)).toHaveLength(1);
expect(parseMsgPush(push(), identity)).toHaveLength(1);
});
it('keeps distinct member-increase events (different members → different seq/msgId)', () => {
const dedup = new SysMsgDedup();
const a = parseMsgPush(memberIncreasePush({ groupId: 700, memberUin: 111, sequence: 800, msgId: 555 }), identity, dedup);
const b = parseMsgPush(memberIncreasePush({ groupId: 700, memberUin: 222, sequence: 801, msgId: 556 }), identity, dedup);
expect(a).toHaveLength(1);
expect(b).toHaveLength(1);
expect(b[0]).toMatchObject({ userUin: 222 });
});
it('does not dedup chat messages, even with an identical (seq, msgId)', () => {
const dedup = new SysMsgDedup();
const chat = (): PacketInfo => pushPacket({
responseHead: { fromUin: 10001, fromUid: 'u_x' },
contentHead: { msgType: 166, subType: 0, sequence: 900, timestamp: 1781540572, msgId: 7 },
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
});
expect(parseMsgPush(chat(), identity, dedup)).toHaveLength(1);
expect(parseMsgPush(chat(), identity, dedup)).toHaveLength(1);
});
});

View File

@@ -6,8 +6,8 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetBuddyRecommendArk } from '../../../src/oidb-services/contacts/get-buddy-recommend-ark';
import { env, v, s } from '../_pb-oracle';
function makeSender(arkJson = '{"app":"com.tencent.contact.lua"}') {
const respEnv: OidbBase<OidbBuddyRecommendArkResp> = { command: 0x9130, subCommand: 0, body: { arkJson } };
function makeSender(ark = '{"app":"com.tencent.contact.lua"}') {
const respEnv: OidbBase<OidbBuddyRecommendArkResp> = { command: 0x12B6, subCommand: 0, body: { ark } };
const r: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<OidbBuddyRecommendArkResp>>(respEnv)),
@@ -16,38 +16,37 @@ function makeSender(arkJson = '{"app":"com.tencent.contact.lua"}') {
}
describe('GetBuddyRecommendArk namespace', () => {
it('declares command 0x9130 sub 0, uin form', () => {
expect(GetBuddyRecommendArk.command).toBe(0x9130);
it('declares command 0x12b6 sub 0, plain OIDB envelope', () => {
expect(GetBuddyRecommendArk.command).toBe(0x12B6);
expect(GetBuddyRecommendArk.subCommand).toBe(0);
expect(GetBuddyRecommendArk.uinForm).toBe(true);
expect(GetBuddyRecommendArk.uinForm).toBe(false);
});
it('serializes uin + the hard-coded jump_url template (phone defaults to empty)', () => {
it('serializes uin + phone placeholder + the hard-coded jump_url template', () => {
const out = GetBuddyRecommendArk.serialize({} as any, { userId: 5 });
expect(out).toMatchObject({ uin: 5, phoneNum: '' });
expect(out).toMatchObject({ uin: 5, phoneNumber: '-' });
expect(out.jumpUrl).toBe('mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=5');
});
it('byte-oracle: routes to 0x9130_0 and locks req tags {1:uin, 2:phone, 3:jumpUrl}', async () => {
it('byte-oracle: routes to 0x12b6_0 and locks req tags {1:uin, 2:phone, 3:jumpUrl}', async () => {
const sender = makeSender();
const ark = await GetBuddyRecommendArk.invoke(sender, { userId: 10000 });
expect(ark).toBe('{"app":"com.tencent.contact.lua"}');
const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x9130_0');
expect(cmd).toBe('OidbSvcTrpcTcp.0x12b6_0');
const jumpUrl = 'mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=10000';
// phoneNum '' is a proto3 default → omitted; only tags 1 + 3 present.
const body = [...v(1, 10000), ...s(3, jumpUrl)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0x9130, 0, body, true));
const body = [...v(1, 10000), ...s(2, '-'), ...s(3, jumpUrl)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0x12B6, 0, body, false));
});
it('includes phone tag 2 when a phone number is provided', () => {
const out = GetBuddyRecommendArk.serialize({} as any, { userId: 7, phoneNumber: '123' });
expect(out.phoneNum).toBe('123');
expect(out.phoneNumber).toBe('123');
});
it('deserialize returns the ark json string ("" when absent)', () => {
expect(GetBuddyRecommendArk.deserialize({} as any, { arkJson: 'x' })).toBe('x');
expect(GetBuddyRecommendArk.deserialize({} as any, { ark: 'x' })).toBe('x');
expect(GetBuddyRecommendArk.deserialize({} as any, {})).toBe('');
});
});

View File

@@ -30,6 +30,8 @@ describe('SetSpecialTitle namespace', () => {
expect(env.body?.groupUin).toBe(12345);
expect(env.body?.body?.targetUid).toBe('resolved-uid');
expect(env.body?.body?.specialTitle).toBe('crown');
// uinName (tag 7) must mirror specialTitle or the server silently no-ops.
expect(env.body?.body?.uinName).toBe('crown');
// -1 (int_32) round-trips as 0xFFFFFFFF after the proton decoder reinterprets.
expect(env.body?.body?.expireTime).toBe(0xFFFFFFFF);
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.10.0",
"version": "1.10.3",
"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.

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.10.0",
"version": "1.10.3",
"private": true,
"type": "module",
"main": "index.mjs",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.10.0",
"version": "1.10.3",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.10.0",
"version": "1.10.3",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",

Some files were not shown because too many files have changed in this diff Show More