Commit Graph
1068 Commits
Author SHA1 Message Date
DrSmoothl 85ca207279 refactor(onebot): extract openSqliteDb helper for the three stores
message/media/reaction store 构造器各自逐字复制同一段引导(mkdir 父目录 + 打开
DatabaseSync + PRAGMA journal_mode=WAL + PRAGMA synchronous=NORMAL),改一处 PRAGMA
要改三处。抽 openSqliteDb(dbPath) 收敛,schema init 与路径改写留在各调用方。

- message-store 的 .json→.db 改写保留(改写后同目录,mkdir 目标不变,等价)。
- 三文件删掉不再使用的 fs/path import。

行为严格不变:onebot 516 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认
三处引导等价、路径细节无边角、无回归。
2026-07-01 18:37:42 +08:00
DrSmoothl d89b095af5 refactor(protocol,proto-defs): fold 1:1 subpath exports into wildcards
protocol/package.json 有 273 行专给 91 个 oidb-service(每个 3 行 1:1);加一个
service 忘改 package.json → build 期解析失败。把所有严格 1:1 的目录组折叠成通配符
(moduleResolution:"bundler" 原生支持),消除永久手同步负担。

- protocol:./oidb-services/*(91) + ./highway/*(7) + ./web/*(7) + ./msg-push/*(3);
  bare ./msg-push / ./highway(exact)与单文件 export 原样保留。
- proto-defs:./oidb-actions/*(10)。
- 净 -467/+15 行;两包均 private:true,通配新暴露的少量内部文件无害(exports 只
  gate 跨包解析、无外部消费者、无副作用)。

零源码/import 改动。全套工具链验证:12 包 typecheck Done、protocol/onebot(516)/
core(467)/mcp(22) 测试全绿;对抗性 Agent 端到端解析 136 个真实深导入全部命中、
确认 exact/wildcard 共存正确。
2026-07-01 18:30:45 +08:00
DrSmoothl 15a6fe3785 refactor(onebot): make event converter dispatch an exhaustive registry
阶段 2(零行为改动):把 convertEvent 的 17-arm switch 换成
CONVERTERS: { [K in QQEventVariant['kind']]: ConverterFor<K> | null } 表。mapped
type 对事件类型联合 total——新增一个 kind 却漏写 converter 会**编译报错**,而非
像原 switch 那样静默走 default: return null。

- ptt_trans_result(内部语音转文字事件,不对外)在表里显式标 null,与原 default
  行为等价。
- 派发一次 localized cast 解 correlated-union,纯类型层、运行时等价。
- 护栏实测有效:删任一 kind 条目即 TS2741 编译失败。

onebot 516 全绿、typecheck 干净;对抗性 Agent 逐一核对 17 映射、独立复现护栏报错。
2026-07-01 18:03:02 +08:00
DrSmoothl ae17bc0cf5 refactor(onebot): extract event envelope builders; collapse message triplets
阶段 1(零行为改动):消掉 17 个 converter 各手搓的 time/self_id/post_type 信封,
合并 message 三胞胎。

- 新增 event-converter/envelope.ts:notice/request/message 三个信封 builder,
  converter 只供应各自 post_type 的字段。
- to-notice(12)/to-request(2) 改用 notice()/request()。
- to-message:friend+temp 合成 convertPrivateMessage(subType)(仅 sub_type 差),
  group 独立;新增 toSegments 收敛 7 参 elementsToJson splat。导出名不变。

行为 byte 级不变(测试 toEqual 顺序无关,key 集合与值逐一保持):event-converter
48 + onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐 converter 对比 HEAD 确认
16 个输出等价、无字段增减/值变、无运行时循环。
2026-07-01 17:58:49 +08:00
DrSmoothl 891a197335 refactor(onebot): collapse action registration into a single barrel
加一个 action 文件原本要同步改三处手写清单:ApiHandler 的 12 个 register import +
12 行构造调用、各文件的 register footer、action-docs 的 13 import + GROUPS。现收敛
成一个 actions/index.ts barrel 作为「文件→动作 + 分类」的单一真相。

- action-kit:抽 RegisteredActionSpec(describe+register),ActionSpec/
  StreamActionSpec extends 它,registerActions 参数放宽到 RegisteredActionSpec[]
  (它只调 .register),于是 stream 动作也能并入统一注册。
- 新增 actions/index.ts:ACTION_GROUPS(11 组含分类,stream 合并)+ ALL_ACTIONS。
- api-handler:12 import+12 调用 → registerActions(this, context, ALL_ACTIONS);
  .handle_quick_operation(唯一非 ActionSpec 的裸 handler,需要 h 本身)从
  extended 搬进构造器一处显式注册。
- action-docs:改用 barrel 的 ACTION_GROUPS,删本地 GROUPS + 13 import。
- 删 12 个 register footer + 清理因此变 unused 的 ApiHandler/ApiActionContext import。

行为严格不变:注册的动作集合、.handle_quick_operation、文档分类/计数均一致。
onebot 516 全绿、全仓 12 包 typecheck Done;对抗性 Agent 逐条对比 HEAD 确认等价。
2026-07-01 17:49:07 +08:00
DrSmoothl b6cde5101d refactor(common,core): extract mapWithConcurrency util; use in forward enrich
阶段 2:把「限量+并发分批」的手写循环收进一个 common util。此形状已被复制进
私有 SLE(friend.ts),是已发生的复制漂移;抽出后堵住它、并给未来的富化点一个
现成原语(cap + 并发批 + best-effort 是防 Tencent 风控封号的标准配方)。

- 新增 common/concurrency.ts:mapWithConcurrency(items, concurrency, fn),批处理
  语义(每批 Promise.all 等齐再下一批,非 rolling pool,保持 forward 现有行为),
  结果按输入顺序返回。7 个单测覆盖顺序/绝对index/峰值≤limit+跨批serialize/
  不整除/单批/空/concurrency<1。
- 迁移 forward.ts residue 昵称富化的并发批循环;cap(slice MAX)/dedup(Set)/
  best-effort(fn 内 try/catch) 保留在 callsite。行为严格不变。

对抗性 Agent 逐条对比 HEAD 确认等价。common 50 / core 467 全绿、typecheck 干净。
2026-07-01 17:29:25 +08:00
DrSmoothl 9d67630396 refactor(common,core): extract single-flight+TTL cache primitive
阶段 1:把手写多份的「单飞+TTL 记忆化」收进一个 common 原语,消除各处
各自实现「TTL 判定 / inflight 去重 / finally 清理」的漂移风险(底层都是 Tencent
风控:忙碌客户端会为每条消息发一次未缓存 OIDB 拉取,持续爆发触发封号)。

- 新增 common/single-flight-cache.ts:createSingleFlightCache<K,V>({ ttlMs, load,
  shouldCache?, now? }).get(key, {force});shouldCache 容纳「错误结果不缓存以便
  重试」,now 可注入便于测 TTL。7 个单测覆盖新鲜命中/单飞去重/force/TTL 过期/
  shouldCache/错误传播/invalidate。
- 迁移 contacts.fetchGroupMemberList(key=groupId, ttl 60s, 默认 shouldCache)与
  update-check.getUpdateInfo(全局 key, ttl 6h, shouldCache=!error)。行为严格不变。

对抗性 Agent 逐条对比 HEAD 确认两处等价(含 update-check 时间戳来源毫秒级微差、
对 6h TTL 可忽略)。common 43 / core 467 全绿、typecheck 干净。
2026-07-01 17:25:04 +08:00
DrSmoothl 6f6f372337 refactor(onebot): drop 55 redundant ACTION_FAILED try/catch in extended actions
阶段 2b:从 extended.ts 删除 55 个「纯兜底」try/catch(catch 体恰为单条
return failedResponse(ACTION_FAILED, String(e)/e.message)),让抛错落到唯一 seam
runAction(已统一 100 + error.message)。retcode 不变(这些本就是 100),去的是
冗余包装。

- 保留:try/finally、带前缀的 catch(获取精华消息失败 / 语音转码失败)、
  download_file 保存失败的 BAD_REQUEST catch、fetchFilteredGroupRequests 的
  catch{return []} 吞值——均原样未动。
- 唯一文案变化:约 30 个原用 String(e) 的 catch,其 wording 由 "Error: X" 变为
  seam 的裸 "X"(丢类名前缀,retcode 不变;OidbError 的服务器码仍在 message 内)
  ——一致化改善,无测试/契约依赖该前缀。
- onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐块比对 HEAD 确认等价、
  结构正确、无误删漏改。
2026-07-01 16:30:00 +08:00
DrSmoothl 5be852f394 refactor(onebot): drop redundant per-action try/catch in qzone/album/admin
阶段 2a:删除 qzone(7)、group-album(8)、group-admin(1) 共 16 个「纯兜底再包一层」
的 try/catch,让抛错自然落到唯一 seam runAction(阶段 1 已统一为 ACTION_FAILED 100
+ error.message)。qzone/album 原返回 1200 → 归一 100(本任务有意);group-admin
原本就是 100,仅去冗余包装。

- 保留:qzone helper uploadQzoneImages 的带前缀 re-throw catch、group-info 的
  honor-info 前缀 catch、message 的吞值 catch(best-effort 保留旧 URL)——均未动。
- 清理三文件不再使用的 RETCODE/failedResponse import。
- qzone-actions 测试断言 1200 → 100(wording 前缀经 seam 仍保留)。
- onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐个对比 HEAD 确认纯兜底、
  无其它漂移、无误删漏改。
2026-07-01 16:20:26 +08:00
DrSmoothl ab45667fdf refactor(onebot): unify action-error retcode at the runAction seam
将「动作抛错返回什么错误码」从各处不一致(100 / 1200 / 漏包→1200)收敛到唯一
兜底处 ApiHandler.runAction,统一为 ACTION_FAILED(100) + error.message。

阶段 1(改 seam 本身):
- runAction catch:默认码 1200 → 100;文案 'internal error' 兜底改为 String(error)。
  OidbError.message 本就含 QQ 服务端 code,无需特判。
- 新增 3 个测试锁定策略:抛 Error→100+message;抛 OidbError→100 且 wording 含
  code+server msg;抛非 Error→100+String()。
- rename_group_file 那个原断言 1200 的测试(未包裹动作、落 runAction)改为 100。

各 action 里多余的 try/catch(qzone/group-album 等仍返回 1200)留待后续阶段删除,
在此之前其失败不经此 seam。onebot 全量 516 全绿、typecheck 干净。
2026-07-01 16:11:49 +08:00
DrSmoothl ab40f086ee refactor(protocol): dedup NTV2 record/video mediaNode builder in decoder
阶段 3(零行为改动):record(bizType 12/22) 与 video(bizType 11/21) 解码分支里
各写一份、逐字完全相同的 23 行 `mediaNode:{ fileUuid,storeId,uploadTime,ttl,
subType,info:{…} }` 块,抽成共享 helper buildMediaNode(idx, fi),消除这对并行拷贝
的漂移风险(改一处忘另一处)。

- VideoFile / Ptt 两处的 mediaNode 来源变量与 shape 不同,正确保持独立、未误并。
- 逐字提取,行为 byte 级不变:typecheck 干净、protocol 全量 561 全绿;对抗性
  Agent byte-diff 确认原两份完全相同、helper body 与之逐字一致。

注:计划中的 poke faceId→subType 字段对齐已主动撤销——poke 不能当消息段发送,
且自身消息回显路径会读 element.subType 使该改动可观测,违反"重构行为不变"。
2026-07-01 15:56:43 +08:00
DrSmoothl 8e173cf7d7 refactor(onebot): merge element toSegment/fromSegment into one codec table
阶段 2(零行为改动):把「同一种消息元素」的两个 onebot 方向——收·转
(to-segment) 与 发·解(message-parser)——从两个文件各写各的分支,合并到一张
按元素类型索引的 ELEMENT_CODECS 表,每种类型一条 { toSegment?, fromSegment? }。

- 新增 event-converter/element-codecs.ts:13 类 toSegment + 14 类 fromSegment
  逐字平移自原实现;私有 helper intOr/marketFaceElement/pickMediaSource 移来并导出。
- to-segment.ts:elementToSegment 改查表 + 保留原 default 透传兜底。
- message-parser.ts:segmentToElement 保留 9 个纯输入糖 case 作前置 normalize,
  真实类型改查表,末尾保留原 unsupported warn。
- onebot 对账测试升级为按表键核对 S/P(比正则更硬),并断言真实类型 case 不再
  残留于 parser、输入糖仍在。

行为 byte 级不变:onebot 全量 513 全绿、typecheck 干净;对抗性 Agent 逐字比对
确认无漂移、无运行时循环依赖。
2026-07-01 15:48:04 +08:00
DrSmoothl f4170b014a refactor(protocol,onebot): add message-element four-direction reconciliation manifest
消息元素散在 4 处派发(收·解 / 收·转 / 发·解 / 发·打包),历史上各写各的、
无对账,导致字段名对不上、漏写方向走 default 静默失败。

阶段 1(零行为改动):立一份权威清单 element-manifest + 两道架构护栏测试。
- element-manifest.ts:每种元素类型 × 四向支持('yes'/'no'/'by-design-no')
  + 字段契约 + typesForDirection() + 输入糖白名单。清单逐字反映当前行为。
- 两道对账测试(因包边界拆两处、共用清单):正则扫 4 处派发代码,比对清单。
  谁增删一个方向却不同步清单,测试当场报红,不再运行时静默。
- 取值域用 [A-Za-z0-9_]+,避免未来驼峰/下划线类型名被静默漏抓致护栏失效。
- poke 的 W=by-design-no:QQ 不允许戳一戳当消息段发送,缺席正确。

对抗性 Agent 两轮复审通过。
2026-07-01 15:48:04 +08:00
囧囧JOJO f424454422 fix(webui): align debug account picker styling (#181) 2026-07-01 14:43:29 +08:00
DrSmoothl 5d6ce86b66 refactor(onebot): give trans_group_file semantic param roles
Follow-up to #161: trans_group_file's group_id/file_id used plain
f.uint()/f.string(); switch them to f.groupId()/f.fileId() (identical
coercion) so the WebUI debug console renders a group picker + file-id
control for the new action and the catalog carries the roles. Catalog
regenerated.
2026-07-01 02:27:35 +08:00
Airline233 9ca64bed10 feat(core,onebot): implement trans_group_file action (#161) 2026-07-01 02:13:35 +08:00
Airline233 2f374ea8c9 feat(qzone): support post visibility rights when publishing qzone posts (#178)
Add ugc_right and target_uins to the qzone publish path across protocol,
bridge, and the send_qzone_msg OneBot action, regenerate the MCP catalog,
and cover restricted visibility (16/128) with validation tests.
2026-06-30 23:57:39 +08:00
DrSmoothl c90a3954e4 fix(bridge): self-heal login detection when the hook misses the edge
Docker SnowLuma could hang forever at "等待登录" after QQ had already
logged in. Root cause: login detection is edge-triggered — it only learns
the state from a loginState frame the native hook PUSHES when it observes
the login transition. `getLoginState()` is a cached value read once at
connect; after that the session waits passively. Desktop attaches the
hook before the user logs in, so it catches the edge. In Docker, QQ
auto-logs-in from a persisted session — fast on startup — so the
transition lands before the recv pipe is connected (frames aren't
replayed) or via a silent restore path the hook doesn't intercept. The
edge is missed and the cached state stays not-logged-in.

Fix: while connected but not logged in, actively re-probe QQ's own
ptlogin/deeplink ports via probeQqLoginInfo (level-triggered, pipe-
independent — the same call the workaround used) and synthesize the login
once it reports a real uin. Immediate probe on connect + a 3s interval;
stopped on login / teardown / dispose, with an in-flight guard so a slow
port scan can't stack concurrent probes. Idempotent with the pushed-frame
path. 7 tests cover detect-via-probe, the later-interval case, the
not-logged-in / non-real-uin / throwing-probe guards, no double-emit, and
no concurrent stacking. probeLogin is injectable for tests.
2026-06-30 23:29:51 +08:00
DrSmoothl 397087dc74 test(core): hoist Bridge import to fix flaky 5s timeout
bridge-private-routing.test.ts loaded the Bridge dependency tree via
`await import(...)` INSIDE each `it`, so the first test paid the whole
~3.8s module-eval cost against its 5000ms per-test budget — fine locally
but tipping over on slower CI runners (surfaced as a timeout on an
unrelated PR). Moved the Bridge / IdentityService imports to top-level
statics (vi.mock is hoisted above them, so element-builder stays mocked):
the heavy load now happens once at file collection, not against a test
timeout. Per-test execution dropped from ~3.8s to ~7ms.
2026-06-30 23:09:21 +08:00
DrSmoothl 48e2777bc3 chore(release): v1.11.0 2026-06-30 20:38:37 +08:00
DrSmoothl a8307891fa fix(core): backfill forward-msg sender nickname/card (#174)
get_forward_msg nodes came back with empty or "QQ用户" sender names: the
SsoRecvLongMsg payload doesn't always populate the member name, and the
sync decode only consulted the L1 identity cache. So a sender absent from
that cache (just-started bot, inactive member) had no name.

ForwardApi.enrichSenders() now backfills nameless nodes on both fetch
paths (wire + cache-hit, with write-back so seeded inner caches enrich on
first read):
- L3: one fetchGroupMemberList per distinct group (inflight+TTL cached)
  resolves every in-group sender at once; card preferred over nickname,
  matching the existing wire-decode convention.
- L4: per-uin fetchUserProfile only for the residue (members who left the
  group, private nodes).

Best-effort: a failed lookup keeps the placeholder, never failing fetch.

Adversarially reviewed — fixed the one High it found: the L4 fallback was
an unbounded Promise.all of un-cached OIDB 0xFE1_2 lookups, which a
high-churn group's historical forward (many since-left senders) or a
flaky member-list call could amplify into a rate-limit ban (the very risk
ContactsApi's own cache note warns about). Now: member-list failure keeps
the placeholder instead of fanning out, and the residue is capped
(FORWARD_PROFILE_MAX) and resolved in small concurrency-limited batches.
2026-06-30 20:32:49 +08:00
DrSmoothl fc4d3a9c5d fix(protocol): set_group_name body tag 3, not 1 (#173, OIDB 1006)
set_group_name (OIDB 0x89a_15) always failed with OIDB error 1006 even
with admin rights. The group name in the body sits at tag 3, but we had
it at tag 1 — so the server rejected the malformed request structure
before ever checking permission. Confirmed against Lagrange's
OidbSvcTrpcTcp0x89A_15Body (ProtoMember(3) TargetName).

The reporter had tried tag 1 and tag 2 (both still 1006) — the answer was
tag 3. Live-verified on tempserver: with the fix the error changes from
1006 (structure rejected) to 1328 (permission — the test bot is only a
member), proving the request structure is now accepted; an admin bot will
succeed.
2026-06-30 20:14:20 +08:00
DrSmoothl 1f23e6e9f0 fix(protocol): ptt-trans md5 must be a hex string, not raw bytes (#165)
fetch_ptt_text failed for every voice with QQ errCode -1079 ("ptt
translate failed"). RE'd the cause in wrapper.linux.node: EncodeTroopPtt /
EncodeC2CPtt (ptt_trans_worker.cc) run the md5 through a bytes→hex helper
(sub_7A02D80, the 000102…ff table) before putting it in the request — so
the md5 field is a 32-char lowercase HEX STRING, but we were sending the
raw 16 bytes (hexToBytes(md5Hex)). Wrong length + encoding → server reject.

All other fields matched QQ NT exactly (verified field-by-field against
the two encoders): group {1=msg,2=sender,3=group,4=fileId,5=md5,6=dur,
7=size,8=format,9=uuid,10=event}, c2c {…,9=md5}, type 1=group/2=c2c.

Fix: md5 field is `string` (the lowercased hex), not `bytes`. Live-
verified on tempserver — errCode -1079 is gone and a real voice now
returns ASR text. (The "Live-verified end to end" claim in the old
comment was wrong; c2c had the same latent bug.)
2026-06-30 20:02:07 +08:00
DrSmoothl 0cf9cdd0d7 chore(core): diagnose ptt translate failures (#165 备选)
When QQ's ASR returns a non-zero errCode, log the request fields we
sourced from cache (md5 length / format / uuid presence / duration /
size) alongside the errCode, so a server-side ASR failure can be told
apart from our own missing/zero field. Behaviour unchanged — still
throws. Helps diagnose the "ptt translate failed" instability reported
in #165 before deciding whether it's our bug.
2026-06-30 19:31:20 +08:00
DrSmoothl 90456def2e feat(onebot): get_record out_format — server-side voice transcode (#165)
#165: get_record gains an optional `out_format` (mp3/amr/wma/m4a/spx/ogg/
wav/flac, mirroring NapCat). When set, the QQ voice (SILK/AMR) is
transcoded server-side and the result is attached as `data.base64`; the
original info (file/url/file_size) is preserved. Absent ⇒ behaviour
unchanged. This spares ASR consumers from shipping a SILK decoder.

- protocol: convertAudioBytes(bytes, format, deps?) drives the bundled
  SILK-capable ffmpeg addon's convertFile through temp files (always
  cleaned up), with a format allowlist and an output-size cap. Pure/
  injectable, unit-tested with a fake addon (6 cases).
- core: ExtrasApi.convertRecord(source, format) = loadBinarySource (64 MiB
  cap) → convertAudioBytes.
- onebot: get_record wires out_format; transcode failure (incl. an addon
  lacking SILK decode) degrades to ACTION_FAILED, never crashes.

Adversarially reviewed: no path traversal (format allowlisted), no SSRF
(source is the cached CDN url, not user input), cleanup covers every path,
graceful degradation confirmed. Catalog regenerated. Real-machine e2e
(does the shipped .node actually decode SILK?) is Phase 2.
2026-06-30 19:25:40 +08:00
DrSmoothl 8fc5917b3b fix(webui): align message composer/builder (Apple-HIG)
Two alignment fixes in the 消息构建 tab:
- MessageBuilder is now a bounded "compose canvas" (always bordered) so the
  empty hint reads as an intentional empty state inside a defined input
  region, instead of a stray centered line floating in the left-aligned
  form.
- The 账号 / 目标 label rows are pinned to a fixed h-8 (== the 群聊/私聊
  segmented control's height) so both labels and the selectors beneath them
  share a baseline — min-h-7 wasn't enough since the segmented is ~32px.
2026-06-30 18:57:54 +08:00
DrSmoothl 65195abbe0 fix(mcp): add role/stream to Catalog types to match generated catalog
Phase 0 added `role` to FieldDoc and `stream` to ActionDoc and regenerated
catalog.ts, but the mcp package's own CatalogParam/CatalogAction types
(intentionally decoupled from onebot per ADR-0005) weren't updated — so
`tsc --noEmit` failed on the generated catalog.ts (TS2353, unknown
properties role/stream). The mcp vitest suite passed because esbuild
doesn't type-check the generated snapshot, which is why this slipped.

CatalogParam gains role?: string (loose, to stay decoupled from onebot's
FieldRole union); CatalogAction gains stream?: boolean. `pnpm typecheck`
is green across all packages.
2026-06-30 18:45:34 +08:00
DrSmoothl d5fbd6fa06 feat(webui): multi-tab debug console + embedded API browser
Phase 6 of the debug-console expansion — the four pieces become one
console: 测试台 / 消息构建 / 实时活动 / API 浏览器, behind an Apple-HIG
sliding-indicator tab bar.

- ApiBrowser: a searchable, category-grouped reference for every
  declarative action (~520), straight from /api/debug/actions — params /
  returns / invariants / role + readOnly + stream badges. Each row's 试一下
  prefills the tester and switches to it (ActionTester gains a
  presetAction prop keyed by nonce).
- Tester / compose / activity stay MOUNTED and toggle via CSS, so the
  live feed's SSE never drops — it keeps capturing events fired while you
  invoke from the tester tab (the invoke-then-observe loop) — and
  in-progress params/messages survive a peek at another tab. The API
  browser, heavy and stateless, mounts on demand.

Adversarially reviewed: no crash / leak / mis-trigger; the review caught
that conditional-mounting silently dropped cross-tab live events and
discarded in-progress work — fixed by keeping the stateful panels mounted.
2026-06-30 17:40:04 +08:00
DrSmoothl 383ddb0a5d feat(webui): visual message builder + composer (nested forward)
Phase 5 of the debug-console expansion. A drag-reorderable segment
builder so you never hand-write a OneBot message array: common segments
first-class (text / @ / image / face / reply / record / video), advanced
folded (file / mface / poke / json / xml / markdown / forward-node), with
`node` nesting a full builder (merged forward, depth-capped). @ uses the
group member picker via the sibling group context; media via FileSource.
Each segment carries a stable `_id` key so editing a field never remounts
the row.

- MessageBuilder + toOneBot() serialise to the exact OneBot v11 shapes
  SnowLuma's parser reads (verified field-by-field).
- MessageComposer (the 消息构建 tab): pick target, build, preview, send —
  routing through send_*_forward_msg when the message has nodes, else
  send_*_msg. Refuses a mixed node/non-node forward (the backend would
  silently drop the stray segments) and validates incomplete segments
  before sending.
- ParamField renders the builder for message-type params in the tester
  (raw-text escape hatch kept), emitting the serialized array as the
  string value.

Adversarially reviewed: serialization contract and React key/focus both
verified clean (no _id leakage); fixed the mixed-forward silent-drop,
added pre-send segment validation, and made the drag boundary explicit.
2026-06-30 17:31:51 +08:00
DrSmoothl 11866caa2f feat(webui): role-driven action tester with streaming + history
Phase 4 of the debug-console expansion — the tester no longer makes you
hand-write JSON. Each param renders the right smart control from its
semantic role: group/friend/member pickers (member linked to the sibling
group_id), FileSource for media, FaceGrid, datetime for timestamps,
switch for bool, select for enum — with the raw-JSON escape hatch kept.

- Read-only actions badge green, side-effecting amber; a name-pattern set
  of destructive actions (kick/ban/recall/delete/…) confirms first.
- Stream API actions invoke over /api/debug/invoke-stream and render
  frames live, tracked in the app-level task registry with progress; a
  clean success requires the terminal response frame, and a failed frame
  shows its reason (not just the {type:'error'} marker).
- Every call lands in capped localStorage history with one-click replay;
  responses render in a collapsible JsonTree.
- Extracted LiveActivity (filter / search / export) and the Segmented
  control into their own components; debug-page is now a thin host.

Adversarially reviewed: stream terminal-frame judging, member/group
linkage, and contract shapes verified; fixed the failed-stream-frame
reason being hidden, a latent required-enum controlled-select trap, stale
member value on group change, and several low UX edges.
2026-06-30 17:17:15 +08:00
DrSmoothl c5611ed622 feat(webui): debug-console shared primitives, data layer, task manager
Phase 3 of the debug-console expansion — the Apple-HIG foundation the
new tabs build on (reusing the existing ui kit; new controls match its
idiom, no browser-native widgets).

API client + types:
- debug.invokeStream() reads /api/debug/invoke-stream via fetch + a body
  reader, parsing data:<json> SSE frames (header auth, cancellable).
- debug.upload() streams a file via XHR for real upload progress.
- DebugActionParam.role, DebugActionDoc.stream/invariants, FieldRole,
  DebugStreamFrame, DebugUploadResult.

Primitives:
- Tabs (sliding indicator + roving tabindex), Picker (searchable,
  windowed combobox with a raw-value escape hatch), JsonTree (collapsible
  response viewer, image-url preview, copy w/ http fallback, node cap),
  FileSource (URL / server-path / browser-upload tri-state), FaceGrid.

Infra:
- DebugTaskProvider + TaskBadge: app-level registry of in-flight upload/
  stream tasks so they survive in-app tab switches, with a global
  progress chip and a beforeunload guard; eviction never drops a running
  task. Wired into App.
- use-debug-contacts: lazy friend/group/member data layer, shared module
  cache + localStorage (version-stamped, avatars stripped to dodge quota)
  + TTL + request-id race guard, degrading to raw input on error.

Adversarially reviewed (no automated component tests): virtualization
math and SSE framing verified correct; fixed the stale-contacts-on-switch
member-selection hazard, the quota-kills-persistence issue, and several
low UX edges (active-row clamp, filter scroll reset, copy fallback).
2026-06-30 16:53:43 +08:00
DrSmoothl a7667f1cd5 feat(core,onebot): debug-console stream-invoke + upload endpoints
Phase 2 of the debug-console expansion. Two backend endpoints under the
existing /api/* bearer auth:

- POST /api/debug/invoke-stream — drive a Stream API action (#163) and
  relay every frame to the browser over an SSE body. The frontend reads
  it with fetch()+a stream reader (header auth), so it needs no SSE
  query-token allowlist entry. Frames are NEVER dropped: backpressure is
  handled by waiting for the consumer to drain, not by discarding (a lost
  chunk corrupts a transfer). Non-stream actions emit a single frame.
- POST /api/debug/upload — stream a browser-selected file to a temp path
  on THIS server (the bot runs server-side, not on the operator's
  machine), so the path can feed a send action's file/image/record/video
  param. Raw bytes in the body (no multipart buffering), ?filename= for a
  readable suffix, streamed to disk under os.tmpdir()/snowluma-debug-
  upload with a 4 GiB cap and a 24h TTL sweep.

instance.invokeStream() delegates to ApiHandler.processStreamRequest.

Pure logic (filename sanitisation, fenced size-capped disk sink, the
stream-invoke Response builder) lives in debug-tools.ts with 12 unit
tests. Adversarially reviewed: path traversal is robust (19 hostile
filenames all fenced), frames provably never dropped, auth runs before
any disk write. Fixed a High found in review — the write stream had no
'error' listener (an async ENOSPC/EIO during flush would crash the whole
process) and a late-open race could leak a partial file; both now raced
into the awaits and cleaned up after 'close'.
2026-06-30 16:19:59 +08:00
DrSmoothl c839121fdb fix(protocol): send super/new faces with the right wire encoding (#168)
A face was always built as a legacy FaceElem (face.index). QQ-NT only renders
classic small faces that way; newer 'super'/animated faces sent as face.index
are silently remapped by the server (e.g. 424→168) or shown as a placeholder.

Classify each face id off QQ's own system-face catalog (0x9154_1, ported from
SLE/Lagrange) and pick the matching wire form:
  - super (animated, aniSticker pack ≠ (1,1)) → CommonElem 37 + QFaceExtra
  - other id ≥ 260                            → CommonElem 33 + QSmallFaceExtra
  - classic id < 260                          → legacy FaceElem

The catalog is fetched once (shared, lazy-warmed off the first face send) and
classify falls back to an id-range guess until it lands. Data-driven so all 66
non-(1,1) super faces encode correctly, not just a hardcoded few.

Verified on a live account: 424→424 (was 168), super 392→392, classic 14→14.
2026-06-30 16:09:28 +08:00
DrSmoothl f9900053b0 feat(onebot): backfill semantic roles across action params
Phase 1 of the debug-console expansion. Sweeps the 8 action files,
swapping bare coercion primitives for the role-stamped equivalents from
Phase 0 (or appending `.role()` where a `.default()`/`.optional()` field
must keep its exact coercion). Coercion is byte-for-byte unchanged; the
only intentional bound change is face_id min 1→0 (QQ face 0 is valid).

Classification (verified against each run()):
- group_id → f.groupId() everywhere.
- user_id → f.userId() for any-user / friend / stranger / private-route
  targets (send_private, friend poke, friend add/remove, stranger info,
  private file transfer, forward-to-friend, share-contact).
- user_id → f.memberId() only when it's a member of a sibling group_id
  (batch kick elements; the groupUserAction preset already injects it).
- media file/image/record + file_id → f.file()/image()/record()/fileId()
  (or .role() when defaulted/optional); message_id/timestamp/duration via
  the constructor or .role() hatch as coercion requires.

Polymorphic ids left as bare uint on purpose (no single role can honestly
describe them): mark_msg_as_read.target_id (group# or uin), bot_appid,
msg_seq, fileset_id, folder_id, chunk indices, stream_id.

Catalog regenerated: 71 group_id / 25 user_id / 9 member_id / 19
message_id / 11 file_id / 7 image / 6 file roles surfaced. Done by 4
parallel agents; adversarially reviewed — zero coercion regressions,
zero member/user misclassifications.
2026-06-30 16:00:21 +08:00
DrSmoothl 14a61f4ce8 feat(onebot): add semantic role field + stream flag to action metadata
Phase 0 of the debug-console expansion. Introduces a closed `FieldRole`
union (group_id/user_id/member_id/message_id/file_id/file/image/record/
video/duration/timestamp/face_id) orthogonal to `type` (which governs
coercion), so the WebUI debug console can render semantic pickers instead
of forcing hand-written JSON.

- FieldDoc gains `role?`; Field gains a `.role()` modifier (survives
  optional/default/describe). toJsonSchema emits it as `x-role`.
- Semantic constructors f.groupId/userId/memberId/fileId/file/image/
  record/video/duration/timestamp/faceId wrap the coercion primitives and
  stamp a role (messageId backfilled). Media sources reject '' to preserve
  the empty-string guard they replace. faceId allows 0 (valid QQ face id).
- Extracted stringCore so f.string() and string-valued roles share it.
- ActionDoc gains `stream?`; defineStreamAction sets stream:true.
- Presets: groupAction injects f.groupId(); groupUserAction injects
  f.groupId() + f.memberId() (a group action's user_id is a member of
  that group). Backfills role onto 56 group_id / 7 member_id sites.
- Regenerated MCP catalog (79 x-role, 5 stream).

Adversarially reviewed: no coercion regression, member_id stamping has
zero false positives across all 7 groupUserAction sites, x-role is inert
to MCP consumers.
2026-06-30 15:42:25 +08:00
DrSmoothl 7285db1e37 feat(onebot,mcp): catalog the Stream API actions (#163 phase 4)
Surface the six Stream API actions in the self-generated docs catalog under
a new 流式接口 category: export each module's specs as an `actions` array
(register now iterates it) and widen the doc collector's spec type to anything
carrying describe() so defineStreamAction results qualify alongside
defineAction. Regenerated the MCP catalog snapshot.

End-to-end verified on a live account over HTTP: test_download_stream (10
frames + terminal), an upload_file_stream round-trip (200 KB chunked in →
sent as a c2c file → download_file_stream back out, byte- and sha256-exact),
and the SSRF guard rejecting a cloud-metadata URL.
2026-06-30 14:40:39 +08:00
DrSmoothl 369dea582c feat(onebot): download stream actions (#163 phase 3)
NapCat-compatible server-push download: one request answered by a file_info
header, N base64 file_chunk frames, then a terminal file_complete. Bytes come
from a local file under the stream temp root, an http(s) URL, or a cached
image/voice id resolved to its QQ CDN URL. test_download_stream pushes 10
canned frames so a client can validate the transport without touching QQ.

Actions: download_file_stream / download_file_image_stream /
download_file_record_stream / test_download_stream.

Hardened beyond the NapCat original (which streams any local path and follows
redirects to anywhere), per three adversarial review passes:
- arbitrary-file-read: local reads are fenced inside the stream temp root,
  realpath-resolved so a symlink can't point out.
- SSRF: every URL (incl. each redirect hop, followed manually) is guarded —
  http(s) only, and neither the literal host nor any resolved address may be
  private/loopback/link-local; IPv6 is byte-parsed so normalized v4-mapped
  literals (::ffff:a9fe:a9fe) can't slip past. (DNS rebinding remains a
  documented residual — needs connect-time peer-IP validation.)
- robustness: TTFB-only connect timeout (doesn't cut a large body mid-stream)
  plus a per-chunk idle watchdog that aborts a stalled source so a hung
  upstream can't pin a socket; total size capped; non-2xx bodies cancelled;
  client disconnect aborts via the sink.

501 onebot tests green.
2026-06-30 14:40:39 +08:00
DrSmoothl 4f0a0f89ae feat(onebot): upload_file_stream + clean_stream_temp_file (#163 phase 2)
NapCat-compatible chunked upload: a client pushes a file in base64 chunks
across repeated upload_file_stream calls keyed by stream_id; the bot
reassembles them into a local temp file and returns its path for a normal
send. Sidesteps the 2 MB HTTP body cap and the shared-filesystem assumption
of file:// sends.

Reassembly streams chunk-by-chunk to disk (no whole-file Buffer.concat) so
an arbitrarily large upload won't OOM. clean_stream_temp_file wipes only the
stream temp dirs.

Hardened well past the NapCat original (which has all of these holes), per
two adversarial review passes:
- stream_id is allowlist-validated + every derived path fenced inside the
  upload dir — no path traversal (the original lets stream_id write/delete
  arbitrary paths).
- total_chunks / concurrent streams / per-chunk + per-stream bytes are all
  bounded — no single-request OOM or disk/fd exhaustion.
- chunk indices are claimed synchronously and only counted complete once
  flushed — no double-count race, no truncated-read-on-concurrent-complete.
- state + temp dirs are namespaced per account.

494 onebot tests green.
2026-06-30 14:40:39 +08:00
DrSmoothl 01ef98abb6 feat(onebot): Stream API transport plumbing (#163 phase 1)
Foundation for NapCat-compatible Stream API actions (chunked file
upload/download): a single request answered by many response frames.

- streaming.ts: StreamSink + frame wrappers (wrapStreamFrame /
  wrapStreamTerminal) matching NapCat's wire — each frame an OB11 envelope
  with stream:'stream-action', data.type ∈ stream/response/error, and
  message mirrored into wording.
- ApiHandler: registerStreamAction / isStreamAction; handle() threads a
  sink; processStreamRequest drives WS multi-frame dispatch with optional
  liveness-based abort; dead processRequest removed.
- action-kit: defineStreamAction (sink-aware run, registers as a stream
  action) reusing defineAction's parse/describe.
- adapters: HTTP server streams chunked \r\n\r\n-delimited frames (no
  Content-Length, no false application/json), aborting on client
  disconnect; WS server/client use a backpressure-aware safeSendAsync and
  abort a stream once the socket closes.

No stream actions are registered yet — those land in the next phases.
Verified by two adversarial review passes. 480 onebot tests green.
2026-06-30 14:40:39 +08:00
Airline233 62eb8fd763 feat: Qzone支持上传图片(发说说、评论附图) (#152)
* feat(core,onebot,protocol): support publish shuoshuo and comment with image

* Fix: Accidentally changed notes
2026-06-30 01:47:21 +08:00
DrSmoothl 547640bbfd fix(onebot): route oversized videos to the file path up front (#145)
A video larger than MAX_VIDEO_SIZE (~100 MB, QQ's video-resource cap)
uploads "successfully" — the server accepts the Highway bytes — but the
receiver sees 视频已过期 because no valid video resource is ever produced.

The existing large-video → file fallback only fired from the send catch
block, i.e. when the upload threw. An oversized upload doesn't throw, so
the fallback never triggered. Add a proactive split before the send: any
video whose source size is known to exceed MAX_VIDEO_SIZE is re-routed to
the file pipeline up front (mirrored for private and group sends). Smaller
videos (verified up to ~49 MB) are unaffected and still send as videos.

This pairs with the c2c-file fix (f8caa92): the re-routed video now rides
the now-working offline-file path and downloads correctly.
2026-06-30 01:24:00 +08:00
DrSmoothl f8caa92333 fix(core): make c2c files >5MiB downloadable — drop stale busId, fix md5-head magic
Private (c2c) files larger than a few MiB uploaded fine but the receiver
always got "download failed" (#157). Two independent bugs in the offline-
file upload (OidbSvcTrpcTcp.0xe37 + highway cmdId 95), both confirmed on a
live account and against a plaintext packet capture of the real QQ client:

1. FileUploadExt.busiBuff carried a stale `busId: 102`. NapCat, Lagrange and
   the QQ client all emit busiBuff with senderUin only. The extra busId let
   the server accept the highway upload but never finalise it as a
   downloadable offline file once the payload passed ~5 MiB.

2. md510MCheckSum used `10 * 1024 * 1024` (10485760) as the "first 10 MB"
   limit. QQ's magic number is 0x98A000 = 10002432. With the wrong limit the
   server's first-block verification failed for any file larger than
   0x98A000, so files >~10 MB uploaded but never finalised either.

With both fixed, c2c files of arbitrary size (verified up to ~20 MB; the
general highway path has no inherent size cap) download correctly.
2026-06-30 00:13:34 +08:00
DrSmoothl 57ff0e69d8 fix(core): make c2c file 0xE37_800 finalize best-effort, not fatal (#157)
Real-machine retest showed a plain c2c file send (NotOnlineFile only, no
field6) is already downloadable — the original #157 'fix' made the 0xE37_800
finalize a hard dependency, so any finalize error would now fail a send that
would otherwise succeed (a regression, same speculative-NapCat-parity trap as
the #145 force-full).

Wrap the finalize in try/catch: on success we still attach field6 (extra
download routing that mirrors NapCat and may help some receiver clients); on
failure we log and send without it. field6 is now enrichment, not a
requirement.

Adds a regression test: a failing 0xE37_800 still produces a PbSendMsg with
the file and no field6.
2026-06-29 16:08:20 +08:00
DrSmoothl 053137669a fix(protocol): drop the ineffective video force-full-on-fast-path retry (#145)
forceFullOnFastPath re-issued the NTV2 upload with tryFastUploadCompleted:
false to try to refresh a possibly-expired video resource. Real-machine
testing on a live account + RE of the QQ NT kernel (wrapper.node) proved it
never works:
- the server's fast-path is driven by md5-metadata existence and ignores
  the flag (proton omits a false bool anyway); the retry re-fast-paths
- the kernel itself does no validity check — HandleRspUploadV3 trusts the
  response's fileExist and goes straight to SendUploadSuccFTN

So an expired-but-still-indexed video resource is a platform-level
limitation, not something the upload flow can refresh. Removing the retry
drops two wasted OIDB round-trips per cached-video re-send. The underlying
#145 (receiver '资源已过期' for a server-expired resource) remains a
platform issue, tracked separately.

Tests updated to assert the single-request behaviour.
2026-06-29 15:32:57 +08:00
DrSmoothl 37f768dd33 fix(bridge): isolate process enumeration so a blocked native call can't freeze the loop (#158)
QQ's silent hot-update churns the process table; the watcher's synchronous
native getAllMainProcess() (/proc walk reading cmdline/maps) blocks while a
process is mid-exec(). Running on the main event loop, that froze the whole
bot — OneBot stopped responding, the watcher stopped ticking, the supervisor
saw it 'alive' so never restarted it (silent death until manual restart).

- run the native enumeration in a worker_threads worker, raced against a
  deadline on the main thread; a blocked call no longer stalls the loop
- on timeout/failure return an UNKNOWN sentinel (null); PipeWatcher keeps the
  prior process+pipe snapshot instead of treating missing data as 'all QQ
  gone' (which would dispose live sessions and tear down a healthy hook)
- graceful fallback to in-loop enumeration when the addon can't load in a
  worker or there's no addon (macOS); custom listers (tests) bypass the worker
- bounded orphan workers across a sustained hang

Tests: PipeWatcher null-sentinel (no false process-gone, recovers); enumerator
sync-fallback + broken-isolation paths. Native /proc-walk hardening rides in
the nnphook repo separately.
2026-06-28 23:30:10 +08:00
DrSmoothl 5dc3ec88d4 fix(webui): smooth sidebar collapse — no reflow, centered icons, pin button
The hover-rail flipped its content to a collapsed layout instantly while the
width animated, so on every expand/collapse icons jumped toward the top-left and
labels flashed in, wrapped super-tall, then settled — and the collapsed rail
leaked the first glyph of every label plus hard-clipped highlight bars.

Lay the rail content out at a fixed width and let the aside clip it: nothing
reflows during the width animation. Icons live in a fixed centered column (never
move); labels stay mounted with nowrap and just fade out when collapsed (no
wrap, no leak); the active pill and update banner render their background as an
absolute layer that becomes a centered squircle on the rail instead of a
hard-clipped bar.

Adds the promised pin toggle to the sidebar footer (desktop) — mirrors the
「钉住侧栏展开」 appearance setting: pinned keeps the rail open, unpinned returns
to hover-to-peek.
2026-06-28 23:29:25 +08: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