Compare commits

...
25 Commits
Author SHA1 Message Date
snowluma-bot[bot] 688402814c Merge pull request #159 from SnowLuma/dev
chore: promote dev → main (7ec74f2)
2026-06-28 14:48:25 +00:00
DrSmoothl 7ec74f2928 chore(release): v1.10.4 2026-06-28 22:48:00 +08:00
DrSmoothl 2b15bc6710 feat(webui): group Settings sidebar into 控制台 / SnowLuma / 平台
The flat tab strip mixed three domains — the dashboard itself, the all-accounts
SnowLuma protocol runtime, and the host/platform. Regroup into 3 labelled
sections (macOS System-Settings idiom): section headers show on the desktop
rail; the mobile strip stays a flat wrap via display:contents. Each group is a
role=group + aria-labelledby; the nav gains an aria-label.

This gives '全局配置' (and future global protocol knobs) a principled home and
ends the mixing. Phase 4 (final) of the global-settings split.
2026-06-28 22:25:39 +08:00
DrSmoothl 196f98e97c feat(webui): global-config settings tab + /api/global-config
Adds a '全局配置' Settings tab that edits config/snowluma.json — the rkey
fallback-server list and the deployment-wide musicSignUrl — backed by a new
bearer-gated GET/POST /api/global-config (load/saveGlobalSettings, then
oneBotManager.reloadGlobalSettings to hot-apply to live instances).

The panel reuses the established settings-panel idiom (Input/Button/Label,
debounced auto-save, flash); rkey servers are an inline add/remove list with
client-side http(s) validation hints. It deliberately does not reconcile inputs
from the server's normalized response (would erase a half-typed URL); a
load-failure shows an error+retry, and the save toast says '无效项已忽略' when
the server would drop an entry.

Removes the now-dead per-UIN musicSignUrl form (moved to global in Phase 2).
Phase 3 of the global-settings split (nav grouping is Phase 4).
2026-06-28 22:16:07 +08:00
DrSmoothl ea1c5ff9eb feat(onebot): migrate musicSignUrl from per-UIN to global config
musicSignUrl is a deployment-wide signing-service endpoint (same for every
account), so it belongs in the global config/snowluma.json next to rkey, not in
per-UIN onebot_<uin>.json.

- GlobalSettings gains musicSignUrl (http(s)-validated, '' = built-in default);
  consumption switches to globalSettings.musicSignUrl and hot-reloads via
  applyGlobalSettings.
- One-shot copy-up at boot (migrateGlobalSettings, called first in main()):
  lifts the first VALID legacy value from any config/onebot*.json into the
  global store. Idempotent via a key-PRESENCE guard, so an intentional
  clear-to-'' is never reverted by a stale legacy value.
- Remove musicSignUrl from per-UIN OneBotConfig (type + parse/serialize).

Phase 2 of the global-settings split. (WebUI form follows in Phase 3.)
2026-06-28 21:38:32 +08:00
DrSmoothl 659970077a refactor(onebot): move rkey fallback from per-UIN to a global config store
The rkey fallback endpoint is deployment infra (one self-hosted server serves
all accounts; fallback rkeys are fungible), so it doesn't belong in per-UIN
onebot_<uin>.json. Introduce config/snowluma.json — a generic home for small
all-accounts SnowLuma settings — and move rkey.fallbackServers there.

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

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

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

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

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

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

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

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

Use a short RKEY_EMPTY_COOLDOWN (10s) whenever no usable image rkey is cached,
keeping the 30s steady-state backoff only once we actually hold one — so a
transient empty fetch self-heals in seconds instead of 30s. (Part A of #156;
remote-server fallback follows.)
2026-06-28 01:25:19 +08:00
DrSmoothl 6c2a3fc325 fix(ci): strip ANSI before matching TRACE in needs-logs bot
The needs-logs workflow tested /\bTRACE\b/i against the raw issue body.
Pasted terminal logs wrap the level in ANSI color codes (\x1b[90mTRACE\x1b[0m);
the trailing 'm' of the color code abuts 'TRACE', so the leading \b never
matches and a log that clearly contains TRACE is wrongly flagged needs-logs
(e.g. #156). Strip ANSI escapes first, and measure the too-short heuristic on
the cleaned text too.
2026-06-28 01:25:03 +08:00
DrSmoothl 5eaac0870c feat(webui): scale notification-channel opt-in to large lists
The per-account 上下线通知渠道 picker rendered every global channel as a
flat toggle row, so 40+ channels produced an unbounded, messy wall inside
通用设置. Rework it into a collapsible control:

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

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

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

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

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

Extract the shared heuristic (isHighwaySizeError / videoNeedsFileFallback
/ splitVideoFileFallback) so private and group stay in sync, and drop the
now-unreachable element-builder video catch. Adds send-video-fallback
tests covering both the known-oversize and remote-error-heuristic paths.
2026-06-27 16:27:33 +08:00
stla 85182795b5 feat(protocol,onebot): raise video size limit with Highway-first fallback (#153)
Round 3: fix hardcoded 4096 MB in error messages
- Use MAX_VIDEO_SIZE_HARD constant instead of hardcoded 4096 MB
- Both throw sites now derive limit from the same constant
2026-06-27 16:10:25 +08:00
DrSmoothl 70fd40e34c chore(mcp): regenerate catalog after returnsSchema backfill 2026-06-26 23:08:38 +08:00
DrSmoothl 0e8a194d4f feat(onebot): backfill returnsSchema on remaining read-only actions (c2: source-proven only) 2026-06-26 23:05:52 +08:00
DrSmoothl d2490787ae feat(onebot): backfill returnsSchema on info/group-info read-only actions 2026-06-26 22:44:10 +08:00
DrSmoothl 0163af979a fix(ci): robust catalog sync (untracked-file guard, mkdir, rebase) + stale-catalog gate 2026-06-26 22:03:42 +08:00
DrSmoothl 75f14540c8 ci: sync action catalog.json to SnowLumaDocs via bot on release 2026-06-26 22:03:42 +08:00
DrSmoothl 5e0d2db8b2 feat(mcp): emit catalog.json twin + carry returnsSchema in catalog 2026-06-26 22:03:42 +08:00
DrSmoothl 18014fb3c5 feat(onebot): backfill returnsSchema on representative read-only actions 2026-06-26 22:03:42 +08:00
DrSmoothl 355cce1e52 feat(onebot): add optional returnsSchema to action doc metadata 2026-06-26 22:03:42 +08:00
游手好闲的言柒 04a9016a7d fix(onebot): strip at segments from private messages (#151)
* fix(onebot): support inline file url/path in send_group/private_msg

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

* fix(onebot): strip at segments from private messages
2026-06-26 21:08:01 +08:00
DrSmoothl cf7de9f7bd chore: update vite version to ^8.0.16 in pnpm-workspace.yaml 2026-06-26 19:59:58 +08:00
69 changed files with 13974 additions and 525 deletions

No files matched your search

+10
View File
@@ -41,3 +41,13 @@ jobs:
- name: Run all package tests
run: pnpm -r --no-bail --if-present test
# The MCP test suite regenerates the action catalog (catalog.ts + the
# catalog.json the docs site consumes). Fail if the committed snapshot
# drifted from the live specs — keeps the API docs from going stale.
- name: Verify generated action catalog is up to date
run: |
if ! git diff --exit-code -- packages/mcp/src/generated; then
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi
+6 -2
View File
@@ -31,10 +31,14 @@ jobs:
const m = body.match(/###\s*TRACE 日志[^\n]*\n([\s\S]*?)(?:\n###\s|$)/);
const section = (m ? m[1] : '').trim();
// 粘贴的终端日志常带 ANSI 颜色码(如 \x1b[90mTRACE\x1b[0m),
// 颜色码结尾的 'm' 紧贴 TRACE 会吃掉 \b 单词边界,先剥掉再判定。
const clean = section.replace(/\x1b\[[0-9;]*m/g, '');
const empty = section === '' || /^_no response_$/i.test(section);
const hasTrace = /\bTRACE\b/i.test(section);
const hasTrace = /\bTRACE\b/i.test(clean);
// 去掉代码围栏后过短,基本等于没给
const stripped = section.replace(/```[a-z]*|```|`/gi, '').trim();
const stripped = clean.replace(/```[a-z]*|```|`/gi, '').trim();
const tooShort = stripped.length < 40;
const ok = !empty && hasTrace && !tooShort;
+114
View File
@@ -0,0 +1,114 @@
name: Sync action catalog to docs
# Regenerates the OneBot action catalog from @snowluma/onebot's specs and commits
# the plain-JSON twin (catalog.json) into the SnowLumaDocs repo, where the docs
# build turns it into the API Reference pages. Runs on main (the release/promote
# target) so the published docs always describe shipped behavior. Uses the same
# SnowLuma bot GitHub App as the promote-dev-to-main flow.
on:
push:
branches: [main]
paths:
- 'packages/onebot/src/actions/**'
- 'packages/onebot/src/action-kit.ts'
- 'packages/onebot/src/action-docs.ts'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: sync-docs-catalog
cancel-in-progress: true
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout SnowLuma
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Generate catalog.json
run: pnpm --filter @snowluma/mcp gen
- name: Validate GitHub App credentials
env:
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
run: |
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
echo 'Configure the same GitHub App used by the promote-dev-to-main flow.' >&2
exit 1
fi
- name: Mint GitHub App installation token (scoped to SnowLumaDocs)
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: SnowLumaDocs
- name: Resolve bot identity
id: bot
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
run: |
set -euo pipefail
bot_login="${APP_SLUG}[bot]"
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
{
echo "login=${bot_login}"
echo "email=${bot_email}"
} >> "${GITHUB_OUTPUT}"
- name: Commit catalog.json to docs repo
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
BOT_LOGIN: ${{ steps.bot.outputs.login }}
BOT_EMAIL: ${{ steps.bot.outputs.email }}
OWNER: ${{ github.repository_owner }}
run: |
set -euo pipefail
src="$(pwd)/packages/mcp/src/generated/catalog.json"
tmp="$(mktemp -d)"
git clone --depth 1 \
"https://x-access-token:${GH_TOKEN}@github.com/${OWNER}/SnowLumaDocs.git" "$tmp"
mkdir -p "$tmp/docs/public/api"
cp "$src" "$tmp/docs/public/api/catalog.json"
cd "$tmp"
git config user.name "${BOT_LOGIN}"
git config user.email "${BOT_EMAIL}"
# Stage first: `git diff --quiet` ignores UNTRACKED files, so on the
# initial sync (catalog.json not yet in the docs repo) the index diff
# is the only reliable change check.
git add docs/public/api/catalog.json
if git diff --cached --quiet; then
echo "::notice::catalog.json unchanged; nothing to sync."
exit 0
fi
git commit -m "chore(api): sync action catalog from SnowLuma@${GITHUB_SHA::7}"
# Single writer, but guard against a concurrent docs commit racing the
# shallow clone: rebase onto the latest main before pushing.
git pull --rebase --depth 1 origin main
git push origin HEAD:main
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.10.3",
"version": "1.10.4",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.10.3",
"version": "1.10.4",
"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).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.10.3",
"version": "1.10.4",
"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).",
+2 -2
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.10.3",
"version": "1.10.4",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -54,7 +54,7 @@
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "^24.12.2",
"cross-env": "^10.1.0",
"hono": "^4.12.21",
"hono": "^4.12.25",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
+43 -1
View File
@@ -9,6 +9,7 @@ import type {
SsoReadedReportReq,
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
@@ -238,6 +239,11 @@ export class MessageApi {
* - `subcmd: 1` — c2c file send command code
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
* - `expireTime` — 7 days from now (Lagrange convention)
*
* Beyond NotOnlineFile (`FileExtra.file`), the message MUST also carry
* `FileExtra.field6` — the server-issued download routing. We obtain it by
* running the 0xE37_800 finalize first; without it the recipient sees
* "文件传输失败" even though PbSendMsg returns ok (issue #157).
*/
async sendC2cFile(
userUin: number,
@@ -247,6 +253,28 @@ export class MessageApi {
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
// Resolve our own uid — needed both for the 0xE37_800 finalize and the
// `field6` download-routing the receiver reads.
let selfUid = this.ctx.identity.selfUid;
if (!selfUid) {
const selfUin = Number.parseInt(this.ctx.identity.uin ?? '', 10);
if (Number.isFinite(selfUin) && selfUin > 0) selfUid = await this.ctx.resolveUserUid(selfUin);
}
if (!selfUid) throw new Error('self uid unavailable for c2c file send');
// Finalize the offline file (0xE37_800) to obtain the server-issued
// download routing. The apply + Highway upload alone leave the file
// un-downloadable; `field6` below carries the credential the recipient
// needs (see finalize-offline-file.ts). Mirrors NapCat's upload→finalize
// →send sequence (issue #157).
const fileHash = info.fileHash ?? '';
const meta = await FinalizeOfflineFile.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: userUid,
fileUuid: info.fileId,
fileHash,
});
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
const fileExtraBytes = protobuf_encode<FileExtra>({
@@ -259,7 +287,21 @@ export class MessageApi {
subcmd: 1,
dangerEvel: 0,
expireTime: nowSec + sevenDaysSec,
fileHash: info.fileHash ?? '',
fileHash,
},
field6: {
field2: {
field1: meta.field110,
fileUuid: info.fileId,
fileName: info.fileName,
field6: meta.field3,
field7: meta.field101,
field8: meta.field100,
timestamp1: meta.timestamp1,
fileHash,
selfUid,
destUid: userUid,
},
},
});
+5
View File
@@ -2,6 +2,7 @@ import { HookManager } from '@snowluma/bridge';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
@@ -28,6 +29,10 @@ process.on('uncaughtException', (error) => {
async function main() {
log.info('SnowLuma starting');
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
// any session (and thus any per-UIN config rewrite) can drop it.
migrateGlobalSettings();
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
+3
View File
@@ -28,6 +28,9 @@ export const BACKUP_FILES: readonly BackupFileSpec[] = [
{ name: 'runtime.json', binary: false, credential: false },
{ name: 'ui.json', binary: false, credential: false },
{ name: 'notifications.json', binary: false, credential: false },
// Global all-accounts SnowLuma settings (rkey fallback servers, …). Same
// class as notifications.json: global, opt-in, non-credential.
{ name: 'snowluma.json', binary: false, credential: false },
{ name: 'cert.pem', binary: false, credential: false },
{ name: 'ui-assets/background', binary: true, credential: false },
{ name: 'webui.json', binary: false, credential: true },
+27
View File
@@ -3,6 +3,7 @@ import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config';
import type { OneBotManager } from '@snowluma/onebot/manager';
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
@@ -1247,6 +1248,32 @@ export async function initWebUI(
});
});
// ─── Global deployment config (config/snowluma.json) ─────────────────────
// All-accounts SnowLuma knobs (rkey fallback servers + musicSignUrl). Saving
// section-merges + normalizes server-side, then hot-reloads every instance.
app.get('/api/global-config', (c) => c.json({ config: loadGlobalSettings() }));
app.post('/api/global-config', async (c) => {
const declaredLen = Number(c.req.header('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > 512 * 1024) {
return c.json({ success: false, message: '配置过大' }, 413);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
try {
const config = saveGlobalSettings(body);
oneBotManager.reloadGlobalSettings();
return c.json({ success: true, config });
} catch (err) {
log.warn('save global config failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
});
// ─── WebUI customization config (config/ui.json) ─────────────────────────
// Appearance (A) + layout (C). The full config is bearer-gated; only the
// cosmetic appearance subset is exposed unauthenticated for the login page.
@@ -3,6 +3,8 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
@@ -64,7 +66,23 @@ describe('Bridge private media routing', () => {
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async sendRawPacket(_cmd: string, body: Uint8Array): Promise<SendPacketResult> {
finalizeCmd: string | null = null;
override async resolveUserUid(uin: number): Promise<string> {
return uin === 10000 ? 'u_self' : `u_${uin}`;
}
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
// The c2c file send first runs the 0xE37_800 finalize, then PbSendMsg.
if (cmd.includes('0xe37_800')) {
this.finalizeCmd = cmd;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<OidbOfflineFileFinalizeResp>>({
body: { body: { metadata: { field3: 11, field100: new Uint8Array([1]), field101: new Uint8Array([2]), field110: 22, timestamp1: 1710000123 } } },
})),
};
}
this.capturedBody = body;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
@@ -118,6 +136,22 @@ describe('Bridge private media routing', () => {
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000));
// issue #157: the finalize (0xE37_800) must run, and its download routing
// must ride along in field6 — without it the recipient can't download.
expect(bridge.finalizeCmd).toBe('OidbSvcTrpcTcp.0xe37_800');
expect(fileExtra?.field6?.field2).toMatchObject({
fileUuid: 'uuid-abc-123',
fileName: 'doc.txt',
fileHash: 'hash-xyz',
selfUid: 'u_self',
destUid: 'u_peer_xyz',
field1: 22, // ← finalize metadata.field110
field6: 11, // ← finalize metadata.field3
timestamp1: 1710000123,
});
expect(fileExtra?.field6?.field2?.field7).toEqual(new Uint8Array([2])); // ← metadata.field101
expect(fileExtra?.field6?.field2?.field8).toEqual(new Uint8Array([1])); // ← metadata.field100
// c2cCmd is left at 0 / undefined — the old `c2cCmd=11` was a
// stale go-cqhttp value the QQ-NT server doesn't recognise on the
// c2c-file path.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.10.3",
"version": "1.10.4",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+7
View File
@@ -29,4 +29,11 @@ it('generates src/generated/catalog.ts from the live action specs', () => {
const dir = new URL('../src/generated/', import.meta.url);
mkdirSync(dir, { recursive: true });
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
// Plain-JSON twin of the catalog, consumed by the docs site (SnowLumaDocs)
// via the sync-docs-catalog workflow. Same data as catalog.ts.
writeFileSync(
new URL('../src/generated/catalog.json', import.meta.url),
JSON.stringify({ actions, categories }, null, 2) + '\n',
);
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2
View File
@@ -21,6 +21,8 @@ export interface CatalogAction {
category?: string;
summary?: string;
returns?: string;
/** JSON Schema for the action's `data` payload (absent when undocumented). */
returnsSchema?: Record<string, unknown>;
/** True only for pure data-fetch actions (no side effects). Drives the
* read/write tool routing: read-only → query_action, else → invoke_action.
* Classified at the source spec by what the action's `run` actually does. */
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.10.3",
"version": "1.10.4",
"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>'`.",
@@ -40,6 +40,10 @@
"types": "./src/config.ts",
"default": "./src/config.ts"
},
"./global-config": {
"types": "./src/global-config.ts",
"default": "./src/global-config.ts"
},
"./types": {
"types": "./src/types.ts",
"default": "./src/types.ts"
+8
View File
@@ -331,6 +331,10 @@ export interface ActionDoc {
category?: string;
summary?: string;
returns?: string;
/** JSON Schema for the `data` payload inside the OneBot envelope (NOT the
* whole envelope). Optional + authored incrementally; absent ⇒ data shape
* is documented only by the prose `returns`. */
returnsSchema?: JsonSchema;
/** True only for pure data-fetch actions (no side effects). Drives the MCP's
* read/write tool routing; defaults to false (treated as a write). */
readOnly: boolean;
@@ -358,6 +362,8 @@ interface ActionDef<S extends Spec> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
/** JSON Schema for the `data` payload (NOT the envelope). See ActionDoc. */
returnsSchema?: JsonSchema;
/** Mark true ONLY for pure data-fetch actions with no side effects. Default
* false = write. Surfaced via describe() into the catalog for the MCP's
* read/write routing. Classify by what `run` actually does, not the name. */
@@ -425,6 +431,7 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
aliases: names.slice(1),
summary: def.summary,
returns: def.returns,
returnsSchema: def.returnsSchema,
readOnly: def.readOnly ?? false,
params: entries.map(([name, field]) => ({ name, ...field.doc })),
invariants: rules.map((rule) => rule.doc),
@@ -450,6 +457,7 @@ interface PresetDef<S extends Spec, Extra> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
returnsSchema?: JsonSchema;
readOnly?: boolean;
params?: S;
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
+388 -3
View File
@@ -325,6 +325,14 @@ export const actions = [
name: 'get_group_msg_history',
summary: '获取群消息历史',
readOnly: true,
returns: '{ messages }:群消息事件对象数组(每项为 OneBot 消息事件,内部字段不固定)。',
returnsSchema: {
type: 'object',
properties: {
messages: { type: 'array', description: '消息事件对象数组', items: { type: 'object' } },
},
required: ['messages'],
},
params: {
// message_id is a signed int32 hash (hashMessageIdInt32) and is
// frequently NEGATIVE — a `{min:0}` validator rejects a real anchor at
@@ -344,6 +352,14 @@ export const actions = [
name: 'get_friend_msg_history',
summary: '获取好友消息历史',
readOnly: true,
returns: '{ messages }:好友消息事件对象数组(每项为 OneBot 消息事件,内部字段不固定)。',
returnsSchema: {
type: 'object',
properties: {
messages: { type: 'array', description: '消息事件对象数组', items: { type: 'object' } },
},
required: ['messages'],
},
params: {
user_id: f.uint(),
// Signed int32 hash, frequently negative — see get_group_msg_history.
@@ -549,6 +565,14 @@ export const actions = [
name: ['fetch_ptt_text', 'get_ptt_text', 'get_record_text'],
summary: '获取语音转文字结果',
readOnly: true,
returns: '{ text }:语音识别出的文本。',
returnsSchema: {
type: 'object',
properties: {
text: { type: 'string', description: '语音转写文本' },
},
required: ['text'],
},
params: {
message_id: f.string().default(''),
},
@@ -569,6 +593,14 @@ export const actions = [
name: 'get_cookies',
summary: '获取 Cookies',
readOnly: true,
returns: '{ cookies }:指定域名的 Cookie 字符串。',
returnsSchema: {
type: 'object',
properties: {
cookies: { type: 'string', description: '该域名的 Cookie 字符串' },
},
required: ['cookies'],
},
params: { domain: f.string().default('qun.qq.com') },
run: async (p, ctx) => {
try {
@@ -584,6 +616,14 @@ export const actions = [
name: 'get_csrf_token',
summary: '获取 CSRF 令牌',
readOnly: true,
returns: '{ token }:CSRF 令牌(bkn,数值)。',
returnsSchema: {
type: 'object',
properties: {
token: { type: 'integer', description: 'CSRF 令牌(bkn)' },
},
required: ['token'],
},
params: {},
run: async (_p, ctx) => {
try {
@@ -599,6 +639,16 @@ export const actions = [
name: 'get_credentials',
summary: '获取凭证',
readOnly: true,
returns: '{ cookies, token, csrf_token }:Cookie 字符串与 CSRF 令牌(token 与 csrf_token 同值)。',
returnsSchema: {
type: 'object',
properties: {
cookies: { type: 'string', description: '该域名的 Cookie 字符串' },
token: { type: 'integer', description: 'CSRF 令牌(bkn)' },
csrf_token: { type: 'integer', description: 'CSRF 令牌(同 token)' },
},
required: ['cookies', 'token', 'csrf_token'],
},
params: { domain: f.string().default('qun.qq.com') },
run: async (p, ctx) => {
try {
@@ -686,6 +736,17 @@ export const actions = [
name: 'get_group_file_system_info',
summary: '获取群文件系统信息',
readOnly: true,
returns: '{ file_count, limit_count, used_space, total_space }:群文件数量与容量信息(used_space 恒 0,total_space 为固定 10GiB 常量)。',
returnsSchema: {
type: 'object',
properties: {
file_count: { type: 'integer', description: '当前文件数' },
limit_count: { type: 'integer', description: '最大文件数' },
used_space: { type: 'integer', description: '已用空间(占位,恒 0)' },
total_space: { type: 'integer', description: '总空间(占位,恒 10GiB)' },
},
required: ['file_count', 'limit_count', 'used_space', 'total_space'],
},
run: async (p, ctx) => {
const info = await ctx.bridge.apis.groupFile.getCount(p.group_id);
return okResponse({
@@ -701,6 +762,14 @@ export const actions = [
name: 'check_url_safely',
summary: '检查链接安全性',
readOnly: true,
returns: '{ level }:安全等级(占位实现,恒为 1)。',
returnsSchema: {
type: 'object',
properties: {
level: { type: 'integer', description: '安全等级(占位,恒 1)' },
},
required: ['level'],
},
params: {},
run: async () => {
return okResponse({ level: 1 });
@@ -772,6 +841,27 @@ export const actions = [
name: 'get_group_ignored_notifies',
summary: '获取被过滤的入群请求',
readOnly: true,
returns: '被过滤的入群请求数组,每项含群号、申请人、邀请人、留言与处理标记。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名称' },
request_id: { type: 'integer', description: '请求序列号' },
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
message: { type: 'string', description: '验证留言' },
checked: { type: 'boolean', description: '是否已处理' },
actor: { type: 'integer', description: '处理人 QQ 号' },
invitor_uin: { type: 'integer', description: '邀请人 QQ 号' },
invitor_nick: { type: 'string', description: '邀请人昵称' },
flag: { type: 'string', description: '处理用 flag(eventType:groupId:targetUid:filtered)' },
},
required: ['group_id', 'group_name', 'request_id', 'requester_uin', 'requester_nick', 'message', 'checked', 'actor', 'invitor_uin', 'invitor_nick', 'flag'],
},
},
params: {},
run: async (_p, ctx) => {
const reqs = await fetchFilteredGroupRequests(ctx);
@@ -798,6 +888,25 @@ export const actions = [
name: 'get_group_ignore_add_request',
summary: '获取被忽略的入群请求(NapCat)',
readOnly: true,
returns: '被忽略的入群请求数组(NapCat 字段命名),每项含请求序列、邀请人、群信息与处理标记。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
request_id: { type: 'integer', description: '请求序列号' },
invitor_uin: { type: 'integer', description: '邀请人 QQ 号' },
invitor_nick: { type: 'string', description: '邀请人昵称' },
group_id: { type: 'integer', description: '群号' },
message: { type: 'string', description: '验证留言' },
group_name: { type: 'string', description: '群名称' },
checked: { type: 'boolean', description: '是否已处理' },
actor: { type: 'integer', description: '处理人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
},
required: ['request_id', 'invitor_uin', 'invitor_nick', 'group_id', 'message', 'group_name', 'checked', 'actor', 'requester_nick'],
},
},
params: {},
run: async (_p, ctx) => {
const reqs = await fetchFilteredGroupRequests(ctx);
@@ -825,6 +934,19 @@ export const actions = [
name: 'get_group_shut_list',
summary: '获取群禁言列表',
readOnly: true,
returns: '仍在禁言中的成员数组,每项含 QQ 号、昵称与禁言到期时间戳(秒)。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '成员 QQ 号' },
nickname: { type: 'string', description: '成员昵称' },
shut_up_time: { type: 'integer', description: '禁言到期时间戳(秒)' },
},
required: ['user_id', 'nickname', 'shut_up_time'],
},
},
run: async (p, ctx) => {
const members = await ctx.bridge.apis.contacts.fetchGroupMemberList(p.group_id);
const nowSec = Math.floor(Date.now() / 1000);
@@ -890,6 +1012,36 @@ export const actions = [
name: 'get_profile_like',
summary: '获取资料点赞',
readOnly: true,
returns: '点赞资料:uid、最近点赞时间、收藏(favoriteInfo)与点赞(voteInfo)统计。',
returnsSchema: {
type: 'object',
properties: {
uid: { type: 'string', description: '用户 uid' },
time: { type: 'integer', description: '最近点赞时间戳' },
favoriteInfo: {
type: 'object',
description: '收藏统计',
properties: {
total_count: { type: 'integer', description: '收藏总数' },
last_time: { type: 'integer', description: '最近收藏时间戳' },
today_count: { type: 'integer', description: '今日收藏数' },
userInfos: { type: 'array', description: '用户列表(恒空)' },
},
},
voteInfo: {
type: 'object',
description: '点赞统计',
properties: {
total_count: { type: 'integer', description: '点赞总数' },
new_count: { type: 'integer', description: '新增点赞数' },
new_nearby_count: { type: 'integer', description: '附近的人新增点赞数' },
last_visit_time: { type: 'integer', description: '最近访问时间戳' },
userInfos: { type: 'array', description: '用户列表(恒空)' },
},
},
},
required: ['uid', 'time', 'favoriteInfo', 'voteInfo'],
},
params: {
// 原实现 user_id 经 asNumber,无校验(0 也透传)。
user_id: f.int({ min: 0 }).default(0),
@@ -910,6 +1062,11 @@ export const actions = [
name: 'fetch_custom_face',
summary: '获取自定义表情',
readOnly: true,
returns: '字符串数组:return_type=url 时为图片 URL,return_type=id 时为 emoji_id。',
returnsSchema: {
type: 'array',
items: { type: 'string', description: '图片 URL 或 emoji_id(取决于 return_type)' },
},
params: {
count: f.int({ min: 0 }).default(10),
// return_type=url 返回图片 URL(默认,给前端显示);
@@ -937,6 +1094,25 @@ export const actions = [
name: 'get_emoji_likes',
summary: '获取表情回应用户',
readOnly: true,
returns: '{ emoji_like_list }:回应该表情的用户列表(nick_name 恒为空串)。',
returnsSchema: {
type: 'object',
properties: {
emoji_like_list: {
type: 'array',
description: '回应用户列表',
items: {
type: 'object',
properties: {
user_id: { type: 'string', description: '用户 QQ 号(字符串)' },
nick_name: { type: 'string', description: '昵称(当前实现恒为空串)' },
},
required: ['user_id', 'nick_name'],
},
},
},
required: ['emoji_like_list'],
},
params: {
message_id: f.messageId(),
emoji_id: f.string({ allowEmpty: false }),
@@ -957,6 +1133,31 @@ export const actions = [
name: 'fetch_emoji_like',
summary: '获取表情回应用户(NapCat 分页)',
readOnly: true,
returns: '分页的表情回应用户列表(NapCat 形状),含分页游标 cookie 与首/末页标记。',
returnsSchema: {
type: 'object',
properties: {
result: { type: 'integer', description: '结果码(恒 0)' },
errMsg: { type: 'string', description: '错误信息(恒空串)' },
emojiLikesList: {
type: 'array',
description: '回应用户列表',
items: {
type: 'object',
properties: {
tinyId: { type: 'string', description: '用户 QQ 号(字符串)' },
nickName: { type: 'string', description: '昵称(恒空串)' },
headUrl: { type: 'string', description: '头像 URL(恒空串)' },
},
required: ['tinyId', 'nickName', 'headUrl'],
},
},
cookie: { type: 'string', description: '下一页游标(末页为空串)' },
isLastPage: { type: 'boolean', description: '是否末页' },
isFirstPage: { type: 'boolean', description: '是否首页' },
},
required: ['result', 'errMsg', 'emojiLikesList', 'cookie', 'isLastPage', 'isFirstPage'],
},
params: {
message_id: f.messageId(),
emojiId: f.string({ allowEmpty: false }),
@@ -1005,6 +1206,8 @@ export const actions = [
name: 'get_recent_contact',
summary: '获取最近会话(占位)',
readOnly: true,
returns: '占位实现,恒返回空数组。',
returnsSchema: { type: 'array', description: '最近会话列表(占位,恒空)' },
params: {
count: f.int({ min: 0 }).default(10),
},
@@ -1021,6 +1224,14 @@ export const actions = [
name: 'get_online_clients',
summary: '获取在线客户端(占位,OneBot v11 形状)',
readOnly: true,
returns: '{ clients }:在线设备列表(占位,clients 恒为空数组)。',
returnsSchema: {
type: 'object',
properties: {
clients: { type: 'array', description: '在线设备列表(占位,恒空)' },
},
required: ['clients'],
},
params: {},
run: async () => {
return okResponse({ clients: [] });
@@ -1036,6 +1247,24 @@ export const actions = [
name: '_get_model_show',
summary: '获取机型展示(兼容 mock)',
readOnly: true,
returns: '数组,每项含 variants(回显请求的机型名与 need_pay 标记)。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
variants: {
type: 'object',
properties: {
model_show: { type: 'string', description: '机型展示名(回显请求的 model,缺省 snowluma)' },
need_pay: { type: 'boolean', description: '是否需付费(恒 false)' },
},
required: ['model_show', 'need_pay'],
},
},
required: ['variants'],
},
},
params: {
model: f.string().default(''),
},
@@ -1058,6 +1287,16 @@ export const actions = [
name: 'get_group_at_all_remain',
summary: '获取群 @全体成员 剩余次数',
readOnly: true,
returns: '{ can_at_all, remain_at_all_count_for_group, remain_at_all_count_for_uin }:@全体可用性与剩余次数。',
returnsSchema: {
type: 'object',
properties: {
can_at_all: { type: 'boolean', description: '当前是否可 @全体成员' },
remain_at_all_count_for_group: { type: 'integer', description: '本群今日剩余 @全体次数' },
remain_at_all_count_for_uin: { type: 'integer', description: '本账号今日剩余 @全体次数' },
},
required: ['can_at_all', 'remain_at_all_count_for_group', 'remain_at_all_count_for_uin'],
},
run: async (p, ctx) => {
try {
const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id);
@@ -1087,6 +1326,16 @@ export const actions = [
name: 'get_clientkey',
summary: '获取 clientkey',
readOnly: true,
returns: '{ clientKey, expireTime, keyIndex }:clientkey 及其过期时间与索引。',
returnsSchema: {
type: 'object',
properties: {
clientKey: { type: 'string', description: 'clientkey' },
expireTime: { type: 'string', description: '过期时间' },
keyIndex: { type: 'string', description: 'key 索引' },
},
required: ['clientKey', 'expireTime', 'keyIndex'],
},
params: {},
run: async (_p, ctx) => {
const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey();
@@ -1109,6 +1358,14 @@ export const actions = [
name: 'share_peer',
summary: '分享用户/群 Ark 卡片',
readOnly: true,
returns: '{ arkMsg }:服务端生成的推荐联系人 Ark 卡片 JSON 字符串。',
returnsSchema: {
type: 'object',
properties: {
arkMsg: { type: 'string', description: 'Ark 卡片 JSON 字符串' },
},
required: ['arkMsg'],
},
params: {
user_id: f.uint().optional(),
group_id: f.uint().optional(),
@@ -1132,6 +1389,14 @@ export const actions = [
name: 'send_ark_share',
summary: '分享用户/群 Ark 卡片(NapCat 标准名)',
readOnly: true,
returns: '{ arkMsg }:服务端生成的推荐联系人 Ark 卡片 JSON 字符串。',
returnsSchema: {
type: 'object',
properties: {
arkMsg: { type: 'string', description: 'Ark 卡片 JSON 字符串' },
},
required: ['arkMsg'],
},
params: {
user_id: f.uint().optional(),
group_id: f.uint().optional(),
@@ -1160,6 +1425,8 @@ export const actions = [
name: 'share_group_ex',
summary: '分享群 Ark 卡片',
readOnly: true,
returns: '服务端生成的群推荐 Ark 卡片 JSON 字符串。',
returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' },
params: { group_id: f.uint() },
run: async (p, ctx) => {
try {
@@ -1173,6 +1440,8 @@ export const actions = [
name: 'send_group_ark_share',
summary: '分享群 Ark 卡片(NapCat 标准名)',
readOnly: true,
returns: '服务端生成的群推荐 Ark 卡片 JSON 字符串。',
returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' },
params: { group_id: f.uint() },
run: async (p, ctx) => {
try {
@@ -1189,6 +1458,21 @@ export const actions = [
name: 'get_doubt_friends_add_request',
summary: '获取可疑好友申请',
readOnly: true,
returns: '可疑好友申请数组,每项含 uid(作为处理用 flag)、昵称、来源、留言与申请时间。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
uid: { type: 'string', description: '申请人 uid(回传作 set_doubt_friends_add_request 的 flag)' },
nick: { type: 'string', description: '申请人昵称' },
source: { type: 'string', description: '申请来源' },
msg: { type: 'string', description: '验证留言' },
reqTime: { type: 'integer', description: '申请时间戳' },
},
required: ['uid', 'nick', 'source', 'msg', 'reqTime'],
},
},
params: { count: f.int({ min: 0 }).default(50) },
run: async (p, ctx) => {
try {
@@ -1251,6 +1535,8 @@ export const actions = [
name: 'get_collection_list',
summary: '获取收藏列表(占位)',
readOnly: true,
returns: '占位实现,恒返回空数组。',
returnsSchema: { type: 'array', description: '收藏列表(占位,恒空)' },
params: {},
run: async () => {
return okResponse([]);
@@ -1391,6 +1677,8 @@ export const actions = [
name: 'nc_get_packet_status',
summary: '获取 packet 状态(占位)',
readOnly: true,
returns: '占位实现,恒返回 null。',
returnsSchema: { type: 'null', description: 'packet 状态(占位,恒 null)' },
params: {},
run: async () => {
return okResponse(null);
@@ -1415,6 +1703,15 @@ export const actions = [
name: 'nc_get_user_status',
summary: '获取用户在线/扩展状态',
readOnly: true,
returns: '{ status, ext_status }:用户在线状态码与扩展状态码。',
returnsSchema: {
type: 'object',
properties: {
status: { type: 'integer', description: '在线状态码' },
ext_status: { type: 'integer', description: '扩展状态码' },
},
required: ['status', 'ext_status'],
},
params: { user_id: f.uint() },
run: async (p, ctx) => {
const status = await ctx.bridge.apis.extras.getStrangerStatus(p.user_id);
@@ -1428,6 +1725,30 @@ export const actions = [
name: 'get_ai_characters',
summary: '获取 AI 语音角色',
readOnly: true,
returns: '按分类分组的 AI 语音角色列表,每组含分类名与角色(id、名称、试听 URL)。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
type: { type: 'string', description: '角色分类名' },
characters: {
type: 'array',
description: '该分类下的角色列表',
items: {
type: 'object',
properties: {
character_id: { type: 'string', description: '角色 ID' },
character_name: { type: 'string', description: '角色显示名' },
preview_url: { type: 'string', description: '试听音频 URL' },
},
required: ['character_id', 'character_name', 'preview_url'],
},
},
},
required: ['type', 'characters'],
},
},
params: { chat_type: f.int({ min: 0 }).default(1) },
run: async (p, ctx) => {
try {
@@ -1535,6 +1856,17 @@ export const actions = [
name: 'get_rkey_server',
summary: '获取 rkey 服务器信息',
readOnly: true,
returns: '{ expired_time, name, private_rkey?, group_rkey? }:rkey 过期时间与(存在时的)私聊/群聊 rkey。',
returnsSchema: {
type: 'object',
properties: {
expired_time: { type: 'integer', description: '过期时间戳(秒)' },
name: { type: 'string', description: '服务器名(恒 SnowLuma)' },
private_rkey: { type: 'string', description: '私聊 rkey(存在时返回)' },
group_rkey: { type: 'string', description: '群聊 rkey(存在时返回)' },
},
required: ['expired_time', 'name'],
},
params: {},
run: async (_p, ctx) => {
if (!ctx.getDownloadRKeys) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
@@ -1570,6 +1902,38 @@ export const actions = [
name: ['ocr_image', '.ocr_image'],
summary: 'OCR 图片(服务端,需图片 URL 或已缓存的图片 file_id)',
readOnly: true,
returns: '{ texts, language }:识别文本数组(含置信度与坐标)与识别语言。',
returnsSchema: {
type: 'object',
properties: {
texts: {
type: 'array',
description: '识别出的文本块',
items: {
type: 'object',
properties: {
text: { type: 'string', description: '文本内容' },
confidence: { type: 'number', description: '置信度' },
coordinates: {
type: 'array',
description: '文本框顶点坐标',
items: {
type: 'object',
properties: {
x: { type: 'number', description: 'X 坐标' },
y: { type: 'number', description: 'Y 坐标' },
},
required: ['x', 'y'],
},
},
},
required: ['text', 'confidence', 'coordinates'],
},
},
language: { type: 'string', description: '识别语言' },
},
required: ['texts', 'language'],
},
params: { image: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
// A passed-in http(s) URL is used verbatim (NOT re-signed) — if it is a
@@ -1671,7 +2035,14 @@ export const actions = [
name: 'get_forward_msg',
summary: '获取合并转发消息(id 或 message_id)',
readOnly: true,
returns: '{ messages }',
returns: '{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件,内部字段不固定)。',
returnsSchema: {
type: 'object',
properties: {
messages: { type: 'array', description: '转发消息节点数组', items: { type: 'object' } },
},
required: ['messages'],
},
params: { id: f.string().optional() },
run: async (p, ctx, raw) => {
let id = p.id || '';
@@ -1736,7 +2107,14 @@ export const actions = [
name: 'translate_en2zh',
summary: '英译中',
readOnly: true,
returns: '{ words }',
returns: '{ words }:与输入等长的中文译文字符串数组。',
returnsSchema: {
type: 'object',
properties: {
words: { type: 'array', description: '译文数组', items: { type: 'string' } },
},
required: ['words'],
},
params: { words: f.raw() },
run: async (p, ctx) => {
const rawWords = p.words;
@@ -2053,7 +2431,14 @@ export const actions = [
name: 'get_fileset_id',
summary: '从分享码/链接获取 fileset_id',
readOnly: true,
returns: '{ fileset_id }',
returns: '{ fileset_id }:解析出的文件集 ID。',
returnsSchema: {
type: 'object',
properties: {
fileset_id: { type: 'string', description: '文件集 ID' },
},
required: ['fileset_id'],
},
params: { share_code: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
+26
View File
@@ -7,6 +7,19 @@ export const actions = [
name: 'get_friend_list',
summary: '获取好友列表',
readOnly: true,
returns: '好友列表数组,每项含 QQ 号、昵称与备注。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
},
params: {},
run: async (_p, ctx) => {
if (ctx.getFriendList) {
@@ -20,6 +33,19 @@ export const actions = [
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
returns: '陌生人资料:QQ 号、昵称、性别、年龄,命中资料时另含等级。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
sex: { type: 'string', description: '性别(male/female/unknown)' },
age: { type: 'integer', description: '年龄' },
qq_level: { type: 'integer', description: 'QQ 等级(仅查到资料时返回)' },
level: { type: 'integer', description: 'QQ 等级,同 qq_level(仅查到资料时返回)' },
},
required: ['user_id', 'nickname', 'sex', 'age'],
},
params: { user_id: f.uint().describe('QQ 号') },
run: async (p, ctx) => {
const userId = p.user_id;
@@ -7,6 +7,21 @@ export const actions = [
groupAction({
name: 'get_group_album_list',
readOnly: true,
returns: '群相册列表数组,每项为一个相册的基本信息。',
returnsSchema: {
type: 'array',
description: '群相册列表',
items: {
type: 'object',
properties: {
id: { type: 'string', description: '相册 id' },
name: { type: 'string', description: '相册名称' },
picNum: { type: 'integer', description: '相册内照片数量' },
createTime: { type: 'integer', description: '相册创建时间(unix 秒)' },
},
required: ['id', 'name', 'picNum', 'createTime'],
},
},
run: async (p, ctx) => {
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
@@ -28,6 +43,29 @@ export const actions = [
groupAction({
name: 'get_qun_album_list',
readOnly: true,
returns: 'NapCat 风格的相册列表封套:{album_list, attach_info, has_more}(本实现 attach_info 恒为空串、has_more 恒为 false)。',
returnsSchema: {
type: 'object',
properties: {
album_list: {
type: 'array',
description: '相册列表',
items: {
type: 'object',
properties: {
album_id: { type: 'string', description: '相册 id' },
album_name: { type: 'string', description: '相册名称' },
create_time: { type: 'integer', description: '相册创建时间(unix 秒)' },
pic_num: { type: 'integer', description: '相册内照片数量' },
},
required: ['album_id', 'album_name', 'create_time', 'pic_num'],
},
},
attach_info: { type: 'string', description: '分页游标(本 web 实现一次取满,恒为空串)' },
has_more: { type: 'boolean', description: '是否还有更多(本 web 实现恒为 false)' },
},
required: ['album_list', 'attach_info', 'has_more'],
},
run: async (p, ctx) => {
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
@@ -69,6 +107,19 @@ export const actions = [
groupAction({
name: 'get_group_album_media_list',
readOnly: true,
returns: '相册媒体列表及下一页分页游标:{mediaList, nextAttachInfo}。',
returnsSchema: {
type: 'object',
properties: {
mediaList: {
type: 'array',
description: '相册媒体项列表(各项字段不固定)',
items: { type: 'object' },
},
nextAttachInfo: { type: 'string', description: '下一页分页游标(空串表示无更多)' },
},
required: ['mediaList', 'nextAttachInfo'],
},
params: {
album_id: f.string({ allowEmpty: false }),
attach_info: f.string().default(''),
+98 -2
View File
@@ -59,7 +59,12 @@ export const actions = [
name: 'get_group_file_url',
summary: '获取群文件下载链接',
readOnly: true,
returns: '{ url: string }',
returns: '群文件下载链接。',
returnsSchema: {
type: 'object',
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
// 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() },
@@ -72,6 +77,49 @@ export const actions = [
name: 'get_group_root_files',
summary: '获取群根目录文件列表',
readOnly: true,
returns: '群文件系统信息(文件与文件夹列表)。',
returnsSchema: {
type: 'object',
properties: {
files: {
type: 'array',
description: '文件列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
file_id: { type: 'string', description: '文件 ID' },
file_name: { type: 'string', description: '文件名' },
busid: { type: 'integer', description: '业务 ID' },
file_size: { type: 'integer', description: '文件大小(字节)' },
upload_time: { type: 'integer', description: '上传时间戳' },
dead_time: { type: 'integer', description: '过期时间戳' },
modify_time: { type: 'integer', description: '修改时间戳' },
download_times: { type: 'integer', description: '下载次数' },
uploader: { type: 'integer', description: '上传者 QQ 号' },
uploader_name: { type: 'string', description: '上传者昵称' },
},
},
},
folders: {
type: 'array',
description: '文件夹列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
folder_id: { type: 'string', description: '文件夹 ID' },
folder_name: { type: 'string', description: '文件夹名' },
create_time: { type: 'integer', description: '创建时间戳' },
creator: { type: 'integer', description: '创建者 QQ 号' },
create_name: { type: 'string', description: '创建者昵称' },
total_file_count: { type: 'integer', description: '文件夹内文件总数' },
},
},
},
},
required: ['files', 'folders'],
},
run: async (p, ctx) => {
return okResponse(await ctx.getGroupFiles(p.group_id, '/'));
},
@@ -81,6 +129,49 @@ export const actions = [
name: 'get_group_files_by_folder',
summary: '获取群子目录文件列表',
readOnly: true,
returns: '群文件系统信息(文件与文件夹列表)。',
returnsSchema: {
type: 'object',
properties: {
files: {
type: 'array',
description: '文件列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
file_id: { type: 'string', description: '文件 ID' },
file_name: { type: 'string', description: '文件名' },
busid: { type: 'integer', description: '业务 ID' },
file_size: { type: 'integer', description: '文件大小(字节)' },
upload_time: { type: 'integer', description: '上传时间戳' },
dead_time: { type: 'integer', description: '过期时间戳' },
modify_time: { type: 'integer', description: '修改时间戳' },
download_times: { type: 'integer', description: '下载次数' },
uploader: { type: 'integer', description: '上传者 QQ 号' },
uploader_name: { type: 'string', description: '上传者昵称' },
},
},
},
folders: {
type: 'array',
description: '文件夹列表',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
folder_id: { type: 'string', description: '文件夹 ID' },
folder_name: { type: 'string', description: '文件夹名' },
create_time: { type: 'integer', description: '创建时间戳' },
creator: { type: 'integer', description: '创建者 QQ 号' },
create_name: { type: 'string', description: '创建者昵称' },
total_file_count: { type: 'integer', description: '文件夹内文件总数' },
},
},
},
},
required: ['files', 'folders'],
},
// folder_id / folder are aliases; first non-empty wins, else '/'.
params: { folder_id: f.string().default(''), folder: f.string().default('') },
run: async (p, ctx) => {
@@ -171,7 +262,12 @@ export const actions = [
name: 'get_private_file_url',
summary: '获取私聊文件下载链接',
readOnly: true,
returns: '{ url: string }',
returns: '私聊文件下载链接。',
returnsSchema: {
type: 'object',
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
// 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
+64
View File
@@ -9,6 +9,20 @@ export const actions = [
name: 'get_group_list',
summary: '获取群列表',
readOnly: true,
returns: '群信息对象数组。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
},
required: ['group_id', 'group_name', 'member_count', 'max_member_count'],
},
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const noCache = p.no_cache;
@@ -23,6 +37,17 @@ export const actions = [
name: 'get_group_info',
summary: '获取群信息',
readOnly: true,
returns: '群信息对象。',
returnsSchema: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
},
required: ['group_id', 'group_name', 'member_count', 'max_member_count'],
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
@@ -39,6 +64,27 @@ export const actions = [
name: 'get_group_member_list',
summary: '获取群成员列表',
readOnly: true,
returns: '群成员信息对象数组。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
card: { type: 'string', description: '群名片' },
sex: { type: 'string', enum: ['male', 'female', 'unknown'], description: '性别' },
age: { type: 'integer', description: '年龄' },
join_time: { type: 'integer', description: '入群时间戳(秒)' },
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
level: { type: 'string', description: '群等级' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
@@ -54,6 +100,24 @@ export const actions = [
name: 'get_group_member_info',
summary: '获取群成员信息',
readOnly: true,
returns: '群成员信息对象。',
returnsSchema: {
type: 'object',
properties: {
group_id: { type: 'integer', description: '群号' },
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
card: { type: 'string', description: '群名片' },
sex: { type: 'string', enum: ['male', 'female', 'unknown'], description: '性别' },
age: { type: 'integer', description: '年龄' },
join_time: { type: 'integer', description: '入群时间戳(秒)' },
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
level: { type: 'string', description: '群等级' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
+40
View File
@@ -9,6 +9,15 @@ export const actions = [
defineAction({
name: 'get_login_info',
readOnly: true,
returns: '当前登录账号的 QQ 号与昵称。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '登录 QQ 号' },
nickname: { type: 'string', description: '登录昵称' },
},
required: ['user_id', 'nickname'],
},
params: {},
run: (_p, ctx) => {
const login = ctx.getLoginInfo();
@@ -19,6 +28,15 @@ export const actions = [
defineAction({
name: 'get_status',
readOnly: true,
returns: '运行状态。`online`/`good` 均表示账号是否在线。',
returnsSchema: {
type: 'object',
properties: {
online: { type: 'boolean', description: '是否在线' },
good: { type: 'boolean', description: '状态是否正常(与 online 一致)' },
},
required: ['online', 'good'],
},
params: {},
run: (_p, ctx) => {
const online = ctx.isOnline();
@@ -29,6 +47,16 @@ export const actions = [
defineAction({
name: 'get_version_info',
readOnly: true,
returns: '实现与协议版本信息。',
returnsSchema: {
type: 'object',
properties: {
app_name: { type: 'string', description: '实现名称(SnowLuma)' },
app_version: { type: 'string', description: '实现版本' },
protocol_version: { type: 'string', description: 'OneBot 协议版本' },
},
required: ['app_name', 'app_version', 'protocol_version'],
},
params: {},
run: () => {
return okResponse({
@@ -42,6 +70,12 @@ export const actions = [
defineAction({
name: 'can_send_image',
readOnly: true,
returns: '能力查询结果。',
returnsSchema: {
type: 'object',
properties: { yes: { type: 'boolean', description: '是否支持发送图片' } },
required: ['yes'],
},
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
@@ -51,6 +85,12 @@ export const actions = [
defineAction({
name: 'can_send_record',
readOnly: true,
returns: '能力查询结果。',
returnsSchema: {
type: 'object',
properties: { yes: { type: 'boolean', description: '是否支持发送语音' } },
required: ['yes'],
},
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
+1
View File
@@ -89,6 +89,7 @@ export const actions = [
name: 'get_msg',
summary: '获取消息',
readOnly: true,
returns: '消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const data = ctx.getMessage(p.message_id);
+48
View File
@@ -10,6 +10,30 @@ export const actions = [
defineAction({
name: 'get_qzone_msg_list',
readOnly: true,
returns: '说说列表对象,含说说总数与本页说说数组。',
returnsSchema: {
type: 'object',
properties: {
total: { type: 'integer', description: '账号说说总数(非本页数量)' },
msglist: {
type: 'array',
description: '本页说说数组',
items: {
type: 'object',
properties: {
tid: { type: 'string', description: '说说 id(delete/comment/like 的句柄)' },
content: { type: 'string', description: '说说正文' },
time: { type: 'integer', description: '发表时间(unix 秒)' },
comment_num: { type: 'integer', description: '评论数' },
is_private: { type: 'boolean', description: '是否仅自己可见' },
images: { type: 'array', items: { type: 'string' }, description: '图片 URL 列表(每图取最大可用变体)' },
},
required: ['tid', 'content', 'time', 'comment_num', 'is_private', 'images'],
},
},
},
required: ['total', 'msglist'],
},
summary: '获取 QQ 空间说说列表(默认机器人自己的空间)',
params: {
target_uin: f.uint().describe('目标 QQ 号,省略则取机器人自己').optional(),
@@ -32,6 +56,30 @@ export const actions = [
defineAction({
name: 'get_qzone_feeds',
readOnly: true,
returns: '好友动态对象,含本页 feed 数组与是否有更多页。',
returnsSchema: {
type: 'object',
properties: {
feeds: {
type: 'array',
description: '本页好友动态数组',
items: {
type: 'object',
properties: {
uin: { type: 'integer', description: '动态作者 QQ 号' },
nickname: { type: 'string', description: '作者昵称' },
time: { type: 'integer', description: '发表时间(unix 秒)' },
appid: { type: 'integer', description: 'Qzone 应用 id(311=说说,4=相册,…)' },
key: { type: 'string', description: 'feed 句柄(Qzone 用于定位该条动态)' },
html: { type: 'string', description: '预渲染 HTML 原样透传' },
},
required: ['uin', 'nickname', 'time', 'appid', 'key', 'html'],
},
},
has_more: { type: 'boolean', description: '服务端是否报告本页之后还有更多页' },
},
required: ['feeds', 'has_more'],
},
summary: '获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)',
params: {
page_num: f.int({ min: 1 }).describe('页码(1 起;仅首页可靠)').default(1),
-5
View File
@@ -61,7 +61,6 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
}],
wsClients: [],
},
musicSignUrl: '',
statusCommand: makeDefaultStatusCommand(),
notifications: { channelIds: [] },
};
@@ -115,7 +114,6 @@ function toJsonObject(config: OneBotConfig): JsonObject {
wsServers: nets.wsServers.map(wsServerToJson),
wsClients: nets.wsClients.map(wsClientToJson),
},
musicSignUrl: config.musicSignUrl ?? '',
statusCommand: {
enabled: config.statusCommand.enabled,
swallow: config.statusCommand.swallow,
@@ -179,12 +177,10 @@ function wsClientToJson(n: WsClientNetwork): JsonObject {
function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
let legacyFormat: MessageFormat | undefined;
let legacyReport: boolean | undefined;
let musicSignUrl = '';
for (const src of sources) {
const mf = parseMessageFormat(src.messageFormat);
if (mf) legacyFormat = mf;
if (typeof src.reportSelfMessage === 'boolean') legacyReport = src.reportSelfMessage;
if (typeof src.musicSignUrl === 'string') musicSignUrl = src.musicSignUrl;
}
const inheritedFormat: MessageFormat = legacyFormat ?? 'array';
const inheritedReport: boolean = legacyReport ?? false;
@@ -208,7 +204,6 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
return {
networks,
musicSignUrl,
statusCommand: parseStatusCommand(sources),
notifications: parseNotifications(sources),
};
+191
View File
@@ -0,0 +1,191 @@
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
import type { JsonObject, RKeyConfig } from './types';
const log = createLogger('OneBot.GlobalConfig');
const CONFIG_DIR = 'config';
const GLOBAL_CONFIG_PATH = path.join(CONFIG_DIR, 'snowluma.json');
/**
* Global, all-accounts SnowLuma protocol settings — the home for small
* deployment-wide knobs that are NOT per-UIN (so they don't belong in
* `onebot_<uin>.json`). Persisted as `config/snowluma.json`. New small global
* settings should be added here rather than spawning a file/page per feature.
*/
export interface GlobalSettings {
/** Opt-in remote rkey fallback (see RKeyConfig). Default: servers empty = off. */
rkey: RKeyConfig;
/** Music-card signing service URL. Deployment-wide (same service for every
* account), so global rather than per-UIN. Empty = use the built-in default. */
musicSignUrl: string;
}
export function defaultGlobalSettings(): GlobalSettings {
return { rkey: { fallbackServers: [] }, musicSignUrl: '' };
}
/** Keep only well-formed, deduped http(s) URLs (must parse + have a host). */
export function normalizeRkeyServers(value: unknown): string[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
const out: string[] = [];
for (const item of value) {
if (typeof item !== 'string') continue;
const v = item.trim();
if (!v || !isHttpUrl(v) || seen.has(v)) continue;
seen.add(v);
out.push(v);
}
return out;
}
function isHttpUrl(value: string): boolean {
try {
const u = new URL(value);
return (u.protocol === 'http:' || u.protocol === 'https:') && u.host.length > 0;
} catch {
return false;
}
}
// NOTE: when adding a new section, extend normalizeGlobalSettings, toJson AND
// saveGlobalSettings in lockstep. normalize/toJson only copy known sections, so
// an un-handled on-disk section is silently dropped on the next load+save — the
// section-merge in saveGlobalSettings only guards against a request OMITTING a
// section, not against this load/serialize pipeline discarding an unknown one.
export function normalizeGlobalSettings(value: unknown): GlobalSettings {
const out = defaultGlobalSettings();
if (!isObject(value)) return out;
const rkey = value.rkey;
if (isObject(rkey)) {
out.rkey.fallbackServers = normalizeRkeyServers(rkey.fallbackServers);
}
if (typeof value.musicSignUrl === 'string') {
const v = value.musicSignUrl.trim();
// Empty = "use built-in default"; otherwise must be a real http(s) endpoint.
out.musicSignUrl = v && isHttpUrl(v) ? v : '';
}
return out;
}
export function loadGlobalSettings(): GlobalSettings {
if (!fs.existsSync(GLOBAL_CONFIG_PATH)) return defaultGlobalSettings();
try {
const raw = fs.readFileSync(GLOBAL_CONFIG_PATH, 'utf8');
return normalizeGlobalSettings(JSON.parse(raw) as unknown);
} catch (err) {
log.warn('config/snowluma.json is corrupt and will be ignored: %s', err instanceof Error ? err.message : String(err));
return defaultGlobalSettings();
}
}
/**
* Persist global settings, SECTION-MERGING over what's on disk: only the
* top-level sections actually present in `incoming` are overwritten, so a
* partial save (e.g. just `rkey`) never wipes a sibling knob. Mirrors
* saveNotificationsConfig's merge discipline.
*/
export function saveGlobalSettings(incoming: unknown): GlobalSettings {
const merged = loadGlobalSettings();
if (isObject(incoming)) {
if (isObject(incoming.rkey)) {
merged.rkey.fallbackServers = normalizeRkeyServers(incoming.rkey.fallbackServers);
}
if (typeof incoming.musicSignUrl === 'string') {
const v = incoming.musicSignUrl.trim();
merged.musicSignUrl = v && isHttpUrl(v) ? v : '';
}
}
fs.mkdirSync(CONFIG_DIR, { recursive: true });
const tmp = GLOBAL_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(toJson(merged), null, 2), 'utf8');
fs.renameSync(tmp, GLOBAL_CONFIG_PATH);
return merged;
}
function toJson(settings: GlobalSettings): JsonObject {
return {
rkey: { fallbackServers: settings.rkey.fallbackServers },
musicSignUrl: settings.musicSignUrl,
};
}
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/**
* One-shot copy-up: `musicSignUrl` used to live in per-UIN config. If the global
* store has none yet, lift the first non-empty value found in any legacy
* `config/onebot*.json` into `config/snowluma.json`. Idempotent — skips once the
* global value is set. (If an operator later clears the global value while a
* stale per-UIN value lingers, a restart would re-copy it; benign and rare.)
*/
export function migrateGlobalSettings(): void {
// One-shot guard keyed on PRESENCE (not truthiness): once snowluma.json carries
// a musicSignUrl key — written by this migration or any global-config save —
// never re-scan. This is what stops an operator's intentional clear-to-'' from
// being reverted by a stale legacy value on the next boot.
if (globalConfigHasMusicSignUrlKey()) return;
const found = scanLegacyMusicSignUrl();
if (!found) return;
saveGlobalSettings({ musicSignUrl: found.value });
const extra = found.others.length ? `; ignored differing value(s) in ${found.others.join(', ')}` : '';
log.info('migrated musicSignUrl to global config from %s: %s%s', found.source, found.value, extra);
}
function globalConfigHasMusicSignUrlKey(): boolean {
if (!fs.existsSync(GLOBAL_CONFIG_PATH)) return false;
try {
const raw = JSON.parse(fs.readFileSync(GLOBAL_CONFIG_PATH, 'utf8')) as unknown;
return isObject(raw) && 'musicSignUrl' in raw;
} catch {
return false;
}
}
interface LegacyMusicSignUrl {
value: string;
source: string;
others: string[];
}
/** Scan config/onebot.json + config/onebot_<uin>.json for a non-empty
* musicSignUrl. Returns the first found plus any other files that carried a
* (differing) value, for logging. */
function scanLegacyMusicSignUrl(): LegacyMusicSignUrl | null {
let dir: string[];
try {
dir = fs.readdirSync(CONFIG_DIR);
} catch {
return null;
}
const files = dir
.filter((f) => f === 'onebot.json' || /^onebot_\d+\.json$/.test(f))
.sort();
let first: { value: string; source: string } | null = null;
const others: string[] = [];
for (const file of files) {
let value: unknown;
try {
const raw = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, file), 'utf8')) as unknown;
value = isObject(raw) ? raw.musicSignUrl : undefined;
} catch {
continue;
}
if (typeof value !== 'string') continue;
const v = value.trim();
// Skip empty AND invalid here, so "first found" means "first usable" — a
// garbage value in an earlier-sorting file can't shadow a real URL in a
// later one (it would be dropped to '' on save and then locked by the guard).
if (!v || !isHttpUrl(v)) continue;
if (!first) first = { value: v, source: file };
else if (v !== first.value) others.push(file);
}
return first ? { ...first, others } : null;
}
+104 -10
View File
@@ -2,6 +2,7 @@ import { createLogger } from '@snowluma/common/logger';
import type { DownloadRKeyInfo } from '@snowluma/core/bridge';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/protocol/events';
import type { RKeyConfig } from './types';
const log = createLogger('OneBot');
@@ -15,6 +16,11 @@ interface CachedRKey {
const RKEY_REFRESH_SKEW = 60;
const RKEY_REFRESH_COOLDOWN = 30;
// When the cache holds NO usable image rkey, the alternative to refreshing is
// handing out a bare URL the CDN rejects with `invalid rkey` (issue #156). So
// retry far more eagerly than the 30s steady-state backoff — but still throttled
// so a persistently-failing fetch isn't hammered once per inbound image.
const RKEY_EMPTY_COOLDOWN = 10;
// Upper bound on how long URL resolution may block on a refresh round-trip.
// A stuck packet send must never wedge message conversion — past this we
// fall back to whatever the cache holds (possibly nothing).
@@ -31,6 +37,17 @@ export class RKeyCache {
private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0;
private refreshInflight: Promise<void> | null = null;
/** Opt-in remote rkey endpoints; empty = feature off (the default). */
private fallbackServers: string[];
constructor(config?: RKeyConfig) {
this.fallbackServers = config?.fallbackServers ?? [];
}
/** Replace the fallback endpoint list (global-config hot-reload). */
setFallbackServers(servers: string[]): void {
this.fallbackServers = servers;
}
warmUp(bridge: BridgeInterface, uin: string): void {
this.ensureFresh(bridge).then(
@@ -101,6 +118,13 @@ export class RKeyCache {
}
}
/** True when at least one common image rkey (group or private) is cached and
* still valid — i.e. we can sign a typical image without a fresh fetch. */
private hasUsableRkey(): boolean {
return this.findInCache(GROUP_IMAGE_RKEY_TYPE) !== null
|| this.findInCache(PRIVATE_IMAGE_RKEY_TYPE) !== null;
}
/** Pull a still-valid rkey out of the cache, or null if missing/expiring. */
private findInCache(primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
@@ -128,21 +152,20 @@ export class RKeyCache {
/**
* Refresh the rkey cache via OIDB 0x9067_202, coalescing concurrent
* callers onto one in-flight request and backing off for
* RKEY_REFRESH_COOLDOWN after a failed attempt so a persistently
* unreachable server isn't hammered once per inbound image. The await is
* bounded by RKEY_REFRESH_TIMEOUT_MS.
* callers onto one in-flight request and backing off (RKEY_REFRESH_COOLDOWN
* when a usable rkey is held, RKEY_EMPTY_COOLDOWN while none is) so a
* persistently-failing fetch isn't hammered once per inbound image. The await
* is bounded by RKEY_REFRESH_TIMEOUT_MS.
*/
private async ensureFresh(bridge: BridgeInterface): Promise<void> {
if (!this.refreshInflight) {
const now = Math.floor(Date.now() / 1000);
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return;
// Back off hard once we hold a usable rkey; retry quickly while we don't,
// so a transient empty/failed fetch self-heals in seconds, not 30s (#156).
const cooldown = this.hasUsableRkey() ? RKEY_REFRESH_COOLDOWN : RKEY_EMPTY_COOLDOWN;
if (now - this.lastRefreshAttempt < cooldown) return;
this.lastRefreshAttempt = now;
this.refreshInflight = bridge.apis.contacts.fetchDownloadRKeys()
.then((rkeys) => { this.updateCache(rkeys); })
.catch((err) => {
log.warn('rkey refresh failed: %s', err instanceof Error ? err.message : String(err));
})
this.refreshInflight = this.runRefresh(bridge)
.finally(() => { this.refreshInflight = null; });
}
@@ -157,6 +180,77 @@ export class RKeyCache {
if (timer) clearTimeout(timer);
}
}
/** One refresh round: native OIDB fetch, then — only if that left us without
* a usable image rkey AND fallback servers are configured — the remote
* fallback. Never throws; logs and degrades to whatever the cache holds. */
private async runRefresh(bridge: BridgeInterface): Promise<void> {
try {
const rkeys = await bridge.apis.contacts.fetchDownloadRKeys();
this.updateCache(rkeys);
} catch (err) {
log.warn('rkey refresh failed: %s', err instanceof Error ? err.message : String(err));
}
if (this.fallbackServers.length > 0 && !this.hasUsableRkey()) {
await this.refreshFromFallback();
}
}
/** Ask each configured fallback server in turn for an rkey, stopping at the
* first that yields one. Populates the group/private image rkey types. */
private async refreshFromFallback(): Promise<void> {
for (const server of this.fallbackServers) {
try {
const data = await fetchFallbackRkey(server);
if (!data) continue;
const now = Math.floor(Date.now() / 1000);
const expiresAt = data.expiredTime > now ? data.expiredTime : now + 3600;
if (data.groupRkey) this.setFallbackRkey(GROUP_IMAGE_RKEY_TYPE, data.groupRkey, expiresAt);
if (data.privateRkey) this.setFallbackRkey(PRIVATE_IMAGE_RKEY_TYPE, data.privateRkey, expiresAt);
if (data.groupRkey || data.privateRkey) {
log.info('rkey loaded from fallback server %s', server);
return;
}
} catch (err) {
log.warn('rkey fallback server %s failed: %s', server, err instanceof Error ? err.message : String(err));
}
}
}
private setFallbackRkey(type: number, value: string, expiresAt: number): void {
this.cache.set(type, { value, type, createTime: 0, ttlSeconds: 0, expiresAt });
}
}
interface FallbackRkeyData {
groupRkey: string;
privateRkey: string;
/** Absolute unix-seconds expiry (0 when the server omits it). */
expiredTime: number;
}
/** Fetch + parse one fallback server's response. Accepts the bare
* `{ group_rkey, private_rkey, expired_time }` shape and an OneBot
* `{ retcode, data: {...} }` wrapper. Returns null when neither rkey is
* present. The stored values keep any leading `&rkey=`/`?rkey=` — resolveImageUrl
* strips it before re-appending, so both prefixed and bare tokens work. */
async function fetchFallbackRkey(server: string): Promise<FallbackRkeyData | null> {
const res = await fetch(server, { signal: AbortSignal.timeout(RKEY_REFRESH_TIMEOUT_MS) });
if (!res.ok) throw new Error(`http ${res.status}`);
let body = await res.json() as Record<string, unknown>;
if (body && typeof body === 'object' && 'retcode' in body && isRecord(body.data)) {
body = body.data;
}
if (!isRecord(body)) return null;
const groupRkey = typeof body.group_rkey === 'string' ? body.group_rkey : '';
const privateRkey = typeof body.private_rkey === 'string' ? body.private_rkey : '';
if (!groupRkey && !privateRkey) return null;
const expiredTime = typeof body.expired_time === 'number' ? body.expired_time : 0;
return { groupRkey, privateRkey, expiredTime };
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
// QQ-NT download appids embedded in the image URL query string. The scene
+11 -3
View File
@@ -7,6 +7,7 @@ import type { ConverterContext } from './event-converter';
import { registerEventPipeline } from './event-pipeline';
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
import { RKeyCache } from './instance-rkey';
import type { GlobalSettings } from './global-config';
import { MediaIndexer } from './media-indexer';
import { MediaStore } from './media-store';
import { MediaUrlResolver } from './media-url-resolver';
@@ -73,7 +74,7 @@ export class OneBotInstance {
return this.apiHandler.handle(action, params);
}
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) {
this.uin = uin;
this.bridge = bridge;
const uinNum = Number.parseInt(uin, 10);
@@ -81,7 +82,7 @@ export class OneBotInstance {
? moduleLog.child({ uin: uinNum })
: moduleLog;
this.rkeyCache = new RKeyCache();
this.rkeyCache = new RKeyCache(globalSettings.rkey);
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db'));
@@ -107,7 +108,7 @@ export class OneBotInstance {
reactionStore: this.reactionStore,
converterCtx: this.converterCtx,
config,
musicSignUrl: config.musicSignUrl,
musicSignUrl: globalSettings.musicSignUrl,
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event) => this.dispatchEvent(event),
};
@@ -134,6 +135,13 @@ export class OneBotInstance {
});
}
/** Apply edited global (all-accounts) settings without a restart. Called by
* the manager when config/snowluma.json is saved from the WebUI. */
applyGlobalSettings(globalSettings: GlobalSettings): void {
this.rkeyCache.setFallbackServers(globalSettings.rkey.fallbackServers);
this.ctx.musicSignUrl = globalSettings.musicSignUrl;
}
dispose(): void {
this.online = false;
this.stopHeartbeat();
+12 -1
View File
@@ -2,6 +2,7 @@ import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { loadOneBotConfig } from './config';
import { loadGlobalSettings } from './global-config';
import { OneBotInstance } from './instance';
import type { AdapterStatus } from './network';
@@ -55,6 +56,16 @@ export class OneBotManager {
return true;
}
/** Re-read global (all-accounts) settings from config/snowluma.json and push
* them to every live instance. Called after the WebUI saves global config. */
reloadGlobalSettings(): void {
const globalSettings = loadGlobalSettings();
for (const instance of this.instances.values()) {
instance.applyGlobalSettings(globalSettings);
}
log.info('global settings reloaded for %d instance(s)', this.instances.size);
}
dispose(): void {
for (const instance of this.instances.values()) {
instance.dispose();
@@ -66,7 +77,7 @@ export class OneBotManager {
if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin, { persistDefaults: true });
const instance = new OneBotInstance(uin, bridge, config);
const instance = new OneBotInstance(uin, bridge, config, loadGlobalSettings());
const activePid = bridge.activePid;
if (activePid !== null) {
+29 -3
View File
@@ -54,6 +54,32 @@ export function parseCQParams(raw: string): Record<string, string> {
return params;
}
/**
* Pick the best loadable source from a media segment's `file` / `url` / `path`
* / `media` fields.
*
* `file` is normally the canonical OneBot field and wins, but it can also be a
* QQ-internal media id (e.g. `<md5>.png`) that this process cannot resolve to a
* local path. When a bot framework echoes a received image back (Yunzai et al.
* resend the original `file=<md5>.ext` together with the download `url`), using
* `file` makes the send path `statSync` the id as a bogus local path and throw
* `ENOENT`. So: keep `file` when it is a directly loadable source (inline
* bytes, a remote url, or a filesystem path with a separator); otherwise, if a
* real http(s) `url` accompanies it, prefer that. (issue #155)
*/
function pickMediaSource(data: Record<string, unknown>): string {
const file = String(data.file ?? '').trim();
const url = String(data.url ?? '').trim();
const fallback = file || url || String(data.path ?? '').trim() || String(data.media ?? '').trim();
if (!file) return fallback;
// `file` is itself loadable: inline bytes, a remote url, or a path (anything
// carrying a `/` or `\` separator, incl. file:// and absolute/relative paths).
if (/^(base64:\/\/|data:|https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file;
// `file` is a bare token (QQ-internal id) — fall back to a real url if present.
if (/^https?:\/\//i.test(url)) return url;
return fallback;
}
// --- JSON segment parsing ---
interface MessageSegment {
@@ -136,7 +162,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
if (imgEmojiId) return marketFaceElement(imgEmojiId, data);
return {
type: 'image',
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
url: pickMediaSource(data),
flash: data.type === 'flash',
subType: intOr(data.subType, 0),
summary: data.summary ? String(data.summary) : undefined,
@@ -153,7 +179,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
return marketFaceElement(emojiId, data);
}
case 'record': {
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
const source = pickMediaSource(data);
if (!source) return null;
return {
type: 'record',
@@ -161,7 +187,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
};
}
case 'video': {
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
const source = pickMediaSource(data);
if (!source) return null;
return {
type: 'video',
+100 -8
View File
@@ -1,6 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/video-upload';
import type { MessageSendResult } from '../api-handler';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
import { segmentsToRawMessage } from '../helper/cq';
@@ -12,6 +13,49 @@ import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types';
const log = createLogger('OneBot');
// A video larger than QQ's Highway video ceiling can't be sent through the
// element pipeline — it must fall back to a regular file upload. The fallback
// is decided at the OneBot layer (not element-builder) because building a
// group/c2c file element needs an uploaded file, which only the file-upload
// pipeline produces. See send-video-fallback.test.ts.
/** Whether a Highway upload error message looks size-related. */
export function isHighwaySizeError(err: unknown): boolean {
return err instanceof Error && /size limit|too large|413|too big|exceed/i.test(err.message);
}
/**
* A video element should fall back to file upload when its source size is
* known to exceed the limit, or — when the size can't be inferred (remote
* URL) — when the upload error itself looks size-related.
*/
export function videoNeedsFileFallback(element: MessageElement, isSizeErr: boolean): boolean {
if (element.type !== 'video') return false;
const sz = getVideoSourceSize(element);
return sz !== null ? sz > MAX_VIDEO_SIZE : isSizeErr;
}
/**
* Partition elements after a failed Highway send: oversized videos become
* `file` elements (re-routed through the file-upload pipeline), everything
* else is returned for a normal re-send.
*/
export function splitVideoFileFallback(
elements: MessageElement[],
isSizeErr: boolean,
): { fileEls: MessageElement[]; remaining: MessageElement[] } {
const fileEls: MessageElement[] = [];
const remaining: MessageElement[] = [];
for (const e of elements) {
if (videoNeedsFileFallback(e, isSizeErr)) {
fileEls.push({ type: 'file', url: e.url, fileId: e.fileId, fileName: e.fileName || 'video.mp4' });
} else {
remaining.push(e);
}
}
return { fileEls, remaining };
}
export async function getGroupMsgHistory(
messageStore: MessageStore,
groupId: number,
@@ -504,6 +548,22 @@ export async function sendPrivateMessage(
});
if (elements.length === 0) throw new Error('message is empty');
// Private chats cannot @-mention anyone — QQ simply ignores the mention
// element in c2c messages. Many OneBot callers blindly append an `at`
// segment right after `reply` (the group-chat convention), which ends up
// producing a broken wire message. Strip `at` elements so they never
// reach the protocol layer.
const hasReply = elements.some(e => e.type === 'reply');
for (let i = elements.length - 1; i >= 0; i--) {
if (elements[i].type === 'at') {
if (!hasReply) {
log.warn('[OneBot] at segment in private message is unsupported — stripped');
}
elements.splice(i, 1);
}
}
if (elements.length === 0) throw new Error('message is empty');
// C2C `{type:'file'}` segments can't ride on the elems[] pipeline —
// c2c files live on `RichText.notOnlineFile`, parallel to elems
// (see `@snowluma/proto-defs/message:notOnlineFile`). The element-builder
@@ -520,13 +580,29 @@ export async function sendPrivateMessage(
// Two sub-paths:
// a) has url/path but no file_id → uploadPrivate() which internally calls sendC2cFile()
// b) has file_id from a prior upload_private_file → sendC2cFile() only
const allFileElements = elements.filter(e => e.type === 'file');
const nonFileElements = elements.filter(e => e.type !== 'file');
let allFileElements = elements.filter(e => e.type === 'file');
let nonFileElements = elements.filter(e => e.type !== 'file');
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
try {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
} catch (err) {
// Highway upload failed — if a large video triggered it, fall back to
// file upload for that element (private messages cannot carry file
// elements through the element pipeline).
const isSizeErr = isHighwaySizeError(err);
if (!nonFileElements.some(e => videoNeedsFileFallback(e, isSizeErr))) throw err;
log.warn('[OneBot] private video upload failed, falling back to file upload: %s', err instanceof Error ? err.message : String(err));
const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr);
allFileElements = [...allFileElements, ...fileEls];
nonFileElements = remaining;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
}
}
}
if (allFileElements.length > 0) {
const userUid = await ref.bridge.resolveUserUid(userId);
@@ -611,13 +687,29 @@ export async function sendGroupMessage(
// Two sub-paths for group file segments:
// a) has url/path but no file_id → upload() which internally calls publish()
// b) has file_id from a prior upload_group_file → publish() only
const allFileElements = elements.filter(e => e.type === 'file');
const nonFileElements = elements.filter(e => e.type !== 'file');
let allFileElements = elements.filter(e => e.type === 'file');
let nonFileElements = elements.filter(e => e.type !== 'file');
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
logSentMessage(true, groupId, nonFileElements);
try {
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
logSentMessage(true, groupId, nonFileElements);
} catch (err) {
// Highway upload failed — if a large video triggered it, fall back to
// group file upload (mirrors the private path; element-builder cannot
// build a group file element without an already-uploaded file_id).
const isSizeErr = isHighwaySizeError(err);
if (!nonFileElements.some(e => videoNeedsFileFallback(e, isSizeErr))) throw err;
log.warn('[OneBot] group video upload failed, falling back to file upload: %s', err instanceof Error ? err.message : String(err));
const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr);
allFileElements = [...allFileElements, ...fileEls];
nonFileElements = remaining;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
logSentMessage(true, groupId, nonFileElements);
}
}
}
for (const fileEl of allFileElements) {
let fileId: string;
+18 -2
View File
@@ -82,11 +82,27 @@ export interface StatusCommandConfig {
trigger: string;
}
/**
* Remote rkey fallback. QQ-NT image/file download URLs need a short-lived,
* server-issued `rkey`; SnowLuma fetches it via OIDB 0x9067_202. On accounts
* where that native fetch persistently returns nothing, every image would be
* served as a bare URL the CDN rejects with `invalid rkey` (#156). When
* `fallbackServers` is non-empty, SnowLuma asks those HTTP endpoints for an
* rkey instead. OFF by default (empty list): no third-party server is ever
* contacted unless you opt in by configuring your own endpoint.
*/
export interface RKeyConfig {
/**
* HTTP(S) endpoints returning `{ group_rkey, private_rkey, expired_time }`
* (NapCat rkey-server format; an OneBot `{ retcode, data }` wrapper is also
* accepted). Tried in order until one yields a usable rkey. Default `[]`.
*/
fallbackServers: string[];
}
/** Per-UIN OneBot configuration. */
export interface OneBotConfig {
networks: OneBotNetworks;
/** Music card signing service URL (optional). */
musicSignUrl?: string;
/** Built-in `#sl` status command settings. Always present after normalization. */
statusCommand: StatusCommandConfig;
/** Which GLOBAL notification channels this account opts into (channel ids are
@@ -0,0 +1,48 @@
// Tests the optional returnsSchema doc metadata: it must round-trip through
// describe() (on both defineAction and the group* presets) and stay absent
// when not provided. Semantics: returnsSchema describes the `data` payload
// inside the OneBot envelope, not the envelope.
import { describe, it, expect } from 'vitest';
import { defineAction, groupAction, f } from '../src/action-kit';
import { okResponse } from '../src/types';
describe('returnsSchema', () => {
const dataSchema = {
type: 'object',
properties: { group_id: { type: 'integer' }, group_name: { type: 'string' } },
required: ['group_id', 'group_name'],
};
it('round-trips returnsSchema through describe() on defineAction', () => {
const spec = defineAction({
name: 'demo_get',
summary: 'demo',
readOnly: true,
returns: '群信息对象',
returnsSchema: dataSchema,
params: { x: f.uint() },
run: () => okResponse({ ok: true }),
});
expect(spec.describe().returnsSchema).toEqual(dataSchema);
expect(spec.describe().returns).toBe('群信息对象');
});
it('omits returnsSchema when not provided', () => {
const spec = defineAction({
name: 'demo_noschema',
params: {},
run: () => okResponse(null),
});
expect(spec.describe().returnsSchema).toBeUndefined();
});
it('carries returnsSchema through groupAction preset', () => {
const spec = groupAction({
name: 'demo_group_get',
readOnly: true,
returnsSchema: dataSchema,
run: () => okResponse({}),
});
expect(spec.describe().returnsSchema).toEqual(dataSchema);
});
});
-3
View File
@@ -24,7 +24,6 @@ describe('makeDefaultOneBotConfig', () => {
expect(config.networks.wsServers[0].messageFormat).toBe('array');
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, trigger: '#sl' });
expect(config.notifications).toEqual({ channelIds: [] });
});
@@ -119,8 +118,6 @@ describe('loadOneBotConfig', () => {
expect(config.networks.wsClients[0].messageFormat).toBe('string');
expect(config.networks.wsClients[0].reportSelfMessage).toBe(true);
expect(config.musicSignUrl).toBe('https://example.com/sign');
// File should now be in unified format on disk.
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8'));
expect(onDisk.networks).toBeDefined();
+142
View File
@@ -0,0 +1,142 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import {
defaultGlobalSettings,
loadGlobalSettings,
migrateGlobalSettings,
normalizeGlobalSettings,
saveGlobalSettings,
} from '../src/global-config';
describe('global-config (config/snowluma.json)', () => {
let tempDir: string;
let prevCwd: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-global-config-'));
prevCwd = process.cwd();
process.chdir(tempDir);
});
afterEach(() => {
process.chdir(prevCwd);
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('defaults to an empty fallback list (feature off)', () => {
expect(defaultGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' });
expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' });
});
it('keeps only well-formed http(s) URLs, trims, and dedupes', () => {
const out = normalizeGlobalSettings({
rkey: { fallbackServers: [' https://a.example/r ', 'ftp://x', 'not-a-url', 'https://', 'https://a.example/r', 'http://b.example/r', 42] },
});
// 'https://' (no host) and non-http schemes are dropped.
expect(out.rkey.fallbackServers).toEqual(['https://a.example/r', 'http://b.example/r']);
});
it('ignores a malformed rkey block', () => {
expect(normalizeGlobalSettings({ rkey: 'nope' })).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' });
expect(normalizeGlobalSettings(null)).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' });
});
it('round-trips through save → disk → load', () => {
const saved = saveGlobalSettings({ rkey: { fallbackServers: ['https://r.example/rkey', 'bogus'] } });
expect(saved.rkey.fallbackServers).toEqual(['https://r.example/rkey']);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', 'snowluma.json'), 'utf8'));
expect(onDisk).toEqual({ rkey: { fallbackServers: ['https://r.example/rkey'] }, musicSignUrl: '' });
expect(loadGlobalSettings().rkey.fallbackServers).toEqual(['https://r.example/rkey']);
});
it('section-merges on save: a partial write never wipes a sibling section', () => {
saveGlobalSettings({ rkey: { fallbackServers: ['https://r.example/rkey'] } });
// A save touching only musicSignUrl must preserve the rkey servers, and
// vice-versa.
const after = saveGlobalSettings({ musicSignUrl: 'https://sign.example/card' });
expect(after.rkey.fallbackServers).toEqual(['https://r.example/rkey']);
expect(after.musicSignUrl).toBe('https://sign.example/card');
expect(saveGlobalSettings({ rkey: { fallbackServers: [] } }).musicSignUrl).toBe('https://sign.example/card');
});
it('normalizes + round-trips musicSignUrl (trimmed)', () => {
expect(normalizeGlobalSettings({ musicSignUrl: ' https://s.example/c ' }).musicSignUrl).toBe('https://s.example/c');
const saved = saveGlobalSettings({ musicSignUrl: 'https://s.example/c' });
expect(saved.musicSignUrl).toBe('https://s.example/c');
expect(loadGlobalSettings().musicSignUrl).toBe('https://s.example/c');
});
describe('migrateGlobalSettings (musicSignUrl copy-up)', () => {
function writeOnebot(file: string, body: unknown) {
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, file), JSON.stringify(body), 'utf8');
}
it('lifts a legacy per-UIN musicSignUrl into the global store', () => {
writeOnebot('onebot_123.json', { musicSignUrl: 'https://legacy.example/sign' });
migrateGlobalSettings();
expect(loadGlobalSettings().musicSignUrl).toBe('https://legacy.example/sign');
});
it('is a no-op when the global value is already set', () => {
saveGlobalSettings({ musicSignUrl: 'https://kept.example/sign' });
writeOnebot('onebot_123.json', { musicSignUrl: 'https://legacy.example/sign' });
migrateGlobalSettings();
expect(loadGlobalSettings().musicSignUrl).toBe('https://kept.example/sign');
});
it('takes the first file and tolerates differing/empty values across files', () => {
writeOnebot('onebot.json', { musicSignUrl: '' }); // empty → skipped
writeOnebot('onebot_111.json', { musicSignUrl: 'https://a.example/s' });
writeOnebot('onebot_222.json', { musicSignUrl: 'https://b.example/s' });
migrateGlobalSettings();
// onebot.json sorts first but is empty; onebot_111 is the first non-empty.
expect(loadGlobalSettings().musicSignUrl).toBe('https://a.example/s');
});
it('does nothing when no legacy value exists', () => {
writeOnebot('onebot_123.json', { networks: {} });
migrateGlobalSettings();
expect(loadGlobalSettings().musicSignUrl).toBe('');
});
it('migrates a value carried by the base onebot.json', () => {
writeOnebot('onebot.json', { musicSignUrl: 'https://base.example/s' });
migrateGlobalSettings();
expect(loadGlobalSettings().musicSignUrl).toBe('https://base.example/s');
});
it('skips an invalid earlier value and migrates the first VALID one', () => {
writeOnebot('onebot.json', { musicSignUrl: 'not-a-url' }); // earlier-sorting garbage
writeOnebot('onebot_111.json', { musicSignUrl: 'https://real.example/s' });
migrateGlobalSettings();
expect(loadGlobalSettings().musicSignUrl).toBe('https://real.example/s');
});
it('does NOT re-copy after an intentional clear-to-empty (presence guard)', () => {
// Operator cleared the global value to '' (the key is present in the file)…
saveGlobalSettings({ musicSignUrl: '' });
// …while a stale legacy value still lingers.
writeOnebot('onebot_123.json', { musicSignUrl: 'https://legacy.example/sign' });
migrateGlobalSettings();
expect(loadGlobalSettings().musicSignUrl).toBe(''); // stays cleared, not reverted
});
it('is a safe no-op when config/ does not exist', () => {
// fresh cwd, no config dir at all
expect(() => migrateGlobalSettings()).not.toThrow();
expect(loadGlobalSettings().musicSignUrl).toBe('');
});
});
it('falls back to defaults when the file is corrupt', () => {
fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true });
fs.writeFileSync(path.join(tempDir, 'config', 'snowluma.json'), '{ not json', 'utf8');
expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' });
});
});
+162 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { RKeyCache } from '../src/instance-rkey';
import type { MessageElement } from '@snowluma/protocol/events';
@@ -124,6 +124,49 @@ describe('RKeyCache.resolveImageUrl', () => {
expect(url).toBe(`${noAppidUrl}&rkey=GROUPKEY`);
});
// #156: a transient empty/failed fetch must self-heal in seconds, not 30s.
// An empty cache uses the short RKEY_EMPTY_COOLDOWN (10s), so a retry ~11s
// later refetches — under the 30s steady-state backoff it would not.
it('retries before the 30s cooldown while the cache holds no usable rkey', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(new Date(1_700_000_000_000));
let calls = 0;
const { bridge, fetchDownloadRKeys } = makeBridge(
async () => (++calls === 1 ? [] : freshGroupRkey()),
);
const cache = new RKeyCache();
const url1 = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url1).toBe(NT_IMAGE_URL); // empty fetch → bare URL
vi.setSystemTime(new Date(1_700_000_000_000 + 11_000)); // +11s: past 10s empty-cooldown, inside 30s
const url2 = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url2).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
}
});
it('does NOT refetch within 30s once a usable rkey is cached', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(new Date(1_700_000_000_000));
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache();
await cache.resolveImageUrl(bridge as never, imageEl(), true);
vi.setSystemTime(new Date(1_700_000_000_000 + 15_000)); // +15s, inside 30s backoff
await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
});
it('leaves non-NT URLs untouched and never fetches', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache();
@@ -135,3 +178,121 @@ describe('RKeyCache.resolveImageUrl', () => {
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
});
});
describe('RKeyCache remote fallback (#156)', () => {
const SERVER = 'https://rkey.example/r';
function stubFetch(payload: unknown, status = 200) {
return vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(JSON.stringify(payload), { status }),
);
}
afterEach(() => {
vi.restoreAllMocks();
});
it('is off by default: never contacts a server, leaves the URL bare', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch');
const { bridge } = makeBridge(async () => []); // native yields nothing
const cache = new RKeyCache(); // no config → fallback off
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(NT_IMAGE_URL);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('falls back to the configured server when the native fetch is empty', async () => {
const fetchSpy = stubFetch({
group_rkey: '&rkey=FBGROUP', private_rkey: '&rkey=FBPRIV', expired_time: nowSec() + 3600,
});
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=FBGROUP`);
expect(fetchSpy).toHaveBeenCalledWith(SERVER, expect.anything());
});
it('signs c2c images with the fallback private rkey', async () => {
stubFetch({ group_rkey: '&rkey=FBGROUP', private_rkey: '&rkey=FBPRIV', expired_time: nowSec() + 3600 });
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), false);
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=FBPRIV`);
});
it('accepts an OneBot { retcode, data } wrapper and bare (unprefixed) tokens', async () => {
stubFetch({ retcode: 0, data: { group_rkey: 'BAREKEY', private_rkey: '', expired_time: nowSec() + 3600 } });
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=BAREKEY`);
});
it('does not hit any server when the native fetch already returned a rkey', async () => {
const fetchSpy = stubFetch({ group_rkey: '&rkey=FBGROUP', expired_time: nowSec() + 3600 });
const { bridge } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`); // native rkey, not fallback
expect(fetchSpy).not.toHaveBeenCalled();
});
it('tries the next server when the first one fails', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch')
.mockRejectedValueOnce(new Error('down'))
.mockResolvedValueOnce(new Response(JSON.stringify({ group_rkey: '&rkey=SECOND', expired_time: nowSec() + 3600 }), { status: 200 }));
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: ['https://a.example/r', 'https://b.example/r'] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=SECOND`);
expect(fetchSpy).toHaveBeenCalledTimes(2);
});
it('leaves the URL bare when every fallback server fails', async () => {
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('down'));
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache({ fallbackServers: [SERVER] });
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(NT_IMAGE_URL);
});
// Hot-reload wire: manager.reloadGlobalSettings → instance.applyGlobalSettings
// → rkeyCache.setFallbackServers. Verify the new list actually takes effect.
// (Fake Date so the 2nd lookup clears the empty-cache refresh cooldown.)
it('setFallbackServers turns the fallback on for a cache that started with none', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(new Date(1_700_000_000_000));
const fetchSpy = stubFetch({ group_rkey: '&rkey=HOTGROUP', expired_time: 1_700_000_000 + 3600 });
const { bridge } = makeBridge(async () => []);
const cache = new RKeyCache(); // starts OFF (no servers)
const before = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(before).toBe(NT_IMAGE_URL); // bare — fallback off
expect(fetchSpy).not.toHaveBeenCalled();
cache.setFallbackServers([SERVER]); // hot-reload pushes a new endpoint
vi.setSystemTime(new Date(1_700_000_000_000 + 11_000)); // clear the 10s empty-cooldown
const after = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(after).toBe(`${NT_IMAGE_URL}&rkey=HOTGROUP`);
expect(fetchSpy).toHaveBeenCalledWith(SERVER, expect.anything());
} finally {
vi.useRealTimers();
}
});
});
@@ -93,6 +93,56 @@ describe('parseMessage', () => {
expect(result[0].url).toBe('https://example.com/img.png');
});
it('prefers a real url when file is a QQ-internal id (issue #155)', async () => {
// Yunzai et al. echo a received image by resending the original
// `file=<md5>.ext` together with the download `url`. `file` is not a
// local path, so picking it would statSync → ENOENT on send.
const result = await parseMessage(
[{
type: 'image',
data: {
file: '35246A5B5C287F680C90839829FD7620.png',
url: 'https://multimedia.nt.qq.com.cn/download?fileid=abc&rkey=xyz',
sub_type: 1,
summary: '[动画表情]',
},
}] as any,
true,
);
expect(result[0].type).toBe('image');
expect(result[0].url).toBe('https://multimedia.nt.qq.com.cn/download?fileid=abc&rkey=xyz');
});
it('keeps file when it is itself loadable even if a url is also present', async () => {
// A path (has a separator) or inline bytes are the actual content and
// must win over any sibling url.
const viaPath = await parseMessage(
[{ type: 'image', data: { file: '/tmp/local.png', url: 'https://example.com/other.png' } }] as any,
false,
);
expect(viaPath[0].url).toBe('/tmp/local.png');
const viaBase64 = await parseMessage(
[{ type: 'image', data: { file: 'base64://AAAA', url: 'https://example.com/other.png' } }] as any,
false,
);
expect(viaBase64[0].url).toBe('base64://AAAA');
});
it('falls back a QQ-internal id record/video to the sibling url (issue #155)', async () => {
const rec = await parseMessage(
[{ type: 'record', data: { file: 'ABCD1234.amr', url: 'https://example.com/v.amr' } }] as any,
false,
);
expect(rec).toEqual([{ type: 'record', url: 'https://example.com/v.amr' }]);
const vid = await parseMessage(
[{ type: 'video', data: { file: 'EF567890.mp4', url: 'https://example.com/v.mp4' } }] as any,
false,
);
expect(vid).toEqual([{ type: 'video', url: 'https://example.com/v.mp4', thumbUrl: undefined }]);
});
it('parses record segment from data.file', async () => {
const result = await parseMessage(
[{ type: 'record', data: { file: 'file:///tmp/voice.amr' } }] as any,
@@ -0,0 +1,157 @@
// Regression coverage for the private-chat-at bug.
//
// Symptom in the wild: bot called `send_private_msg` with a message
// like `[reply, at, text]` — the group-chat convention of quoting +
// @-mentioning the reply target. QQ ignores mention elements in c2c
// messages so the `at` segment is pointless; worse, it produces a
// broken-looking wire message (the recipient sees a phantom "@QQ号"
// that can't be clicked).
//
// Fix: `sendPrivateMessage` now strips all `at` elements before
// handing the array to the protocol layer. When the message also
// contains a `reply` segment the strip is silent (it's the normal
// OneBot convention and the caller didn't do anything wrong); without
// a `reply` the strip still happens but a warn is logged.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../src/instance-context';
import { sendPrivateMessage } from '../src/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
const goodReceipt = {
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
};
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
selfId: 10001,
bridge,
messageStore: {
findEvent: () => null,
findMeta: () => null,
resolveReplySequence: () => 42,
} as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
describe('send_private_msg strips at segments', () => {
it('reply + at + text → only reply + text reach the wire', async () => {
const sendPrivate = vi.fn(async (_uin: number, elements: any[]) => {
// Verify no `at` element reaches the bridge
const types = elements.map((e: any) => e.type);
expect(types).not.toContain('at');
return goodReceipt;
});
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
{ type: 'reply', data: { id: '-2050237785' } },
{ type: 'at', data: { qq: '67890' } },
{ type: 'text', data: { text: ' ' } },
{ type: 'text', data: { text: 'quoted reply text' } },
] as any, false);
expect(sendPrivate).toHaveBeenCalledOnce();
const sentElements = sendPrivate.mock.calls[0]![1] as any[];
const sentTypes = sentElements.map(e => e.type);
expect(sentTypes).toEqual(['reply', 'text', 'text']);
});
it('at-only message (no reply) is also stripped, throws "message is empty"', async () => {
const sendPrivate = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'at', data: { qq: '67890' } },
] as any, false)).rejects.toThrow('message is empty');
expect(sendPrivate).not.toHaveBeenCalled();
});
it('text + at (without reply) strips at and sends remaining text', async () => {
const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'hello' } },
{ type: 'at', data: { qq: '67890' } },
] as any, false);
expect(sendPrivate).toHaveBeenCalledOnce();
const sentElements = sendPrivate.mock.calls[0]![1] as any[];
expect(sentElements).toEqual([{ type: 'text', text: 'hello' }]);
});
it('multiple at segments are all stripped', async () => {
const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
{ type: 'reply', data: { id: '123' } },
{ type: 'at', data: { qq: '67890' } },
{ type: 'at', data: { qq: '12345' } },
{ type: 'text', data: { text: 'hi' } },
] as any, false);
expect(sendPrivate).toHaveBeenCalledOnce();
const sentElements = sendPrivate.mock.calls[0]![1] as any[];
const sentTypes = sentElements.map((e: any) => e.type);
expect(sentTypes).not.toContain('at');
expect(sentTypes).toContain('reply');
expect(sentTypes).toContain('text');
});
it('group messages are NOT affected (at segments preserved)', async () => {
// Sanity: import sendGroupMessage and verify at segments pass through
const { sendGroupMessage } = await import('../src/modules/message-actions');
const sendGroup = vi.fn(async (_groupId: number, elements: any[]) => {
return goodReceipt;
});
const bridge = fakeBridge({
apis: { message: { sendGroup } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 99999, [
{ type: 'reply', data: { id: '123' } },
{ type: 'at', data: { qq: '67890' } },
{ type: 'text', data: { text: 'hi' } },
] as any, false);
expect(sendGroup).toHaveBeenCalledOnce();
const sentElements = sendGroup.mock.calls[0]![1] as any[];
const sentTypes = sentElements.map((e: any) => e.type);
expect(sentTypes).toContain('at');
});
});
@@ -0,0 +1,121 @@
// Regression coverage for large-video → file-upload fallback.
//
// When a video exceeds QQ's Highway video ceiling the element-pipeline
// send throws. The OneBot layer catches that and re-routes the video
// through the dedicated file-upload pipeline (group: groupFile.upload,
// private: groupFile.uploadPrivate). The element-builder cannot produce
// a group file element on its own because it has no uploaded file_id at
// build time — so the fallback MUST live at the OneBot layer for both
// scenes (private already did; #153 left the group side broken).
import { describe, expect, it, vi } from 'vitest';
import type { MessageElement } from '@snowluma/protocol/events';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../src/instance-context';
import { sendGroupMessage, videoNeedsFileFallback } from '../src/modules/message-actions';
const MB = 1024 * 1024;
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
describe('send_group_msg large-video fallback', () => {
it('routes the video through groupFile.upload when the Highway send fails with a size error', async () => {
const sendGroup = vi.fn(async (_gid: number, _elements: any[]) => {
throw new Error('video file too large: 1200 MB exceeds limit');
});
const upload = vi.fn(async (_gid: number, _src: string, _name: string, _folder: string, _doUpload: boolean) =>
({ fileId: 'auto-fid', fileHash: null }));
const publish = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendGroup },
groupFile: { upload, publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [{
type: 'video', data: { file: 'http://example.com/big.mp4' },
}] as any, false);
// Highway send was attempted once (and threw)...
expect(sendGroup).toHaveBeenCalledOnce();
// ...then the video was re-routed through the group file pipeline.
expect(upload).toHaveBeenCalledOnce();
const [gid, src, name] = upload.mock.calls[0]!;
expect(gid).toBe(12345);
expect(src).toBe('http://example.com/big.mp4');
expect(name).toBe('video.mp4');
// upload() publishes internally — no second publish().
expect(publish).not.toHaveBeenCalled();
});
it('rethrows (no fallback) when a remote video fails with a non-size error', async () => {
// Size can't be inferred for a remote URL, and the error isn't
// size-related — we must not silently swallow an unrelated failure
// by converting it to a file upload.
const sendGroup = vi.fn(async (_gid: number, _elements: any[]) => {
throw new Error('network reset while streaming chunk 3');
});
const upload = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendGroup },
groupFile: { upload, publish: vi.fn() },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await expect(sendGroupMessage(ctx, 12345, [{
type: 'video', data: { file: 'http://example.com/big.mp4' },
}] as any, false)).rejects.toThrow('network reset');
expect(upload).not.toHaveBeenCalled();
});
});
describe('videoNeedsFileFallback', () => {
it('triggers on a known oversize source regardless of the error message', () => {
// The real-bot case: a local 1.4 GB video whose Highway upload fails
// with a cryptic `error_code=323` (not size-worded). Source size is
// known, so the file fallback must still fire.
const big = { type: 'video', fileSize: 1400 * MB } as MessageElement;
expect(videoNeedsFileFallback(big, /* isSizeErr */ false)).toBe(true);
});
it('does not trigger for a known under-limit source', () => {
const small = { type: 'video', fileSize: 50 * MB } as MessageElement;
expect(videoNeedsFileFallback(small, true)).toBe(false);
});
it('falls back to the error heuristic when the source size is unknown', () => {
const remote = { type: 'video', url: 'http://example.com/v.mp4' } as MessageElement;
expect(videoNeedsFileFallback(remote, true)).toBe(true);
expect(videoNeedsFileFallback(remote, false)).toBe(false);
});
it('never triggers for non-video elements', () => {
const img = { type: 'image', fileSize: 1400 * MB } as MessageElement;
expect(videoNeedsFileFallback(img, true)).toBe(false);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.10.3",
"version": "1.10.4",
"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).",
+22 -1
View File
@@ -85,8 +85,29 @@ export interface MessageBody {
// C2C 文件附加信息
// 统一使用与线上数据对齐的 NotOnlineFile 结构,修复收发双向的解析问题。
//
// `field6` 携带服务器签发的下载路由(来自 0xE37_800 finalize 响应的
// metadata)。发送 c2c 文件时缺了它,接收方点开会"文件传输失败"——
// `file` 只是元数据,真正的下载凭证在这里。字段 tag 对照 NapCat
// `message/component.ts: PrivateFileExtra / PrivateFileExtraField2`。
export interface PrivateFileExtraField2 {
field1?: pb<1, uint_32>; // ← finalize metadata.field110
fileUuid?: pb<4, string>;
fileName?: pb<5, string>;
field6?: pb<6, uint_32>; // ← finalize metadata.field3
field7?: pb<7, bytes>; // ← finalize metadata.field101
field8?: pb<8, bytes>; // ← finalize metadata.field100
timestamp1?: pb<9, uint_32>; // ← finalize metadata.timestamp1
fileHash?: pb<14, string>;
selfUid?: pb<15, string>;
destUid?: pb<16, string>;
}
export interface PrivateFileExtra {
field2?: pb<2, PrivateFileExtraField2>;
}
export interface FileExtra {
file?: pb<1, NotOnlineFile>;
file?: pb<1, NotOnlineFile>;
field6?: pb<6, PrivateFileExtra>;
}
// PushMsgBody
@@ -75,6 +75,47 @@ export interface OidbPrivateFileUploadRespBody {
export interface OidbPrivateFileUploadResp {
upload?: pb<19, OidbPrivateFileUploadRespBody>;
}
// 0xE37_800 — c2c offline-file finalize / download-credential fetch.
// Called AFTER the Highway upload completes (NapCat runs it even when the
// file already exists server-side). The response metadata (`field30`)
// supplies the download-routing fields the receiver needs; those ride
// along in `FileExtra.field6` on the PbSendMsg. Without this step the file
// uploads + PbSendMsg returns ok but the recipient sees "文件传输失败".
// Ported byte-for-byte from NapCat `Oidb.0XE37_800` + `Oidb.0xE37_1200`.
export interface OidbOfflineFileFinalizeReqBody {
senderUid?: pb<10, string>;
receiverUid?: pb<20, string>;
fileUuid?: pb<30, string>;
fileHash?: pb<40, string>;
}
export interface OidbOfflineFileFinalizeReq {
subCommand?: pb<1, uint_32>;
field2?: pb<2, int_32>;
body?: pb<10, OidbOfflineFileFinalizeReqBody>;
field101?: pb<101, int_32>;
field102?: pb<102, int_32>;
field200?: pb<200, int_32>;
}
// Server-issued download routing for the just-uploaded c2c file. Only the
// fields consumed by `FileExtra.field6` are modelled (NapCat names them
// field3/field100/field101/field110/timestamp1; tags verified).
export interface OidbOfflineFileMetadata {
field3?: pb<3, uint_32>;
field100?: pb<100, bytes>;
field101?: pb<101, bytes>;
field110?: pb<110, uint_32>;
timestamp1?: pb<130, uint_32>;
}
export interface OidbOfflineFileFinalizeRespBody {
field10?: pb<10, uint_32>;
metadata?: pb<30, OidbOfflineFileMetadata>;
}
export interface OidbOfflineFileFinalizeResp {
command?: pb<1, uint_32>;
subCommand?: pb<2, uint_32>;
body?: pb<10, OidbOfflineFileFinalizeRespBody>;
field50?: pb<50, uint_32>;
}
export interface NTV2CommonHead {
requestId?: pb<1, uint_32>;
command?: pb<2, uint_32>;
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.10.3",
"version": "1.10.4",
"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>'`.",
@@ -344,6 +344,10 @@
"types": "./src/oidb-services/group-file/upload-private-file-request.ts",
"default": "./src/oidb-services/group-file/upload-private-file-request.ts"
},
"./oidb-services/group-file/finalize-offline-file": {
"types": "./src/oidb-services/group-file/finalize-offline-file.ts",
"default": "./src/oidb-services/group-file/finalize-offline-file.ts"
},
"./oidb-services/group-file/list-group-files-page": {
"types": "./src/oidb-services/group-file/list-group-files-page.ts",
"default": "./src/oidb-services/group-file/list-group-files-page.ts"
+4
View File
@@ -380,6 +380,10 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
//
// Oversize videos throw here; the OneBot layer catches that and falls
// back to file upload (see message-actions.ts video fallback). A file
// element can't be built here — there's no uploaded file_id yet.
return {
commonElem: {
serviceType: 48,
+22 -8
View File
@@ -32,9 +32,21 @@ export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
export const GROUP_VIDEO_CMD_ID = 1005;
export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
const MAX_VIDEO_SIZE_HARD = 1536 * 1024 * 1024;
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
export function getVideoSourceSize(element: MessageElement): number | null {
if (element.fileSize && element.fileSize > 0) return element.fileSize;
const source = element.url || element.fileId || '';
if (!source) return null;
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
return fs.statSync(local).size;
}
return null;
}
const FALLBACK_THUMB = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
'base64',
@@ -276,13 +288,12 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
// Pre-check on disk size BEFORE reading bytes into memory. The later
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
// run after we'd already allocated the entire file (so a 10 GiB
// local path still OOMs us before the check fires).
const stat = fs.statSync(local);
if (stat.size > MAX_VIDEO_SIZE_HARD) {
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE_HARD / (1024 * 1024)} MB`);
}
if (stat.size > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
moduleLog.warn('video exceeds 100 MB (%d MB), trying Highway upload', stat.size / (1024 * 1024));
}
return {
bytes: new Uint8Array(fs.readFileSync(local)),
@@ -291,7 +302,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
};
}
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE_HARD);
const fileName = element.fileName || loaded.fileName || '';
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
@@ -378,8 +389,11 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
try {
const staged = await stageVideoSource(element, tempDir, cleanups);
if (staged.bytes.length === 0) throw new Error('video file is empty');
if (staged.bytes.length > MAX_VIDEO_SIZE_HARD) {
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE_HARD / (1024 * 1024)} MB`);
}
if (staged.bytes.length > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
moduleLog.warn('video bytes exceed 100 MB (%d MB), Highway upload may fail', staged.bytes.length / (1024 * 1024));
}
const hashes = computeHashes(staged.bytes);
@@ -0,0 +1,60 @@
// 0xE37_800 — c2c (private) offline-file finalize.
//
// Runs AFTER the Highway PUT for a private file. The apply (0xE37_1700)
// + Highway upload get the bytes onto the server, but the recipient
// can't download the file until this call returns the server-issued
// download routing (metadata). Those fields ride along in the outgoing
// PbSendMsg as `FileExtra.field6` — without them the receiver's client
// shows "文件传输失败" even though PbSendMsg returned ok.
//
// NapCat runs this unconditionally (even when the apply reports the file
// already exists). Ported from NapCat `highway/DownloadOfflineFile`.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbOfflineFileFinalizeReq,
OidbOfflineFileFinalizeResp,
OidbOfflineFileMetadata,
} from '@snowluma/proto-defs/oidb-actions/media';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace FinalizeOfflineFile {
export const command = 0xE37;
export const subCommand = 800;
export interface Params {
senderUid: string;
receiverUid: string;
fileUuid: string;
fileHash: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbOfflineFileFinalizeReq => ({
subCommand: 800,
field2: 0,
body: {
senderUid: p.senderUid,
receiverUid: p.receiverUid,
fileUuid: p.fileUuid,
fileHash: p.fileHash,
},
field101: 3,
field102: 1,
field200: 1,
});
export const deserialize = (_ctx: Deps, body: OidbOfflineFileFinalizeResp): OidbOfflineFileMetadata =>
body.body?.metadata ?? {};
export const encode = (env: OidbBase<OidbOfflineFileFinalizeReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbOfflineFileFinalizeReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbOfflineFileFinalizeResp> =>
protobuf_decode<OidbBase<OidbOfflineFileFinalizeResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OidbOfflineFileMetadata> =>
invokeOidb(deps, FinalizeOfflineFile, params);
}
@@ -0,0 +1,120 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { FileExtra } from '@snowluma/proto-defs/message';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FinalizeOfflineFile } from '../../../src/oidb-services/group-file/finalize-offline-file';
import { env, m, s, v } from '../_pb-oracle';
// `bytes` fields are wire type 2 — identical framing to a sub-message, so the
// oracle's `m()` (tag + length + payload) doubles as the bytes emitter.
const b = m;
function makeDeps(resp?: OidbOfflineFileFinalizeResp) {
const responseData = resp !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbOfflineFileFinalizeResp>>({ body: resp }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FinalizeOfflineFile (0xE37_800)', () => {
it('declares 0xE37_800', () => {
expect(FinalizeOfflineFile.command).toBe(0xE37);
expect(FinalizeOfflineFile.subCommand).toBe(800);
});
it('serializes the request body byte-for-byte (oracle locks every tag)', async () => {
const deps = makeDeps({});
await FinalizeOfflineFile.invoke(deps, {
senderUid: 'su', receiverUid: 'ru', fileUuid: 'uuid', fileHash: 'hh',
});
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0xe37_800');
// body(10) { senderUid(10) receiverUid(20) fileUuid(30) fileHash(40) }
const innerBody = [...s(10, 'su'), ...s(20, 'ru'), ...s(30, 'uuid'), ...s(40, 'hh')];
// req: subCommand(1)=800, field2(2)=0 omitted, body(10), field101(101)=3,
// field102(102)=1, field200(200)=1
const req = [...v(1, 800), ...m(10, innerBody), ...v(101, 3), ...v(102, 1), ...v(200, 1)];
const expected = env(0xE37, 800, req, false);
expect(Buffer.from(bytes).toString('hex')).toBe(expected);
});
it('extracts the download-routing metadata from field30 of the response', async () => {
const deps = makeDeps({
body: { metadata: { field3: 5, field100: new Uint8Array([9, 9]), field101: new Uint8Array([8]), field110: 7, timestamp1: 42 } },
});
const meta = await FinalizeOfflineFile.invoke(deps, {
senderUid: 'su', receiverUid: 'ru', fileUuid: 'uuid', fileHash: 'hh',
});
expect(meta.field3).toBe(5);
expect(meta.field110).toBe(7);
expect(meta.timestamp1).toBe(42);
expect(Array.from(meta.field100 ?? [])).toEqual([9, 9]);
expect(Array.from(meta.field101 ?? [])).toEqual([8]);
});
it('returns {} when the response carries no metadata', async () => {
const deps = makeDeps({});
const meta = await FinalizeOfflineFile.invoke(deps, {
senderUid: 'su', receiverUid: 'ru', fileUuid: 'uuid', fileHash: 'hh',
});
expect(meta).toEqual({});
});
});
describe('FileExtra.field6 (c2c download routing — issue #157)', () => {
it('encodes field6.field2 with the exact NapCat tag layout', () => {
const extra: FileExtra = {
field6: {
field2: {
field1: 7,
fileUuid: 'uu',
fileName: 'n.bin',
field6: 3,
field7: new Uint8Array([1, 2]),
field8: new Uint8Array([3]),
timestamp1: 99,
fileHash: 'hh',
selfUid: 'su',
destUid: 'du',
},
},
};
const hex = Buffer.from(protobuf_encode<FileExtra>(extra)).toString('hex');
// PrivateFileExtraField2 in ascending tag order:
// field1(1) fileUuid(4) fileName(5) field6(6) field7(7,bytes)
// field8(8,bytes) timestamp1(9) fileHash(14) selfUid(15) destUid(16)
const f2 = [
...v(1, 7),
...s(4, 'uu'),
...s(5, 'n.bin'),
...v(6, 3),
...b(7, [1, 2]),
...b(8, [3]),
...v(9, 99),
...s(14, 'hh'),
...s(15, 'su'),
...s(16, 'du'),
];
// PrivateFileExtra { field2(2) } → FileExtra { field6(6) }
const expected = Buffer.from(m(6, m(2, f2))).toString('hex');
expect(hex).toBe(expected);
});
it('round-trips field6 through encode/decode', () => {
const extra: FileExtra = {
file: { fileUuid: 'u', fileName: 'f', subcmd: 1 },
field6: { field2: { field1: 1, fileUuid: 'u', fileName: 'f', timestamp1: 5, selfUid: 's', destUid: 'd' } },
};
const back = protobuf_decode<FileExtra>(protobuf_encode<FileExtra>(extra));
expect(back.field6?.field2).toMatchObject({
field1: 1, fileUuid: 'u', fileName: 'f', timestamp1: 5, selfUid: 's', destUid: 'd',
});
expect(back.file?.subcmd).toBe(1);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.10.3",
"version": "1.10.4",
"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.",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.10.3",
"version": "1.10.4",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.10.3",
"version": "1.10.4",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.10.3",
"version": "1.10.4",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.10.3",
"version": "1.10.4",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.10.3",
"version": "1.10.4",
"type": "module",
"scripts": {
"dev": "vite",
@@ -1,7 +1,8 @@
// "通用设置" tab — fields that apply to the whole OneBotInstance rather
// than any specific adapter: the music-sign service URL and the built-in
// `#sl` status command. Edits here mark the config dirty and are
// auto-saved with debounce by the parent ConfigPage.
// "通用设置" tab — per-account fields that apply to the whole OneBotInstance
// rather than any specific adapter: the built-in `#sl` status command and the
// notification opt-in. Edits here mark the config dirty and are auto-saved with
// debounce by the parent ConfigPage. (Deployment-wide knobs like the music-sign
// URL live in Settings → 全局配置, not here.)
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -21,19 +22,6 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
<Label>音乐签名服务 URL</Label>
<Input
type="url"
placeholder="留空则不启用"
value={config.musicSignUrl ?? ''}
onChange={(e) => onChange({ ...config, musicSignUrl: e.target.value || undefined })}
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。
</p>
</div>
<div className="flex flex-col gap-4 rounded-lg border bg-card/40 p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
@@ -2,9 +2,24 @@
// copy of the adapter until the user clicks save (so cancel really does
// throw away changes). Validation is minimal — blank-name and dup-name
// disable the save button; everything else is best-effort coercion.
//
// Visual language: Apple-HIG grouped-list flavour (matches debug-page) —
// captioned sections, soft rounded cards, settings rows with a label on the
// left and a control (toggle / custom dropdown) on the right.
import { useRef, useState } from 'react';
import { Check, Copy, Eye, EyeOff } from 'lucide-react';
import { useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import {
ArrowLeftRight,
ArrowUpRight,
Check,
Copy,
Eye,
EyeOff,
Radio,
Server,
type LucideIcon,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -14,9 +29,10 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { DropdownSelect, type DropdownOption } from '@/components/ui/dropdown-select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { cn } from '@/lib/utils';
import type {
HttpClientNetwork,
@@ -32,6 +48,13 @@ import { NETWORK_TABS } from './defaults';
type AnyAdapter<K extends NetworkKind> = OneBotNetworks[K][number];
const KIND_ICON: Record<NetworkKind, LucideIcon> = {
httpServers: Server,
httpClients: ArrowUpRight,
wsServers: Radio,
wsClients: ArrowLeftRight,
};
interface NodeEditDialogProps<K extends NetworkKind> {
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -49,6 +72,7 @@ interface NodeEditDialogProps<K extends NetworkKind> {
export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps<K>) {
const { open, onOpenChange, kind, initial, isEdit, otherNames, onSubmit } = props;
const tab = NETWORK_TABS[kind];
const Icon: LucideIcon = KIND_ICON[kind];
// Local draft. The parent unmounts this component on close so each
// open gets a fresh `initial` via useState's lazy init — no effect-based
@@ -63,62 +87,101 @@ export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps
const patch = (changes: Partial<AnyAdapter<K>>) => setDraft({ ...draft, ...changes } as AnyAdapter<K>);
const isWs = kind === 'wsServers' || kind === 'wsClients';
const role = ((draft as WsServerNetwork | WsClientNetwork).role ?? 'Universal') as WsRole;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-xl">
<DialogHeader>
<DialogTitle>{isEdit ? `编辑 ${tab.noun}` : `新建 ${tab.noun}`}</DialogTitle>
<DialogDescription>{tab.description}</DialogDescription>
<div className="flex items-center gap-3">
<div className="flex size-11 shrink-0 items-center justify-center rounded-2xl bg-primary/10 text-primary">
<Icon className="size-5" />
</div>
<div className="min-w-0">
<DialogTitle>{isEdit ? `编辑 ${tab.noun}` : `新建 ${tab.noun}`}</DialogTitle>
<DialogDescription className="mt-0.5">{tab.description}</DialogDescription>
</div>
</div>
</DialogHeader>
<div className="flex flex-col gap-3">
<Field
label="名称"
placeholder="自定义"
value={draft.name}
onChange={(v) => patch({ name: v } as Partial<AnyAdapter<K>>)}
error={blankName ? '请填写名称' : duplicateName ? '名称与其它节点重复' : undefined}
/>
<KindFields kind={kind} draft={draft} patch={patch} />
<TokenField
label="授权 Token"
placeholder="不填则无密码"
value={draft.accessToken}
onChange={(v) => patch({ accessToken: v || undefined } as Partial<AnyAdapter<K>>)}
/>
<div className="grid gap-3 border-t pt-3 sm:grid-cols-2">
<SegmentedField
label="消息格式"
value={(draft.messageFormat ?? 'array') as MessageFormat}
options={FORMAT_OPTIONS}
onChange={(v) => patch({ messageFormat: v } as Partial<AnyAdapter<K>>)}
/>
<SegmentedField
label="上报自身消息"
value={draft.reportSelfMessage ? 'on' : 'off'}
options={REPORT_OPTIONS}
onChange={(v) => patch({ reportSelfMessage: v === 'on' } as Partial<AnyAdapter<K>>)}
/>
</div>
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
<div>
<Label className="text-sm">启用</Label>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
<div className="flex flex-col gap-5">
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0 }}
className="flex items-center justify-between gap-4 rounded-2xl border border-border/60 bg-card/60 px-4 py-3.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)]"
>
<div className="min-w-0">
<Label className="text-sm font-medium text-foreground">启用</Label>
<p className="mt-0.5 text-[11px] leading-relaxed text-muted-foreground">
关闭后保存即可保留配置但不启动该节点
</p>
</div>
<ToggleSwitch
value={draft.enabled !== false}
onChange={(v) =>
patch({ enabled: v ? undefined : false } as Partial<AnyAdapter<K>>)
}
onChange={(v) => patch({ enabled: v ? undefined : false } as Partial<AnyAdapter<K>>)}
ariaLabel="启用"
/>
</div>
</motion.div>
<Section caption="连接" delay={0.05}>
<div className="flex flex-col gap-3 p-4">
<Field
label="名称"
placeholder="自定义"
value={draft.name}
onChange={(v) => patch({ name: v } as Partial<AnyAdapter<K>>)}
error={blankName ? '请填写名称' : duplicateName ? '名称与其它节点重复' : undefined}
/>
<KindFields kind={kind} draft={draft} patch={patch} />
</div>
</Section>
<Section caption="鉴权" delay={0.1}>
<div className="p-4">
<TokenField
label="授权 Token"
placeholder="不填则无密码"
value={draft.accessToken}
onChange={(v) => patch({ accessToken: v || undefined } as Partial<AnyAdapter<K>>)}
/>
</div>
</Section>
<Section caption="行为" delay={0.15}>
<div className="divide-y divide-border/60">
<SettingRow label="消息格式" desc="数组为标准 OneBot 段,CQ 码为兼容字符串">
<DropdownSelect
className="w-32"
ariaLabel="消息格式"
value={(draft.messageFormat ?? 'array') as MessageFormat}
options={FORMAT_OPTIONS}
onChange={(v) => patch({ messageFormat: v } as Partial<AnyAdapter<K>>)}
/>
</SettingRow>
{isWs && (
<SettingRow label="角色" desc="Universal 收发合一,Event / Api 分离">
<DropdownSelect
className="w-32"
ariaLabel="角色"
value={role}
options={WS_ROLE_OPTIONS}
onChange={(v) => patch({ role: v } as unknown as Partial<AnyAdapter<K>>)}
/>
</SettingRow>
)}
<SettingRow label="上报自身消息" desc="将机器人自己发送的消息也作为 message_sent 事件上报">
<ToggleSwitch
value={!!draft.reportSelfMessage}
onChange={(v) => patch({ reportSelfMessage: v } as Partial<AnyAdapter<K>>)}
ariaLabel="上报自身消息"
/>
</SettingRow>
</div>
</Section>
</div>
<DialogFooter>
@@ -141,6 +204,36 @@ export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps
);
}
// ─────────────── grouped-list scaffolding ───────────────
/** Captioned inset section — the iOS "grouped list" unit. */
function Section({ caption, delay, children }: { caption: string; delay: number; children: ReactNode }) {
return (
<motion.section
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay }}
className="flex flex-col gap-1.5"
>
<span className="px-1 text-[11px] font-medium text-muted-foreground">{caption}</span>
<div className="overflow-hidden rounded-2xl border border-border/60 bg-card/40">{children}</div>
</motion.section>
);
}
/** Settings row — label (+ optional subtitle) on the left, control on the right. */
function SettingRow({ label, desc, children }: { label: string; desc?: string; children: ReactNode }) {
return (
<div className="flex items-center justify-between gap-4 px-4 py-3">
<div className="min-w-0">
<Label className="text-[13px] text-foreground">{label}</Label>
{desc && <p className="mt-0.5 text-[11px] leading-relaxed text-muted-foreground">{desc}</p>}
</div>
<div className="shrink-0">{children}</div>
</div>
);
}
// ─────────────── kind-specific field strips ───────────────
interface KindFieldsProps<K extends NetworkKind> {
@@ -151,7 +244,8 @@ interface KindFieldsProps<K extends NetworkKind> {
function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsProps<K>) {
// Per-branch narrowing — TS can't follow the generic relationship so
// each arm casts once. Field components receive specific shapes.
// each arm casts once. Field components receive specific shapes. The WS
// `role` lives in the behaviour section, so it is intentionally absent here.
if (kind === 'httpServers') {
const it = draft as HttpServerNetwork;
const set = patch as (c: Partial<HttpServerNetwork>) => void;
@@ -204,41 +298,33 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
const it = draft as WsServerNetwork;
const set = patch as (c: Partial<WsServerNetwork>) => void;
return (
<>
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="0.0.0.0"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
<Field
label="端口"
type="number"
value={it.port}
onChange={(v) => set({ port: Number(v) || 0 })}
/>
<Field
label="路径"
placeholder="/"
value={it.path}
onChange={(v) => set({ path: v || undefined })}
/>
</div>
<SelectField
label="角色"
value={(it.role ?? 'Universal') as WsRole}
options={WS_ROLE_OPTIONS}
onChange={(v) => set({ role: v })}
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="0.0.0.0"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
</>
<Field
label="端口"
type="number"
value={it.port}
onChange={(v) => set({ port: Number(v) || 0 })}
/>
<Field
label="路径"
placeholder="/"
value={it.path}
onChange={(v) => set({ path: v || undefined })}
/>
</div>
);
}
if (kind === 'wsClients') {
const it = draft as WsClientNetwork;
const set = patch as (c: Partial<WsClientNetwork>) => void;
return (
<>
<div className="grid gap-3 sm:grid-cols-[1fr_160px]">
<Field
label="目标 URL"
type="url"
@@ -246,21 +332,13 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
value={it.url}
onChange={(v) => set({ url: v })}
/>
<div className="grid gap-3 sm:grid-cols-2">
<SelectField
label="角色"
value={(it.role ?? 'Universal') as WsRole}
options={WS_ROLE_OPTIONS}
onChange={(v) => set({ role: v })}
/>
<Field
label="重连间隔 (ms)"
type="number"
value={it.reconnectIntervalMs}
onChange={(v) => set({ reconnectIntervalMs: Number(v) || undefined })}
/>
</div>
</>
<Field
label="重连间隔 (ms)"
type="number"
value={it.reconnectIntervalMs}
onChange={(v) => set({ reconnectIntervalMs: Number(v) || undefined })}
/>
</div>
);
}
return null;
@@ -393,112 +471,12 @@ function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
);
}
interface SegmentedOption<T extends string> {
value: T;
label: string;
}
function SegmentedField<T extends string>({
label,
value,
options,
onChange,
}: {
label: string;
value: T;
options: ReadonlyArray<SegmentedOption<T>>;
onChange: (v: T) => void;
}) {
return (
<div className="flex flex-col gap-1.5">
<Label>{label}</Label>
<div className="flex flex-wrap gap-1 rounded-md border bg-muted/30 p-1">
{options.map((opt) => {
const active = value === opt.value;
return (
<button
key={opt.value}
type="button"
onClick={() => onChange(opt.value)}
className={cn(
'flex-1 rounded px-2.5 py-1 text-xs transition-colors cursor-pointer',
active ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:bg-accent/50',
)}
>
{opt.label}
</button>
);
})}
</div>
</div>
);
}
function SelectField<T extends string>({
label,
value,
options,
onChange,
}: {
label: string;
value: T;
options: ReadonlyArray<SegmentedOption<T>>;
onChange: (v: T) => void;
}) {
return (
<div className="flex flex-col gap-1.5">
<Label>{label}</Label>
<Select value={value} onChange={(e) => onChange(e.target.value as T)}>
{options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</Select>
</div>
);
}
interface ToggleSwitchProps {
value: boolean;
onChange: (v: boolean) => void;
ariaLabel: string;
}
function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) {
return (
<button
type="button"
role="switch"
aria-checked={value ? 'true' : 'false'}
aria-label={ariaLabel}
onClick={() => onChange(!value)}
className={cn(
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
value ? 'border-primary bg-primary' : 'border-input bg-muted',
)}
>
<span
className={cn(
'inline-block size-4 rounded-full bg-background shadow-sm transition-transform',
value ? 'translate-x-[22px]' : 'translate-x-1',
)}
/>
</button>
);
}
const FORMAT_OPTIONS: ReadonlyArray<SegmentedOption<MessageFormat>> = [
const FORMAT_OPTIONS: ReadonlyArray<DropdownOption<MessageFormat>> = [
{ value: 'array', label: '数组' },
{ value: 'string', label: 'CQ 码' },
];
const REPORT_OPTIONS: ReadonlyArray<SegmentedOption<'on' | 'off'>> = [
{ value: 'on', label: '开启' },
{ value: 'off', label: '关闭' },
];
const WS_ROLE_OPTIONS: ReadonlyArray<SegmentedOption<WsRole>> = [
const WS_ROLE_OPTIONS: ReadonlyArray<DropdownOption<WsRole>> = [
{ value: 'Universal', label: 'Universal' },
{ value: 'Event', label: 'Event' },
{ value: 'Api', label: 'Api' },
@@ -2,11 +2,20 @@
// defined in 设置 → 通知 as toggles; the selection maps to
// OneBotConfig.notifications.channelIds. Lives inside the account's 通用设置 tab,
// so toggling marks the config dirty and rides the parent's debounced autosave.
import { useEffect, useState } from 'react';
import { Loader2 } from 'lucide-react';
//
// Scales to many channels (40+): collapsed by default to a one-line summary of
// selected channels as removable chips; expanded into a searchable, bulk-
// actionable, height-bounded scroll list so it never blows up the page.
import { useEffect, useMemo, useState } from 'react';
import { AnimatePresence, motion } from 'motion/react';
import { ChevronDown, Loader2, Search, X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useApi } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { NotificationChannel } from '@/types';
interface NotificationOptInProps {
@@ -14,9 +23,14 @@ interface NotificationOptInProps {
onChange: (channelIds: string[]) => void;
}
/** How many summary chips to show before collapsing the rest into "+N". */
const CHIP_CAP = 8;
export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInProps) {
const api = useApi();
const [channels, setChannels] = useState<NotificationChannel[] | null>(null);
const [expanded, setExpanded] = useState(false);
const [query, setQuery] = useState('');
useEffect(() => {
let cancelled = false;
@@ -33,6 +47,8 @@ export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInPr
};
}, [api]);
const selected = useMemo(() => new Set(selectedIds), [selectedIds]);
const toggle = (id: string, on: boolean) => {
const set = new Set(selectedIds);
if (on) set.add(id);
@@ -44,43 +60,168 @@ export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInPr
onChange([...known, ...extra]);
};
const selected = new Set(selectedIds);
const selectAll = () => {
// Only enabled channels can ever fire, so "全选" maps to those.
onChange((channels ?? []).filter((c) => c.enabled).map((c) => c.id));
};
const clearAll = () => onChange([]);
// Resolve the selected ids back to channels for the collapsed chip summary.
// Stale ids (channel deleted globally) fall back to showing the raw id.
const selectedChips = useMemo(() => {
const byId = new Map((channels ?? []).map((c) => [c.id, c]));
return selectedIds.map((id) => ({ id, name: byId.get(id)?.name || id }));
}, [channels, selectedIds]);
const filtered = useMemo(() => {
const list = channels ?? [];
const q = query.trim().toLowerCase();
if (!q) return list;
return list.filter((c) => (c.name || c.id).toLowerCase().includes(q) || c.url.toLowerCase().includes(q));
}, [channels, query]);
const total = channels?.length ?? 0;
const selectedCount = selectedIds.length;
return (
<div className="flex flex-col gap-3 rounded-lg border bg-card/40 p-4">
<div>
<Label>上下线通知渠道</Label>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
该账号上线 / 下线时向选中的渠道推送通知。渠道在「设置 → 通知」中全局定义。
</p>
</div>
<div className="flex flex-col gap-3 rounded-xl border bg-card/40 p-4">
{/* header — toggles the editor open/closed */}
<button
type="button"
aria-expanded={expanded}
onClick={() => setExpanded((v) => !v)}
className="flex w-full items-center justify-between gap-3 text-left"
>
<div className="flex min-w-0 items-center gap-2">
<Label className="cursor-pointer text-foreground">上下线通知渠道</Label>
{channels !== null && (
<Badge variant={selectedCount > 0 ? 'default' : 'outline'}>
已选 {selectedCount} / 共 {total}
</Badge>
)}
</div>
<ChevronDown
className={cn('size-4 shrink-0 text-muted-foreground transition-transform duration-200', expanded && 'rotate-180')}
/>
</button>
{channels === null ? (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="size-3.5 animate-spin" /> 加载渠道…
</div>
) : channels.length === 0 ? (
) : total === 0 ? (
<p className="text-[11px] text-muted-foreground">还没有全局渠道——先到「设置 → 通知」添加。</p>
) : (
<div className="flex flex-col divide-y">
{channels.map((ch) => (
<div key={ch.id} className="flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0">
<div className="min-w-0">
<span className="text-sm">{ch.name || ch.id}</span>
{!ch.enabled && <span className="ml-2 text-[10px] text-muted-foreground">(已全局禁用)</span>}
<p className="truncate text-[11px] text-muted-foreground">{ch.url}</p>
<>
{/* collapsed: selected channels as removable chips */}
{!expanded &&
(selectedCount === 0 ? (
<p className="text-[11px] text-muted-foreground">未选择任何渠道。展开以选择。</p>
) : (
<div className="flex flex-wrap gap-1.5">
{selectedChips.slice(0, CHIP_CAP).map((ch) => (
<Badge key={ch.id} variant="secondary" className="max-w-[12rem] pr-1">
<span className="truncate">{ch.name}</span>
<button
type="button"
onClick={() => toggle(ch.id, false)}
aria-label={`移除 ${ch.name}`}
className="ml-0.5 rounded-full p-0.5 text-muted-foreground transition-colors hover:bg-foreground/10 hover:text-foreground"
>
<X className="size-3" />
</button>
</Badge>
))}
{selectedCount > CHIP_CAP && (
<button
type="button"
onClick={() => setExpanded(true)}
className="rounded-full px-2 py-0.5 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground"
>
+{selectedCount - CHIP_CAP} 更多
</button>
)}
</div>
<ToggleSwitch
// Globally-disabled channel: lock the switch and force it off
// (it can never fire, so the per-account opt-in must read off).
value={ch.enabled && selected.has(ch.id)}
onChange={(v) => toggle(ch.id, v)}
ariaLabel={`为该账号启用渠道 ${ch.name || ch.id}`}
disabled={!ch.enabled}
/>
</div>
))}
</div>
))}
{/* expanded: search + bulk + bounded scroll list */}
<AnimatePresence initial={false}>
{expanded && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.22 }}
className="overflow-hidden"
>
<div className="flex flex-col gap-3 pt-1">
<p className="text-[11px] leading-relaxed text-muted-foreground">
该账号上线 / 下线时向选中的渠道推送通知。渠道在「设置 → 通知」中全局定义。
</p>
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="搜索渠道…"
className="h-8 pl-8 text-xs"
/>
</div>
<button
type="button"
onClick={selectAll}
className="rounded-md px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
全选
</button>
<button
type="button"
onClick={clearAll}
className="rounded-md px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
清空
</button>
</div>
{filtered.length === 0 ? (
<p className="py-4 text-center text-[11px] text-muted-foreground">无匹配渠道</p>
) : (
<ScrollArea className="max-h-64 rounded-lg border bg-background/40">
<div className="divide-y divide-border/60">
{filtered.map((ch) => (
<div
key={ch.id}
className="flex items-center justify-between gap-3 px-3 py-2"
>
<div className="min-w-0">
<div className="flex items-center gap-1.5">
<span className="truncate text-sm">{ch.name || ch.id}</span>
{!ch.enabled && (
<span className="shrink-0 text-[10px] text-muted-foreground">(已全局禁用)</span>
)}
</div>
<p className="truncate text-[11px] text-muted-foreground">{ch.url}</p>
</div>
<ToggleSwitch
// Globally-disabled channel: lock the switch and force it off
// (it can never fire, so the per-account opt-in must read off).
value={ch.enabled && selected.has(ch.id)}
onChange={(v) => toggle(ch.id, v)}
ariaLabel={`为该账号启用渠道 ${ch.name || ch.id}`}
disabled={!ch.enabled}
/>
</div>
))}
</div>
</ScrollArea>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</>
)}
</div>
);
@@ -3,7 +3,7 @@ import { motion } from 'motion/react';
import {
Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, Server, ShieldCheck,
Sparkles, Star, Sun, Tag, Upload, Trash2,
SlidersHorizontal, Sparkles, Star, Sun, Tag, Upload, Trash2,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -42,18 +42,43 @@ import { useAppState } from '@/contexts/AppStateContext';
import { cn } from '@/lib/utils';
import { settingsRoute, type SettingsTab } from '@/router';
import { NotificationsPanel } from '@/components/settings/notifications-panel';
import { GlobalConfigPanel } from '@/components/settings/global-config-panel';
import { SystemPanel } from '@/components/settings/system-panel';
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
{ key: 'appearance', label: '外观', icon: Palette },
{ key: 'data', label: '数据与格式', icon: RefreshCw },
{ key: 'advanced', label: '高级', icon: Code2 },
{ key: 'account', label: '账号安全', icon: ShieldCheck },
{ key: 'system', label: '服务', icon: Server },
{ key: 'notifications', label: '通知', icon: Bell },
{ key: 'about', label: '关于', icon: Info },
interface TabDef { key: SettingsTab; label: string; icon: typeof Sun }
// Three domains, rendered as macOS System-Settings-style sidebar sections:
// the dashboard itself (控制台), the all-accounts SnowLuma protocol runtime,
// and the host/deployment (平台). Section headers show on the desktop rail
// only; the mobile strip stays a flat wrap.
const TAB_GROUPS: { title: string; tabs: TabDef[] }[] = [
{
title: '控制台',
tabs: [
{ key: 'appearance', label: '外观', icon: Palette },
{ key: 'data', label: '数据与格式', icon: RefreshCw },
{ key: 'account', label: '账号安全', icon: ShieldCheck },
],
},
{
title: 'SnowLuma',
tabs: [
{ key: 'globalConfig', label: '全局配置', icon: SlidersHorizontal },
{ key: 'notifications', label: '通知', icon: Bell },
],
},
{
title: '平台',
tabs: [
{ key: 'system', label: '服务', icon: Server },
{ key: 'advanced', label: '高级', icon: Code2 },
{ key: 'about', label: '关于', icon: Info },
],
},
];
const TABS: TabDef[] = TAB_GROUPS.flatMap((g) => g.tabs);
export function SettingsPage() {
// Active tab lives in the URL (`?tab=`) so it's deep-linkable — e.g. the
// sidebar update banner jumps straight to 关于. Default tab omits the param.
@@ -83,6 +108,7 @@ export function SettingsPage() {
{tab === 'account' && <AccountPanel />}
{tab === 'system' && <SystemPanel />}
{tab === 'notifications' && <NotificationsPanel />}
{tab === 'globalConfig' && <GlobalConfigPanel />}
{tab === 'about' && <AboutPanel />}
</motion.div>
</div>
@@ -95,32 +121,51 @@ export function SettingsPage() {
function SettingsNav({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsTab) => void }) {
return (
<nav
aria-label="设置导航"
className={cn(
'flex flex-wrap gap-1 rounded-xl border bg-card p-1.5',
'lg:w-52 lg:shrink-0 lg:flex-col lg:flex-nowrap lg:self-start lg:sticky lg:top-4 lg:max-h-[calc(100vh-6rem)] lg:overflow-y-auto',
)}
>
{TABS.map((t) => {
const Icon = t.icon;
const active = tab === t.key;
return (
<button
key={t.key}
type="button"
onClick={() => onChange(t.key)}
aria-current={active ? 'page' : undefined}
{TAB_GROUPS.map((group, gi) => (
<div
key={group.title}
role="group"
aria-labelledby={`settings-nav-group-${gi}`}
className="contents lg:flex lg:flex-col lg:gap-1"
>
<p
id={`settings-nav-group-${gi}`}
className={cn(
'inline-flex shrink-0 items-center gap-2.5 whitespace-nowrap rounded-lg px-3 py-2 text-sm font-medium transition-colors cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 lg:w-full',
active
? 'bg-accent text-foreground ring-1 ring-primary/20'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground',
'hidden select-none px-3 pb-0.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60 lg:block',
gi === 0 ? 'lg:pt-1' : 'lg:pt-3',
)}
>
<Icon className={cn('size-4 shrink-0', active && 'text-primary')} />
{t.label}
</button>
);
})}
{group.title}
</p>
{group.tabs.map((t) => {
const Icon = t.icon;
const active = tab === t.key;
return (
<button
key={t.key}
type="button"
onClick={() => onChange(t.key)}
aria-current={active ? 'page' : undefined}
className={cn(
'inline-flex shrink-0 items-center gap-2.5 whitespace-nowrap rounded-lg px-3 py-2 text-sm font-medium transition-colors cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 lg:w-full',
active
? 'bg-accent text-foreground ring-1 ring-primary/20'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground',
)}
>
<Icon className={cn('size-4 shrink-0', active && 'text-primary')} />
{t.label}
</button>
);
})}
</div>
))}
</nav>
);
}
@@ -0,0 +1,210 @@
// Settings → 全局配置 tab. Deployment-wide SnowLuma knobs (config/snowluma.json):
// rkey fallback servers + the music-card signing URL. Same UX as the other
// settings panels — debounced auto-save, no explicit save button. Unlike the
// channel editor these are typed inline, so the server's normalized result is
// NOT written back onto the inputs while editing (that would erase a half-typed
// URL); the store reconciles on the next load. Invalid entries are flagged
// client-side and simply dropped by the server on save.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AlertTriangle, KeyRound, Loader2, Music, Plus, RefreshCw, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useApi } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { GlobalSettings } from '@/types';
const MUSIC_SIGN_DEFAULT = 'https://ss.xingzhige.com/music_card/card';
function isHttpUrl(value: string): boolean {
try {
const u = new URL(value);
return (u.protocol === 'http:' || u.protocol === 'https:') && u.host.length > 0;
} catch {
return false;
}
}
export function GlobalConfigPanel() {
const api = useApi();
const [config, setConfig] = useState<GlobalSettings | null>(null);
const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const saveTimer = useRef<number | null>(null);
const msgTimer = useRef<number | null>(null);
const saveGen = useRef(0);
const load = useCallback(async () => {
setLoading(true);
setLoadFailed(false);
try {
setConfig(await api.globalConfig.get());
} catch {
setLoadFailed(true);
} finally {
setLoading(false);
}
}, [api]);
useEffect(() => {
void load();
}, [load]);
useEffect(
() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
if (msgTimer.current) clearTimeout(msgTimer.current);
},
[],
);
const flash = (kind: 'ok' | 'err', text: string) => {
setMsg({ kind, text });
if (msgTimer.current) clearTimeout(msgTimer.current);
msgTimer.current = window.setTimeout(() => setMsg(null), 2400);
};
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
* inputs from the server's normalized response (it would wipe a half-typed
* URL); a generation guard just confirms the latest save. */
const commit = (next: GlobalSettings) => {
setConfig(next);
const gen = ++saveGen.current;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = window.setTimeout(() => {
void api.globalConfig
.save(next)
.then(() => {
if (saveGen.current !== gen) return;
// The server drops invalid (non-http) entries; say so rather than a
// bare "已保存" next to a still-visible rejected value.
const dropped = next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim()))
|| (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
})
.catch(() => {
if (saveGen.current !== gen) return;
flash('err', '保存失败,请检查服务器日志');
});
}, 500);
};
if (loading) {
return (
<div className="flex items-center gap-2 rounded-lg border bg-card/40 p-6 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" /> 加载中…
</div>
);
}
if (loadFailed || !config) {
return (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
<AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} />
<p className="text-sm">加载全局配置失败</p>
<Button variant="outline" size="sm" onClick={() => void load()}>
<RefreshCw className="size-3.5" /> 重试
</Button>
</div>
);
}
const servers = config.rkey.fallbackServers;
const setServers = (next: string[]) => commit({ ...config, rkey: { fallbackServers: next } });
return (
<div className="flex flex-col gap-4">
{/* rkey fallback servers */}
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
<div className="flex items-start gap-2 text-[11px] leading-relaxed text-muted-foreground">
<KeyRound className="mt-0.5 size-3.5 shrink-0" />
<p>
图片 / 文件下载链接需要服务器签发的 <code className="font-mono">rkey</code>。SnowLuma 默认走内核获取;
当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。
<strong className="font-medium text-foreground/80">默认留空=关闭</strong>,不配置就不会联系任何第三方。
建议填你自建的端点。
</p>
</div>
<div className="flex flex-col gap-2 border-t pt-3">
<div className="flex items-center justify-between">
<Label>rkey 回退服务器</Label>
<Button variant="outline" size="sm" onClick={() => setServers([...servers, ''])}>
<Plus className="size-3.5" /> 添加
</Button>
</div>
{servers.length === 0 ? (
<p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
未配置回退服务器(rkey 回退已关闭)
</p>
) : (
<div className="flex flex-col gap-2">
{servers.map((url, i) => {
const invalid = url.trim().length > 0 && !isHttpUrl(url.trim());
return (
<div key={i} className="flex items-center gap-2">
<Input
type="url"
inputMode="url"
spellCheck={false}
placeholder="https://your-rkey-server.example/rkeys"
value={url}
aria-invalid={invalid}
className={cn('font-mono text-xs', invalid && 'border-destructive focus-visible:ring-destructive')}
onChange={(e) => setServers(servers.map((s, idx) => (idx === i ? e.target.value : s)))}
/>
<Button
variant="ghost"
size="icon-sm"
aria-label="删除"
className="shrink-0 text-muted-foreground hover:text-destructive"
onClick={() => setServers(servers.filter((_, idx) => idx !== i))}
>
<Trash2 className="size-4" />
</Button>
</div>
);
})}
<p className="text-[11px] leading-relaxed text-muted-foreground">
端点需返回 <code className="font-mono">{'{ group_rkey, private_rkey, expired_time }'}</code>
(兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。
</p>
</div>
)}
</div>
</div>
{/* music sign URL */}
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
<div className="flex items-start gap-2 text-[11px] leading-relaxed text-muted-foreground">
<Music className="mt-0.5 size-3.5 shrink-0" />
<p>音乐分享卡片的签名服务,对所有账号统一生效。留空则使用内置默认服务。</p>
</div>
<div className="flex flex-col gap-1.5 border-t pt-3">
<Label>音乐签名服务 URL</Label>
<Input
type="url"
inputMode="url"
spellCheck={false}
placeholder={MUSIC_SIGN_DEFAULT}
value={config.musicSignUrl}
aria-invalid={config.musicSignUrl.trim().length > 0 && !isHttpUrl(config.musicSignUrl.trim())}
className={cn(
'font-mono text-xs',
config.musicSignUrl.trim().length > 0 && !isHttpUrl(config.musicSignUrl.trim())
&& 'border-destructive focus-visible:ring-destructive',
)}
onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })}
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
内置默认:<code className="font-mono">{MUSIC_SIGN_DEFAULT}</code>
</p>
</div>
</div>
{msg && <p className={cn('text-xs', msg.kind === 'ok' ? 'text-success' : 'text-destructive')}>{msg.text}</p>}
</div>
);
}
@@ -0,0 +1,143 @@
import { useEffect, useRef, useState } from 'react';
import { AnimatePresence, motion } from 'motion/react';
import { Check, ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface DropdownOption<T extends string> {
value: T;
label: string;
}
interface DropdownSelectProps<T extends string> {
value: T;
options: ReadonlyArray<DropdownOption<T>>;
onChange: (v: T) => void;
ariaLabel: string;
className?: string;
}
/**
* Custom (non-native) dropdown with an Apple-HIG flavour: a calm trigger that
* mirrors {@link Input}'s height/border, a soft floating menu that springs in,
* and a trailing check on the selected row. Keyboard-driven (arrows / enter /
* escape) and closes on outside pointer-down. Use when the design wants a menu
* that matches the surrounding chrome — the plain `Select` stays the zero-dep
* native fallback for dense forms.
*/
export function DropdownSelect<T extends string>({
value,
options,
onChange,
ariaLabel,
className,
}: DropdownSelectProps<T>) {
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
const rootRef = useRef<HTMLDivElement>(null);
const selected = options.find((o) => o.value === value);
useEffect(() => {
if (!open) return;
// Seed the keyboard highlight on the current selection each time we open.
setActive(Math.max(0, options.findIndex((o) => o.value === value)));
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener('pointerdown', onPointer);
return () => document.removeEventListener('pointerdown', onPointer);
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
const choose = (v: T) => {
onChange(v);
setOpen(false);
};
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Escape' && open) {
// Swallow so the surrounding Dialog doesn't also close on the same key.
e.preventDefault();
e.stopPropagation();
setOpen(false);
return;
}
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
if (!open) {
setOpen(true);
return;
}
setActive((i) => {
const n = options.length;
return e.key === 'ArrowDown' ? (i + 1) % n : (i - 1 + n) % n;
});
return;
}
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (!open) setOpen(true);
else if (options[active]) choose(options[active].value);
}
};
return (
<div ref={rootRef} className={cn('relative', className)}>
<button
type="button"
aria-haspopup="listbox"
aria-expanded={open}
aria-label={ariaLabel}
onClick={() => setOpen((o) => !o)}
onKeyDown={onKeyDown}
className={cn(
'flex h-9 w-full items-center justify-between gap-2 rounded-lg border border-border bg-transparent px-3 text-sm shadow-xs outline-none transition-[color,box-shadow]',
'hover:bg-accent/40 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
)}
>
<span className="truncate">{selected?.label ?? ''}</span>
<ChevronDown
className={cn(
'size-4 shrink-0 text-muted-foreground transition-transform duration-200',
open && 'rotate-180',
)}
/>
</button>
<AnimatePresence>
{open && (
<motion.ul
role="listbox"
aria-label={ariaLabel}
initial={{ opacity: 0, y: -4, scale: 0.97 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -4, scale: 0.97 }}
transition={{ type: 'spring', stiffness: 600, damping: 38 }}
className="absolute inset-x-0 top-[calc(100%+4px)] z-50 origin-top overflow-hidden rounded-xl border border-border/60 bg-card p-1 shadow-lg backdrop-blur-sm"
>
{options.map((o, i) => {
const isSel = o.value === value;
const isActive = i === active;
return (
<li key={o.value} role="option" aria-selected={isSel}>
<button
type="button"
tabIndex={-1}
onMouseEnter={() => setActive(i)}
onClick={() => choose(o.value)}
className={cn(
'flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors',
isActive ? 'bg-accent text-accent-foreground' : 'text-foreground',
)}
>
<span className="truncate">{o.label}</span>
{isSel && <Check className="size-4 shrink-0 text-primary" />}
</button>
</li>
);
})}
</motion.ul>
)}
</AnimatePresence>
</div>
);
}
+14 -1
View File
@@ -1,4 +1,4 @@
import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types';
import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
@@ -48,6 +48,7 @@ class HttpApiClient implements ApiClient {
readonly update: ApiClient['update'];
readonly ui: ApiClient['ui'];
readonly notifications: ApiClient['notifications'];
readonly globalConfig: ApiClient['globalConfig'];
readonly systemSettings: ApiClient['systemSettings'];
readonly debug: ApiClient['debug'];
readonly agreements: ApiClient['agreements'];
@@ -190,6 +191,18 @@ class HttpApiClient implements ApiClient {
}),
};
this.globalConfig = {
get: () =>
this.getJson<{ config: GlobalSettings }>('/api/global-config').then((d) => d.config),
save: async (config) => {
const data = await this.postJson<{ success: boolean; config: GlobalSettings }>(
'/api/global-config',
config,
);
return data.config;
},
};
this.agreements = {
get: () => this.getJson<AgreementsPayload>('/api/agreements'),
recordConsent: async (version) => {
+9
View File
@@ -5,6 +5,7 @@ import type {
DebugActionDoc,
DebugInvokeResult,
DebugStreamMessage,
GlobalSettings,
HookProcessInfo,
LogEntry,
LogLevel,
@@ -167,6 +168,14 @@ export interface ApiClient {
test(channelId: string): Promise<{ success: boolean; message?: string; status?: number }>;
};
// ---- global deployment config (rkey fallback servers + musicSignUrl) ----
globalConfig: {
/** Fetch the all-accounts global settings (config/snowluma.json). Bearer-gated. */
get(): Promise<GlobalSettings>;
/** Persist global settings (section-merged + normalized server-side). */
save(config: Partial<GlobalSettings>): Promise<GlobalSettings>;
};
// ---- update check ----
update: {
/** Advisory check for a newer stable release. Read-only — never downloads. */
-1
View File
@@ -62,7 +62,6 @@ export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'],
wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
},
musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined,
statusCommand: normalizeStatusCommand(cfg.statusCommand),
notifications: normalizeNotifications(cfg.notifications),
};
+1 -1
View File
@@ -74,7 +74,7 @@ const debugRoute = createRoute({
});
/** Settings sub-tabs — also the contract for the `?tab=` deep link. */
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'about'] as const;
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'globalConfig', 'about'] as const;
export type SettingsTab = (typeof SETTINGS_TABS)[number];
export const settingsRoute = createRoute({
+13 -1
View File
@@ -107,12 +107,24 @@ export interface StatusCommandConfig {
export interface OneBotConfig {
networks: OneBotNetworks;
musicSignUrl?: string;
statusCommand: StatusCommandConfig;
/** Per-account opt-in to global notification channels (by channel id). */
notifications?: { channelIds: string[] };
}
// ─── Global deployment settings (config/snowluma.json) ──────────────────────
// All-accounts SnowLuma knobs that aren't per-UIN: rkey fallback servers and
// the music-card signing endpoint. Mirrors @snowluma/onebot/global-config.
export interface RKeyConfig {
fallbackServers: string[];
}
export interface GlobalSettings {
rkey: RKeyConfig;
/** Music-card signing service URL. Empty = built-in default. */
musicSignUrl: string;
}
// ─── Notifications (account up/down webhooks) ───────────────────────────────
export type NotificationEventKind = 'offline' | 'online';
+170 -161
View File
@@ -10,8 +10,8 @@ catalogs:
specifier: ~6.0.2
version: 6.0.2
vite:
specifier: ^8.0.8
version: 8.0.8
specifier: ^8.0.16
version: 8.1.0
overrides:
tar: ^7.5.13
@@ -68,10 +68,10 @@ importers:
version: 6.0.2
vite:
specifier: 'catalog:'
version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
version: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/common:
devDependencies:
@@ -83,7 +83,7 @@ importers:
version: 6.0.2
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/core:
dependencies:
@@ -111,7 +111,7 @@ importers:
devDependencies:
'@hono/node-server':
specifier: ^1.19.14
version: 1.19.14(hono@4.12.24)
version: 1.19.14(hono@4.12.27)
'@rollup/plugin-node-resolve':
specifier: ^16.0.3
version: 16.0.3(rollup@4.60.4)
@@ -122,8 +122,8 @@ importers:
specifier: ^10.1.0
version: 10.1.0
hono:
specifier: ^4.12.21
version: 4.12.24
specifier: ^4.12.25
version: 4.12.27
tsx:
specifier: ^4.21.0
version: 4.21.0
@@ -132,13 +132,13 @@ importers:
version: 6.0.2
vite:
specifier: 'catalog:'
version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
version: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vite-plugin-cp:
specifier: ^6.0.3
version: 6.0.3
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/mcp:
dependencies:
@@ -160,10 +160,10 @@ importers:
version: 6.0.2
vite:
specifier: 'catalog:'
version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
version: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/onebot:
dependencies:
@@ -194,10 +194,10 @@ importers:
version: 6.0.2
vite:
specifier: 'catalog:'
version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
version: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/proto-defs:
dependencies:
@@ -232,10 +232,10 @@ importers:
version: 6.0.2
vite:
specifier: 'catalog:'
version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
version: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/proton:
dependencies:
@@ -248,13 +248,13 @@ importers:
version: 24.12.2
tsup:
specifier: ^8.5.0
version: 8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2)
version: 8.5.1(jiti@2.6.1)(postcss@8.5.15)(tsx@4.21.0)(typescript@6.0.2)
vite:
specifier: 'catalog:'
version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
version: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/runtime: {}
@@ -268,7 +268,7 @@ importers:
version: 6.0.2
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/ui:
dependencies:
@@ -338,7 +338,7 @@ importers:
version: 19.2.5(react@19.2.5)
tsup:
specifier: ^8.5.0
version: 8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2)
version: 8.5.1(jiti@2.6.1)(postcss@8.5.15)(tsx@4.21.0)(typescript@6.0.2)
typescript:
specifier: 'catalog:'
version: 6.0.2
@@ -411,7 +411,7 @@ importers:
version: 10.0.1(eslint@10.2.0(jiti@2.6.1))
'@tailwindcss/vite':
specifier: ^4.2.2
version: 4.2.2(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 4.2.2(vite@8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
'@types/node':
specifier: ^25.6.0
version: 25.6.0
@@ -423,7 +423,7 @@ importers:
version: 19.2.3(@types/react@19.2.14)
'@vitejs/plugin-react':
specifier: ^6.0.1
version: 6.0.1(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
version: 6.0.1(vite@8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
eslint:
specifier: ^10.2.0
version: 10.2.0(jiti@2.6.1)
@@ -450,7 +450,7 @@ importers:
version: 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2)
vite:
specifier: 'catalog:'
version: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
version: 8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
packages:
@@ -530,14 +530,14 @@ packages:
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
engines: {node: '>=18'}
'@emnapi/core@1.9.2':
resolution: {integrity: sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==}
'@emnapi/core@1.11.1':
resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==}
'@emnapi/runtime@1.9.2':
resolution: {integrity: sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==}
'@emnapi/runtime@1.11.1':
resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==}
'@emnapi/wasi-threads@1.2.1':
resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}
'@emnapi/wasi-threads@1.2.2':
resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==}
'@epic-web/invariant@1.0.0':
resolution: {integrity: sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==}
@@ -804,14 +804,14 @@ packages:
'@cfworker/json-schema':
optional: true
'@napi-rs/wasm-runtime@1.1.4':
resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==}
'@napi-rs/wasm-runtime@1.1.6':
resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==}
peerDependencies:
'@emnapi/core': ^1.7.1
'@emnapi/runtime': ^1.7.1
'@oxc-project/types@0.124.0':
resolution: {integrity: sha512-VBFWMTBvHxS11Z5Lvlr3IWgrwhMTXV+Md+EQF0Xf60+wAdsGFTBx7X7K/hP4pi8N7dcm1RvcHwDxZ16Qx8keUg==}
'@oxc-project/types@0.137.0':
resolution: {integrity: sha512-WT+Gb24i8hmvo85AIv2oEYouEXkRlKAlT9WaCa3TfLgNCN+GhrJOGZuIlMouAh38Qe4QOx26eUOVsq70qXrywA==}
'@parcel/watcher-android-arm64@2.5.6':
resolution: {integrity: sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==}
@@ -1331,107 +1331,107 @@ packages:
'@radix-ui/rect@1.1.1':
resolution: {integrity: sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==}
'@rolldown/binding-android-arm64@1.0.0-rc.15':
resolution: {integrity: sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==}
'@rolldown/binding-android-arm64@1.1.3':
resolution: {integrity: sha512-DT6Z3PhvioeHMvxo+xHc3KtqggrI7CCTXCmC2h/5zUlp5jVitv7XEy+9q5/7v8IolhlioawpMo8Kg0EEBy7J0g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
'@rolldown/binding-darwin-arm64@1.0.0-rc.15':
resolution: {integrity: sha512-oArR/ig8wNTPYsXL+Mzhs0oxhxfuHRfG7Ikw7jXsw8mYOtk71W0OkF2VEVh699pdmzjPQsTjlD1JIOoHkLP1Fg==}
'@rolldown/binding-darwin-arm64@1.1.3':
resolution: {integrity: sha512-0NwgwsjM7LrsuVnXMK3koTpagBNOhloc/BNjKqZjv4V5zI5r13qx69uVhRx+o5Z0yy4Hzq+lpy7TAgUG/ocvrw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
'@rolldown/binding-darwin-x64@1.0.0-rc.15':
resolution: {integrity: sha512-YzeVqOqjPYvUbJSWJ4EDL8ahbmsIXQpgL3JVipmN+MX0XnXMeWomLN3Fb+nwCmP/jfyqte5I3XRSm7OfQrbyxw==}
'@rolldown/binding-darwin-x64@1.1.3':
resolution: {integrity: sha512-YtiBp4disu6V560loT6PjMdiRaWmVvDNrUunAalbiFx2ggeJwxdAsgZMcoGP17uyAsTwAj5V1niksxlHnVQ1Sw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
'@rolldown/binding-freebsd-x64@1.0.0-rc.15':
resolution: {integrity: sha512-9Erhx956jeQ0nNTyif1+QWAXDRD38ZNjr//bSHrt6wDwB+QkAfl2q6Mn1k6OBPerznjRmbM10lgRb1Pli4xZPw==}
'@rolldown/binding-freebsd-x64@1.1.3':
resolution: {integrity: sha512-yD3EkEdXk2LypPxnf/kSZHirarsI8gcPzc62SukhR9VJTyvV+F9Q/GxWNuCojc7sXyuVC4DxRGhdDK4X8VSsbw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
'@rolldown/binding-linux-arm-gnueabihf@1.0.0-rc.15':
resolution: {integrity: sha512-cVwk0w8QbZJGTnP/AHQBs5yNwmpgGYStL88t4UIaqcvYJWBfS0s3oqVLZPwsPU6M0zlW4GqjP0Zq5MnAGwFeGA==}
'@rolldown/binding-linux-arm-gnueabihf@1.1.3':
resolution: {integrity: sha512-c+8vieQbsD7HNAHKIA34w0GJ9FedFFuJGD+7E6vz7Q3uqAIugL5p45fhlsj4UaAsHpcmlqugBWMhA0/j7o0sIg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@rolldown/binding-linux-arm64-gnu@1.0.0-rc.15':
resolution: {integrity: sha512-eBZ/u8iAK9SoHGanqe/jrPnY0JvBN6iXbVOsbO38mbz+ZJsaobExAm1Iu+rxa4S1l2FjG0qEZn4Rc6X8n+9M+w==}
'@rolldown/binding-linux-arm64-gnu@1.1.3':
resolution: {integrity: sha512-50jD0uUwLvur7Zz9LHz17kaAdTPjn5wN93hEgjvmYFRZwiR7ZJYovTd5ipyWJDAnXKvZ+wgc+/Ika6dwSF5OcA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-arm64-musl@1.0.0-rc.15':
resolution: {integrity: sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==}
'@rolldown/binding-linux-arm64-musl@1.1.3':
resolution: {integrity: sha512-BO9+oPL8K9poZJBfYPsXNtYjPE5uM3qeehT3aFcW4LITOl+iSqhp0abzjR2nWBUNjIZeKXjAEWBZ64WjNoHd6w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/binding-linux-ppc64-gnu@1.0.0-rc.15':
resolution: {integrity: sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==}
'@rolldown/binding-linux-ppc64-gnu@1.1.3':
resolution: {integrity: sha512-f3VpLB1vQ0Eo6ecr/6cekLnvYMFF4YBFoVGkfkvPLq1bAkbAwHYQPZKoAmG6OJyTcxxoC+AvezGx/S1obNC0Mw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-s390x-gnu@1.0.0-rc.15':
resolution: {integrity: sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==}
'@rolldown/binding-linux-s390x-gnu@1.1.3':
resolution: {integrity: sha512-AmurZ26Pqx/RI9N1gzEOCklkKXl927yjfXWUUS0O7Puh8ARM/Ob8qfrD3qnWksScdw6cSrW5PSHE9DyLu7+PtA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-x64-gnu@1.0.0-rc.15':
resolution: {integrity: sha512-023bTPBod7J3Y/4fzAN6QtpkSABR0rigtrwaP+qSEabUh5zf6ELr9Nc7GujaROuPY3uwdSIXWrvhn1KxOvurWA==}
'@rolldown/binding-linux-x64-gnu@1.1.3':
resolution: {integrity: sha512-JJpqs8bRGITDOdbkNKnlojzBabbOHrqjSvDr0IVsZObE1lBcPjxItUEY9eWIDbxaJ3cGrXPWGfGkIxFijg/URg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/binding-linux-x64-musl@1.0.0-rc.15':
resolution: {integrity: sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==}
'@rolldown/binding-linux-x64-musl@1.1.3':
resolution: {integrity: sha512-rSJcdjPxzA/by/6/rYs+v+bXU7UjvnbUWz8MJb6kh6+knqB1dCrtHg0uu7C/4haqJvqdkYHQ5IGn+tCH9GLW/g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/binding-openharmony-arm64@1.0.0-rc.15':
resolution: {integrity: sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==}
'@rolldown/binding-openharmony-arm64@1.1.3':
resolution: {integrity: sha512-hQ3/PYkDJICgevvyNcVrihVeqq7k1Pp3VZ9lY+dauAYUJKO+auqApvANhvR1An9BhmqYKvW2Mu1F9u4DXSMLxQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
'@rolldown/binding-wasm32-wasi@1.0.0-rc.15':
resolution: {integrity: sha512-ApLruZq/ig+nhaE7OJm4lDjayUnOHVUa77zGeqnqZ9pn0ovdVbbNPerVibLXDmWeUZXjIYIT8V3xkT58Rm9u5Q==}
engines: {node: '>=14.0.0'}
'@rolldown/binding-wasm32-wasi@1.1.3':
resolution: {integrity: sha512-Elcv/BtML9lXrV6JuKITc/grN2kYV9gjsQpW8Jfw4ioK0TOkjBjye0nnyqQNy9STNaI20lXNaQBRrD5gSgR0Yg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [wasm32]
'@rolldown/binding-win32-arm64-msvc@1.0.0-rc.15':
resolution: {integrity: sha512-KmoUoU7HnN+Si5YWJigfTws1jz1bKBYDQKdbLspz0UaqjjFkddHsqorgiW1mxcAj88lYUE6NC/zJNwT+SloqtA==}
'@rolldown/binding-win32-arm64-msvc@1.1.3':
resolution: {integrity: sha512-2DrEfhluH9yhiaFApmsjsjwrSYbNcY1oFTzYSP1a535jDbV98zCFanA/96TBUd0iDFcxGmw9QRExwGCXz3U+/g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
'@rolldown/binding-win32-x64-msvc@1.0.0-rc.15':
resolution: {integrity: sha512-3P2A8L+x75qavWLe/Dll3EYBJLQmtkJN8rfh+U/eR3MqMgL/h98PhYI+JFfXuDPgPeCB7iZAKiqii5vqOvnA0g==}
'@rolldown/binding-win32-x64-msvc@1.1.3':
resolution: {integrity: sha512-OL4OMk7UPXOeVGGd3qo5zJyPIljf4AFgk5QAkPPS+OoLuOOozhuaQGC18MxVTnw/06q93gShAJzlwnSCY9YtqA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
'@rolldown/pluginutils@1.0.0-rc.15':
resolution: {integrity: sha512-UromN0peaE53IaBRe9W7CjrZgXl90fqGpK+mIZbA3qSTeYqg3pqpROBdIPvOG3F5ereDHNwoHBI2e50n1BDr1g==}
'@rolldown/pluginutils@1.0.0-rc.7':
resolution: {integrity: sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==}
'@rolldown/pluginutils@1.0.1':
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
'@rollup/plugin-node-resolve@16.0.3':
resolution: {integrity: sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==}
engines: {node: '>=14.0.0'}
@@ -1709,8 +1709,8 @@ packages:
'@tanstack/store@0.9.3':
resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==}
'@tybys/wasm-util@0.10.1':
resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}
'@tybys/wasm-util@0.10.3':
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
'@types/chai@5.2.3':
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
@@ -2342,8 +2342,8 @@ packages:
hermes-parser@0.25.1:
resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==}
hono@4.12.24:
resolution: {integrity: sha512-I36D1s+HgQc55KbhEr4iybfxv/9o1zdpw+XEM6dJa91LqQD0HCoSGdxpRJCZE+aavs87j4V3Ls2OJzq8C/U4iw==}
hono@4.12.27:
resolution: {integrity: sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q==}
engines: {node: '>=16.9.0'}
html-escaper@2.0.2:
@@ -2635,8 +2635,8 @@ packages:
mz@2.7.0:
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
nanoid@3.3.11:
resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
nanoid@3.3.15:
resolution: {integrity: sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
@@ -2740,8 +2740,8 @@ packages:
yaml:
optional: true
postcss@8.5.10:
resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==}
postcss@8.5.15:
resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}
engines: {node: ^10 || ^12 || >=14}
prelude-ls@1.2.1:
@@ -2827,8 +2827,8 @@ packages:
engines: {node: '>= 0.4'}
hasBin: true
rolldown@1.0.0-rc.15:
resolution: {integrity: sha512-Ff31guA5zT6WjnGp0SXw76X6hzGRk/OQq2hE+1lcDe+lJdHSgnSX6nK3erbONHyCbpSj9a9E+uX/OvytZoWp2g==}
rolldown@1.1.3:
resolution: {integrity: sha512-1F1eEtUBtFvcGm1HQ9TiUIUHPQG7mSAODrhIzjxoUEFuo8OcbrGLiVLkevNgj84TE4lnHvnumwFjhJO5Eu135g==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -2977,6 +2977,10 @@ packages:
resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
engines: {node: '>=12.0.0'}
tinyglobby@0.2.17:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'}
tinyrainbow@3.1.0:
resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
engines: {node: '>=14.0.0'}
@@ -3107,13 +3111,13 @@ packages:
resolution: {integrity: sha512-qxKGH3v9wPwUDbDchJf4IH4mRE1zkLWgzZSxwrl8LapwUWm48IFS7SlbRmcF4NquC/fESA5cHFge9E2Ps+woxg==}
engines: {node: '>=14.18.0', vite: '>=3.1.0'}
vite@8.0.8:
resolution: {integrity: sha512-dbU7/iLVa8KZALJyLOBOQ88nOXtNG8vxKuOT4I2mD+Ya70KPceF4IAmDsmU0h1Qsn5bPrvsY9HJstCRh3hG6Uw==}
vite@8.1.0:
resolution: {integrity: sha512-BuJcQK/56NQTWDGn4ABea3q4SSBdNPWwNZKTkkUpcMPnLoquSYH8llRtSUIgoL1KSCpHt5eghLShn50mH36y7Q==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
'@types/node': ^20.19.0 || >=22.12.0
'@vitejs/devtools': ^0.1.0
'@vitejs/devtools': ^0.3.0
esbuild: ^0.27.0 || ^0.28.0
jiti: '>=1.21.0'
less: ^4.0.0
@@ -3341,18 +3345,18 @@ snapshots:
'@bcoe/v8-coverage@1.0.2': {}
'@emnapi/core@1.9.2':
'@emnapi/core@1.11.1':
dependencies:
'@emnapi/wasi-threads': 1.2.1
'@emnapi/wasi-threads': 1.2.2
tslib: 2.8.1
optional: true
'@emnapi/runtime@1.9.2':
'@emnapi/runtime@1.11.1':
dependencies:
tslib: 2.8.1
optional: true
'@emnapi/wasi-threads@1.2.1':
'@emnapi/wasi-threads@1.2.2':
dependencies:
tslib: 2.8.1
optional: true
@@ -3488,9 +3492,9 @@ snapshots:
'@floating-ui/utils@0.2.11': {}
'@hono/node-server@1.19.14(hono@4.12.24)':
'@hono/node-server@1.19.14(hono@4.12.27)':
dependencies:
hono: 4.12.24
hono: 4.12.27
'@humanfs/core@0.19.1': {}
@@ -3526,7 +3530,7 @@ snapshots:
'@modelcontextprotocol/sdk@1.29.0(zod@4.3.6)':
dependencies:
'@hono/node-server': 1.19.14(hono@4.12.24)
'@hono/node-server': 1.19.14(hono@4.12.27)
ajv: 8.20.0
ajv-formats: 3.0.1(ajv@8.20.0)
content-type: 1.0.5
@@ -3536,7 +3540,7 @@ snapshots:
eventsource-parser: 3.1.0
express: 5.2.1
express-rate-limit: 8.5.2(express@5.2.1)
hono: 4.12.24
hono: 4.12.27
jose: 6.2.3
json-schema-typed: 8.0.2
pkce-challenge: 5.0.1
@@ -3546,14 +3550,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)':
'@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)':
dependencies:
'@emnapi/core': 1.9.2
'@emnapi/runtime': 1.9.2
'@tybys/wasm-util': 0.10.1
'@emnapi/core': 1.11.1
'@emnapi/runtime': 1.11.1
'@tybys/wasm-util': 0.10.3
optional: true
'@oxc-project/types@0.124.0': {}
'@oxc-project/types@0.137.0': {}
'@parcel/watcher-android-arm64@2.5.6':
optional: true
@@ -4038,59 +4042,59 @@ snapshots:
'@radix-ui/rect@1.1.1': {}
'@rolldown/binding-android-arm64@1.0.0-rc.15':
'@rolldown/binding-android-arm64@1.1.3':
optional: true
'@rolldown/binding-darwin-arm64@1.0.0-rc.15':
'@rolldown/binding-darwin-arm64@1.1.3':
optional: true
'@rolldown/binding-darwin-x64@1.0.0-rc.15':
'@rolldown/binding-darwin-x64@1.1.3':
optional: true
'@rolldown/binding-freebsd-x64@1.0.0-rc.15':
'@rolldown/binding-freebsd-x64@1.1.3':
optional: true
'@rolldown/binding-linux-arm-gnueabihf@1.0.0-rc.15':
'@rolldown/binding-linux-arm-gnueabihf@1.1.3':
optional: true
'@rolldown/binding-linux-arm64-gnu@1.0.0-rc.15':
'@rolldown/binding-linux-arm64-gnu@1.1.3':
optional: true
'@rolldown/binding-linux-arm64-musl@1.0.0-rc.15':
'@rolldown/binding-linux-arm64-musl@1.1.3':
optional: true
'@rolldown/binding-linux-ppc64-gnu@1.0.0-rc.15':
'@rolldown/binding-linux-ppc64-gnu@1.1.3':
optional: true
'@rolldown/binding-linux-s390x-gnu@1.0.0-rc.15':
'@rolldown/binding-linux-s390x-gnu@1.1.3':
optional: true
'@rolldown/binding-linux-x64-gnu@1.0.0-rc.15':
'@rolldown/binding-linux-x64-gnu@1.1.3':
optional: true
'@rolldown/binding-linux-x64-musl@1.0.0-rc.15':
'@rolldown/binding-linux-x64-musl@1.1.3':
optional: true
'@rolldown/binding-openharmony-arm64@1.0.0-rc.15':
'@rolldown/binding-openharmony-arm64@1.1.3':
optional: true
'@rolldown/binding-wasm32-wasi@1.0.0-rc.15':
'@rolldown/binding-wasm32-wasi@1.1.3':
dependencies:
'@emnapi/core': 1.9.2
'@emnapi/runtime': 1.9.2
'@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)
'@emnapi/core': 1.11.1
'@emnapi/runtime': 1.11.1
'@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)
optional: true
'@rolldown/binding-win32-arm64-msvc@1.0.0-rc.15':
'@rolldown/binding-win32-arm64-msvc@1.1.3':
optional: true
'@rolldown/binding-win32-x64-msvc@1.0.0-rc.15':
'@rolldown/binding-win32-x64-msvc@1.1.3':
optional: true
'@rolldown/pluginutils@1.0.0-rc.15': {}
'@rolldown/pluginutils@1.0.0-rc.7': {}
'@rolldown/pluginutils@1.0.1': {}
'@rollup/plugin-node-resolve@16.0.3(rollup@4.60.4)':
dependencies:
'@rollup/pluginutils': 5.3.0(rollup@4.60.4)
@@ -4247,12 +4251,12 @@ snapshots:
'@tailwindcss/oxide-win32-arm64-msvc': 4.2.2
'@tailwindcss/oxide-win32-x64-msvc': 4.2.2
'@tailwindcss/vite@4.2.2(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
'@tailwindcss/vite@4.2.2(vite@8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
dependencies:
'@tailwindcss/node': 4.2.2
'@tailwindcss/oxide': 4.2.2
tailwindcss: 4.2.2
vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vite: 8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
'@tanstack/history@1.161.6': {}
@@ -4281,7 +4285,7 @@ snapshots:
'@tanstack/store@0.9.3': {}
'@tybys/wasm-util@0.10.1':
'@tybys/wasm-util@0.10.3':
dependencies:
tslib: 2.8.1
optional: true
@@ -4423,10 +4427,10 @@ snapshots:
'@typescript-eslint/types': 8.58.2
eslint-visitor-keys: 5.0.1
'@vitejs/plugin-react@6.0.1(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
'@vitejs/plugin-react@6.0.1(vite@8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
dependencies:
'@rolldown/pluginutils': 1.0.0-rc.7
vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vite: 8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
'@vitest/coverage-istanbul@4.1.4(vitest@4.1.4)':
dependencies:
@@ -4440,7 +4444,7 @@ snapshots:
magicast: 0.5.3
obug: 2.1.1
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
transitivePeerDependencies:
- supports-color
@@ -4456,7 +4460,7 @@ snapshots:
obug: 2.1.1
std-env: 4.1.0
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
'@vitest/expect@4.1.4':
dependencies:
@@ -4467,13 +4471,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
'@vitest/mocker@4.1.4(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
'@vitest/mocker@4.1.4(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
dependencies:
'@vitest/spy': 4.1.4
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vite: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
'@vitest/pretty-format@4.1.4':
dependencies:
@@ -5003,7 +5007,7 @@ snapshots:
dependencies:
hermes-estree: 0.25.1
hono@4.12.24: {}
hono@4.12.27: {}
html-escaper@2.0.2: {}
@@ -5232,7 +5236,7 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
nanoid@3.3.11: {}
nanoid@3.3.15: {}
natural-compare@1.4.0: {}
@@ -5300,17 +5304,17 @@ snapshots:
mlly: 1.8.2
pathe: 2.0.3
postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0):
postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.15)(tsx@4.21.0):
dependencies:
lilconfig: 3.1.3
optionalDependencies:
jiti: 2.6.1
postcss: 8.5.10
postcss: 8.5.15
tsx: 4.21.0
postcss@8.5.10:
postcss@8.5.15:
dependencies:
nanoid: 3.3.11
nanoid: 3.3.15
picocolors: 1.1.1
source-map-js: 1.2.1
@@ -5385,26 +5389,26 @@ snapshots:
path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0
rolldown@1.0.0-rc.15:
rolldown@1.1.3:
dependencies:
'@oxc-project/types': 0.124.0
'@rolldown/pluginutils': 1.0.0-rc.15
'@oxc-project/types': 0.137.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
'@rolldown/binding-android-arm64': 1.0.0-rc.15
'@rolldown/binding-darwin-arm64': 1.0.0-rc.15
'@rolldown/binding-darwin-x64': 1.0.0-rc.15
'@rolldown/binding-freebsd-x64': 1.0.0-rc.15
'@rolldown/binding-linux-arm-gnueabihf': 1.0.0-rc.15
'@rolldown/binding-linux-arm64-gnu': 1.0.0-rc.15
'@rolldown/binding-linux-arm64-musl': 1.0.0-rc.15
'@rolldown/binding-linux-ppc64-gnu': 1.0.0-rc.15
'@rolldown/binding-linux-s390x-gnu': 1.0.0-rc.15
'@rolldown/binding-linux-x64-gnu': 1.0.0-rc.15
'@rolldown/binding-linux-x64-musl': 1.0.0-rc.15
'@rolldown/binding-openharmony-arm64': 1.0.0-rc.15
'@rolldown/binding-wasm32-wasi': 1.0.0-rc.15
'@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.15
'@rolldown/binding-win32-x64-msvc': 1.0.0-rc.15
'@rolldown/binding-android-arm64': 1.1.3
'@rolldown/binding-darwin-arm64': 1.1.3
'@rolldown/binding-darwin-x64': 1.1.3
'@rolldown/binding-freebsd-x64': 1.1.3
'@rolldown/binding-linux-arm-gnueabihf': 1.1.3
'@rolldown/binding-linux-arm64-gnu': 1.1.3
'@rolldown/binding-linux-arm64-musl': 1.1.3
'@rolldown/binding-linux-ppc64-gnu': 1.1.3
'@rolldown/binding-linux-s390x-gnu': 1.1.3
'@rolldown/binding-linux-x64-gnu': 1.1.3
'@rolldown/binding-linux-x64-musl': 1.1.3
'@rolldown/binding-openharmony-arm64': 1.1.3
'@rolldown/binding-wasm32-wasi': 1.1.3
'@rolldown/binding-win32-arm64-msvc': 1.1.3
'@rolldown/binding-win32-x64-msvc': 1.1.3
rollup@4.60.4:
dependencies:
@@ -5589,6 +5593,11 @@ snapshots:
fdir: 6.5.0(picomatch@4.0.4)
picomatch: 4.0.4
tinyglobby@0.2.17:
dependencies:
fdir: 6.5.0(picomatch@4.0.4)
picomatch: 4.0.4
tinyrainbow@3.1.0: {}
toidentifier@1.0.1: {}
@@ -5603,7 +5612,7 @@ snapshots:
tslib@2.8.1: {}
tsup@8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2):
tsup@8.5.1(jiti@2.6.1)(postcss@8.5.15)(tsx@4.21.0)(typescript@6.0.2):
dependencies:
bundle-require: 5.1.0(esbuild@0.27.7)
cac: 6.7.14
@@ -5614,7 +5623,7 @@ snapshots:
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)
postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.15)(tsx@4.21.0)
resolve-from: 5.0.0
rollup: 4.60.4
source-map: 0.7.6
@@ -5623,7 +5632,7 @@ snapshots:
tinyglobby: 0.2.16
tree-kill: 1.2.2
optionalDependencies:
postcss: 8.5.10
postcss: 8.5.15
typescript: 6.0.2
transitivePeerDependencies:
- jiti
@@ -5713,13 +5722,13 @@ snapshots:
transitivePeerDependencies:
- supports-color
vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0):
vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0):
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
postcss: 8.5.10
rolldown: 1.0.0-rc.15
tinyglobby: 0.2.16
postcss: 8.5.15
rolldown: 1.1.3
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 24.12.2
esbuild: 0.27.7
@@ -5728,13 +5737,13 @@ snapshots:
sass: 1.99.0
tsx: 4.21.0
vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0):
vite@8.1.0(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0):
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
postcss: 8.5.10
rolldown: 1.0.0-rc.15
tinyglobby: 0.2.16
postcss: 8.5.15
rolldown: 1.1.3
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 25.6.0
esbuild: 0.27.7
@@ -5743,10 +5752,10 @@ snapshots:
sass: 1.99.0
tsx: 4.21.0
vitest@4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)):
vitest@4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)):
dependencies:
'@vitest/expect': 4.1.4
'@vitest/mocker': 4.1.4(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
'@vitest/mocker': 4.1.4(vite@8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
'@vitest/pretty-format': 4.1.4
'@vitest/runner': 4.1.4
'@vitest/snapshot': 4.1.4
@@ -5763,7 +5772,7 @@ snapshots:
tinyexec: 1.1.1
tinyglobby: 0.2.16
tinyrainbow: 3.1.0
vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
vite: 8.1.0(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 24.12.2
+1 -1
View File
@@ -2,7 +2,7 @@ packages:
- 'packages/*'
catalog:
vite: ^8.0.8
vite: ^8.0.16
typescript: ~6.0.2
overrides: