Merge pull request #175 from SnowLuma/dev

chore: promote dev → main (48e2777)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-06-30 12:39:05 +00:00
commit b807825a09
103 files changed
+8722 -1091

No files matched your search

@@ -0,0 +1,65 @@
name: Issue template guard
# Blank / free-form issues bypass `blank_issues_enabled: false` (it only hides
# the chooser link — the CLI, API and direct URLs still create template-less
# issues). This guard enforces the policy after the fact: an issue opened by
# someone WITHOUT write access that did not go through a template (no template
# label) is commented on and closed. Properly-filed bug reports / feature
# requests (which carry `bug` / `enhancement`) and anyone with write access are
# left alone.
#
# Note: workflows for `issues` events run from the file on the DEFAULT branch,
# so this only takes effect once it lands on `main`.
on:
issues:
types: [opened]
permissions:
issues: write
jobs:
guard:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const issue = context.payload.issue;
// Write-access roles are exempt.
const privileged = ['OWNER', 'MEMBER', 'COLLABORATOR'];
if (privileged.includes(issue.author_association)) {
core.info(`author_association=${issue.author_association} — allowed`);
return;
}
// A template was used iff it stamped its label.
const TEMPLATE_LABELS = ['bug', 'enhancement'];
const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name));
if (labels.some((l) => TEMPLATE_LABELS.includes(l))) {
core.info('template label present — allowed');
return;
}
// Non-privileged + no template → guide and close.
const { owner, repo } = context.repo;
const chooser = `https://github.com/${owner}/${repo}/issues/new/choose`;
const body = [
'感谢你的反馈。',
'',
'本仓库的 issue 需要通过模板提交:请使用 **Bug 反馈** 或 **功能请求** 模板重新创建,',
'以便我们准确、高效地处理。直接创建的空白 / 自定义 issue 会被自动关闭。',
'',
`- 重新创建:${chooser}`,
'- 日常使用、快速交流类问题,可先到 README 中的 QQ 群',
'',
'本 issue 将自动关闭,感谢理解。',
].join('\n');
await github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body });
await github.rest.issues.update({
owner, repo, issue_number: issue.number,
state: 'closed', state_reason: 'not_planned',
});
core.info(`closed #${issue.number} (author_association=${issue.author_association}, no template label)`);
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.10.4",
"version": "1.11.0",
"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.4",
"version": "1.11.0",
"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).",
+42 -9
View File
@@ -6,10 +6,12 @@ import { HookSession, type HookSessionDeps } from './hook-session';
import {
injectHookProcess,
listHookProcesses,
resolveHookNativePath,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { PipeWatcher } from './pipe-watcher';
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { QqHookClient } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
@@ -81,7 +83,13 @@ export class HookManager {
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean;
private readonly listProcessesNative: () => HookProcessBaseInfo[];
/** Watcher/API process enumeration — isolated + timeout-bounded by default
* so a blocked native /proc walk can't freeze the loop (issue #158).
* Resolves to `null` (UNKNOWN) on timeout/failure. */
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
/** The owned enumerator (worker lifecycle), or null when a custom lister was
* injected (tests) — nothing to tear down in that case. */
private readonly enumerator: ProcessEnumerator | null;
private readonly autoLoadOnDiscovery: boolean;
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
@@ -104,15 +112,38 @@ export class HookManager {
},
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
// A custom lister (tests) is used directly — no worker, no isolation, just
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path
// wraps the native enumerator in a worker with a timeout.
if (deps.listProcesses) {
const lister = deps.listProcesses;
this.enumerator = null;
this.enumerate = async () => {
try {
return await lister();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
return null;
}
};
} else {
this.enumerator = createNativeProcessEnumerator({
addonPath: resolveHookNativePath('node'),
fallbackSync: listHookProcesses,
processName: defaultProcessName(),
log: this.log,
});
this.enumerate = () => this.enumerator!.enumerate();
}
if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false;
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.listProcessesNative,
listProcesses: this.enumerate,
listLivePipes: () => QqHookClient.listLivePipes(),
intervalMs: deps.watcherIntervalMs,
log: this.log,
@@ -128,12 +159,13 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise;
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcessesNative();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
const processes = await this.enumerate();
if (processes === null) {
// Enumeration timed out / failed — report the last-known sessions rather
// than an empty list (which the WebUI would render as "no QQ").
return [...this.sessions.values()]
.map((s) => s.toInfo())
.sort((a, b) => a.pid - b.pid);
}
const result: HookProcessInfo[] = [];
for (const proc of processes) {
@@ -181,6 +213,7 @@ export class HookManager {
session.dispose();
}
this.sessions.clear();
this.enumerator?.dispose();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
}
+18 -5
View File
@@ -6,8 +6,11 @@ const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** Native: list QQ.exe processes currently running. */
listProcesses: () => HookProcessBaseInfo[];
/** Native: list QQ.exe processes currently running. May be async and may
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
* case this tick keeps the prior process+pipe state instead of treating the
* missing data as "everything disappeared" (issue #158). */
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
/** Native: PIDs that currently have a live SnowLuma named pipe. */
listLivePipes: () => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
@@ -138,12 +141,22 @@ export class PipeWatcher extends EventEmitter {
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[];
let processes: HookProcessBaseInfo[] | null;
try {
processes = this.listProcesses();
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
processes = null;
}
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
// Treating missing data as "everything disappeared" would fire
// process-gone for every live PID and dispose healthy sessions — the
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
// the manager's per-tick reconnect retries keep running off last-known
// live pipes.
if (processes === null) {
this.emit('tick');
return;
}
let livePipes: Set<number>;
try {
+238
View File
@@ -0,0 +1,238 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { Worker } from 'worker_threads';
import type { HookProcessBaseInfo } from './injector';
/**
* Isolated, timeout-bounded wrapper around the native `getAllMainProcess()`
* enumeration.
*
* Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by
* calling the synchronous native enumerator, which walks `/proc` and reads each
* candidate's `cmdline`/`maps`. Those reads go through the target's mm and
* BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a
* silent hot-update and the process table churns. A blocked synchronous native
* call freezes the whole Node event loop: OneBot stops responding, the watcher
* stops ticking, reconnect logic never runs. The process stays "alive" so the
* supervisor never restarts it — the bot just goes silent.
*
* The only way to put a real timeout on a synchronous native call is to run it
* off the main thread. We run it in a worker; the main thread races the result
* against a deadline. On timeout the main loop keeps going (it returns the
* UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep
* prior state" — crucially NOT "all processes gone"). The blocked worker is
* abandoned (a fresh one is spawned next time); it exits on its own once the
* native call finally returns.
*
* Graceful degradation: if the native addon can't be loaded in a worker (e.g.
* it isn't context-aware) or there's no addon at all (macOS reads sockets, not
* `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e.
* exactly today's behaviour, no worse.
*/
export interface ProcessEnumerator {
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
* out / failed and the caller should keep its prior state. */
enumerate(): Promise<HookProcessBaseInfo[] | null>;
dispose(): void;
}
export interface NativeEnumeratorDeps {
/** Resolved path to the hook `.node` addon, or null when there is none
* (macOS / missing) — in which case we never spawn a worker. */
addonPath: string | null;
/** Synchronous lister used when worker isolation is unavailable. Returns
* today's value (and may itself block — that's the no-worse-than-before
* fallback). */
fallbackSync: () => HookProcessBaseInfo[];
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
processName: string;
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
* enumeration (single-digit ms) but well under a human "is it dead?". */
timeoutMs?: number;
/** Cap on abandoned (blocked) workers before we stop spawning more and just
* return UNKNOWN until they drain. Bounds thread growth across a long
* hot-update window. Default 4. */
maxOrphans?: number;
log?: Logger;
}
const DEFAULT_TIMEOUT_MS = 4000;
const DEFAULT_MAX_ORPHANS = 4;
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
// `process.dlopen` is a global and needs no module system). Loads the addon
// handed in via workerData, then answers each 'enumerate' with the raw pid list
// from the blocking native call. All the cheap post-processing stays on main.
const WORKER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
let addon = null;
try {
const mod = { exports: {} };
process.dlopen(mod, workerData.addonPath);
addon = mod.exports;
} catch (e) {
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
}
if (addon) {
parentPort.on('message', (msg) => {
if (!msg || msg.type !== 'enumerate') return;
try {
const pids = addon.getAllMainProcess();
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
} catch (e) {
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
}
});
parentPort.postMessage({ type: 'ready' });
}
`;
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
return [...new Set(pids)]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: processName, path: '' }));
}
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
const log = deps.log ?? createLogger('ProcessEnumerator');
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
// fallback there is a cheap socket read, not a /proc walk.
if (!deps.addonPath) {
return {
async enumerate() {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate fallback failed: %s', errMsg(err));
return null;
}
},
dispose() { /* nothing to tear down */ },
};
}
const addonPath = deps.addonPath;
let worker: Worker | null = null;
/** Set once we learn the addon can't load in a worker — permanent fallback. */
let isolationBroken = false;
let orphans = 0;
let seq = 0;
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
let disposed = false;
const spawnWorker = (): void => {
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
worker = w;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') return;
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
isolationBroken = true;
for (const { resolve } of pending.values()) resolve(null);
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) return;
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) teardownWorker();
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) return;
// terminate() can't preempt a thread blocked in the native call; it takes
// effect once the call returns. Track it as an orphan until it actually
// exits so we can bound how many we let pile up.
orphans += 1;
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
void w.terminate().catch(() => { /* already gone */ });
};
const syncFallback = (): HookProcessBaseInfo[] | null => {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate sync fallback failed: %s', errMsg(err));
return null;
}
};
return {
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
if (disposed || isolationBroken) return syncFallback();
if (!worker) {
if (orphans >= maxOrphans) {
// Too many blocked workers already piling up (a sustained hang) —
// don't spawn more; report UNKNOWN and let them drain.
return null;
}
spawnWorker();
}
const w = worker;
if (!w) return syncFallback();
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
});
try {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
pending.delete(id);
log.warn('failed to post enumerate request: %s', errMsg(err));
teardownWorker();
return syncFallback();
}
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), timeoutMs);
});
const outcome = await Promise.race([resultPromise, timeout]);
if (timer) clearTimeout(timer);
if (outcome === 'timeout') {
pending.delete(id);
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
teardownWorker();
return null;
}
if (outcome === null) {
// Native call threw inside the worker — treat as a transient failure,
// keep prior state rather than nuking every session.
return null;
}
return mapPids(outcome, deps.processName);
},
dispose() {
disposed = true;
for (const { resolve } of pending.values()) resolve(null);
pending.clear();
const w = worker;
worker = null;
if (w) void w.terminate().catch(() => { /* ignore */ });
},
};
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
@@ -192,4 +192,40 @@ describe('PipeWatcher', () => {
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
watcher.stop();
});
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
let live = new Set<number>([1234]);
const watcher = new PipeWatcher({
listProcesses: () => result,
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
const events = captureEvents(watcher);
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
result = null;
await watcher.tickNow();
expect(events).toEqual([]);
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
// Enumeration recovers with the same set → still no churn.
result = [{ pid: 1234, name: 'qq', path: '' }];
await watcher.tickNow();
expect(events).toEqual([]);
// A REAL disappearance (empty list, not null) still fires the teardown.
result = [];
live = new Set();
await watcher.tickNow();
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
watcher.stop();
});
});
@@ -0,0 +1,55 @@
import { describe, it, expect, vi } from 'vitest';
import { createNativeProcessEnumerator } from '../src/process-enumerator';
import type { HookProcessBaseInfo } from '../src/injector';
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
describe('createNativeProcessEnumerator', () => {
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
it('returns the sync lister result', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => [QQ(10), QQ(20)],
processName: 'qq',
});
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
en.dispose();
});
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => { throw new Error('boom'); },
processName: 'qq',
});
expect(await en.enumerate()).toBeNull();
en.dispose();
});
});
describe('worker isolation that cannot load the addon → permanent fallback', () => {
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
const fallback = vi.fn(() => [QQ(7)]);
const en = createNativeProcessEnumerator({
// A path that exists nowhere → process.dlopen throws in the worker →
// the worker posts 'fatal' → isolation is abandoned for good.
addonPath: '/nonexistent/snowluma-test.node',
fallbackSync: fallback,
processName: 'qq',
timeoutMs: 200,
});
// First call spawns the worker; the fatal message drains it to UNKNOWN.
const first = await en.enumerate();
expect(first).toBeNull();
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
// already, then subsequent calls take the synchronous fallback.
await new Promise((r) => setTimeout(r, 50));
const second = await en.enumerate();
expect(second).toEqual([QQ(7)]);
expect(fallback).toHaveBeenCalled();
en.dispose();
});
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.10.4",
"version": "1.11.0",
"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).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.10.4",
"version": "1.11.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+36 -12
View File
@@ -5,6 +5,9 @@ import {
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { createLogger } from '@snowluma/common/logger';
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
@@ -28,15 +31,6 @@ export interface PttTransInput {
fileId?: number;
}
function hexToBytes(hex: string): Uint8Array {
const s = (hex || '').trim();
if (!s) return new Uint8Array(0);
const len = s.length >> 1;
const out = new Uint8Array(len);
for (let i = 0; i < len; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
return out;
}
// ─────────────── public types (re-exported from bridge.ts as before) ───
export type StrangerStatus = NamespaceStrangerStatus;
@@ -55,6 +49,8 @@ export interface AiVoiceItem {
voiceExampleUrl: string;
}
const log = createLogger('Bridge.Extras');
export class ExtrasApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -126,10 +122,13 @@ export class ExtrasApi {
* already-transcribed case). For a freshly-received voice the response is an
* empty ack and the text is delivered later via the async Event 0x210
* subType-61 push — callers should treat `''` as "pending" and wait for the
* `ptt_trans_result` event (correlated by msgId). Live-verified end to end.
* `ptt_trans_result` event (correlated by msgId).
*/
async translatePttToText(input: PttTransInput): Promise<string> {
const md5 = hexToBytes(input.md5Hex);
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
const md5 = input.md5Hex.toLowerCase();
const req: PttTransReq = input.isGroup
? {
type: 1,
@@ -154,7 +153,32 @@ export class ExtrasApi {
}
const resp = protobuf_decode<PttTransResp>(result.responseData);
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
if (item?.errCode) {
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
// sourced from cache, to tell a server-side ASR failure apart from our own
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
log.warn(
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
item.errCode, input.isGroup,
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
);
throw new Error(`ptt translate failed: error=${item.errCode}`);
}
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
}
/**
* Transcode a voice record (`get_record out_format`, #165). `source` is a
* URL / local path / `base64://…` (the record's download URL in practice);
* it is loaded then transcoded to `format` via the bundled SILK-capable
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
* failed conversion.
*/
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
// default so a tampered/oversized source can't be pulled in.
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
return convertAudioBytes(bytes, format);
}
}
+100 -1
View File
@@ -24,6 +24,17 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge;
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
/** QQ's placeholder when it doesn't hand back a real sender name — treated as
* "missing" so #174's enrichment resolves the real nickname. */
const FORWARD_NAME_PLACEHOLDER = 'QQ用户';
/** Bounds on the L4 (per-uin profile) fallback when enriching forward senders.
* Profile lookups are un-cached single-point OIDB calls Tencent rate-limits
* aggressively, so cap how many distinct uins one forward resolves and how
* many run at once — the rest keep the placeholder. */
const FORWARD_PROFILE_MAX = 20;
const FORWARD_PROFILE_CONCURRENCY = 4;
// Per-layer piggyback entry. Each level of a nested forward attaches
// its own msgBody under a uuid `actionCommand`, so when the receiver
// fetches the outermost res_id it gets every layer in one shot
@@ -518,7 +529,7 @@ export class ForwardApi {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
if (cached) {
return cached.map(node => ({
const nodes = cached.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
@@ -529,6 +540,10 @@ export class ForwardApi {
senderCard: node.senderCard,
messageType: node.messageType,
}));
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
// on read (a no-op once names are present) and persist so later hits skip.
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
return nodes;
}
const selfUid = await resolveSelfUid(bridge);
@@ -588,12 +603,96 @@ export class ForwardApi {
this.consumePiggybacks(nodes, piggybackByUuid);
}
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
// isn't always populated, and the sync decode only consults the L1 cache.
await this.enrichSenders(nodes);
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
}
return nodes;
}
/** A node whose display name the server didn't give us (empty or the QQ
* placeholder) and that we can resolve (has a uin). */
private needsName(n: ForwardNodePayload): boolean {
return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER);
}
/** Backfill sender nickname/card on forward nodes the long-msg payload left
* nameless. Resolves group senders via one member-list fetch per group (L3,
* inflight+TTL cached in ContactsApi), then any residue + private nodes via
* the user-profile lookup (L4). Best-effort: a failed lookup keeps the
* placeholder rather than failing the whole forward. Returns true if any
* node was changed (so callers can persist the enriched cache). */
private async enrichSenders(nodes: ForwardNodePayload[]): Promise<boolean> {
const pending = nodes.filter(n => this.needsName(n));
if (pending.length === 0) return false;
let changed = false;
// L3 — group member lists (one fetch resolves every sender from that group).
const byGroup = new Map<number, ForwardNodePayload[]>();
const residue: ForwardNodePayload[] = [];
for (const n of pending) {
if (n.messageType === 'group' && n.groupId) {
const arr = byGroup.get(n.groupId) ?? [];
arr.push(n);
byGroup.set(n.groupId, arr);
} else {
residue.push(n);
}
}
for (const [groupId, groupNodes] of byGroup) {
let byUin: Map<number, { nickname: string; card: string }>;
try {
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }]));
} catch {
// Member list (one cheap, cached call) failed — keep the placeholder
// rather than fanning the whole group out to per-uin profile lookups.
// That error path is exactly what would amplify into a rate-limit ban.
continue;
}
for (const n of groupNodes) {
const m = byUin.get(n.userUin);
const name = m?.card || m?.nickname;
if (name) {
n.senderCard = m!.card || n.senderCard || '';
n.nickname = name;
changed = true;
} else {
residue.push(n); // in-group sender that left the group → profile fallback
}
}
}
// L4 — user profile for the residue (members who left the group, private
// nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and
// Tencent rate-limits these hard (see ContactsApi's member-list note), so:
// dedupe by uin, CAP the count (drop the rest to placeholder), and resolve
// in small concurrency-limited batches. Best-effort.
const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))]
.slice(0, FORWARD_PROFILE_MAX);
if (uins.length > 0) {
const byUin = new Map<number, string>();
for (let i = 0; i < uins.length; i += FORWARD_PROFILE_CONCURRENCY) {
const batch = uins.slice(i, i + FORWARD_PROFILE_CONCURRENCY);
const results = await Promise.all(batch.map(async (uin): Promise<readonly [number, string]> => {
try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; }
catch { return [uin, ''] as const; }
}));
for (const [uin, nick] of results) byUin.set(uin, nick);
}
for (const n of residue) {
if (!this.needsName(n)) continue;
const nick = byUin.get(n.userUin);
if (nick) { n.nickname = nick; changed = true; }
}
}
return changed;
}
/** Walk a list of PushMsgBody, run each through the regular msg-push
* pipeline, and shape the result into ForwardNodePayloads. Extracted
* so both the outer + piggyback decode paths share one implementation. */
+13 -2
View File
@@ -100,8 +100,14 @@ function normalizeUploadFileName(name: string, fallback: string): string {
return safeFallback || 'file.bin';
}
// QQ's "first 10 MB" checksum uses the magic limit 0x98A000 (10002432) —
// NOT 10*1024*1024 and not 10^7. Using the wrong limit makes the server's
// first-block verification fail for files larger than 0x98A000, so the
// offline file uploads but never finalises as downloadable (#157).
const MD5_HEAD_LIMIT = 10002432;
function md5First10MB(bytes: Uint8Array): Uint8Array {
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
const limit = Math.min(bytes.length, MD5_HEAD_LIMIT);
return computeMd5(bytes.subarray(0, limit));
}
@@ -177,7 +183,12 @@ function buildPrivateFileUploadExt(
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
// #157: NapCat/Lagrange (and the QQ client, confirmed by packet
// capture) emit a busiBuff with ONLY senderUin — no busId. A stale
// busId:102 here made the offline-file server accept the highway
// upload but never finalise it as downloadable once the file got
// big (>5 MiB): the receiver saw the file but every download failed.
// (The other half of that bug was the wrong md5-head limit above.)
senderUin: BigInt(senderUin),
receiverUin: 0n,
groupCode: 0n,
+35 -19
View File
@@ -13,6 +13,7 @@ import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-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';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
// the concrete Bridge instance when passing it to `buildSendElems`
@@ -26,6 +27,8 @@ import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
const log = createLogger('Bridge.Message');
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
@@ -240,10 +243,11 @@ export class MessageApi {
* - `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).
* `FileExtra.file` alone makes the file downloadable (verified on a live
* account). We ALSO attach `FileExtra.field6` — extra server-issued download
* routing from a best-effort 0xE37_800 finalize that mirrors NapCat and may
* help some receiver clients. The finalize is non-fatal: if it fails we send
* without field6 rather than failing the send (issue #157).
*/
async sendC2cFile(
userUin: number,
@@ -262,22 +266,31 @@ export class MessageApi {
}
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).
// The file is already downloadable from the `NotOnlineFile` reference
// alone — verified on a live account: a plain c2c file send (no field6)
// downloads fine. `field6` is EXTRA server-issued download routing (from
// the 0xE37_800 finalize) that mirrors NapCat and may help some receiver
// clients. So fetch it BEST-EFFORT: if the finalize fails, send without
// field6 rather than failing the whole send. (issue #157 — the finalize
// was originally fatal, which could regress a send that would otherwise
// succeed.)
const fileHash = info.fileHash ?? '';
const meta = await FinalizeOfflineFile.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: userUid,
fileUuid: info.fileId,
fileHash,
});
let meta: Awaited<ReturnType<typeof FinalizeOfflineFile.invoke>> | null = null;
try {
meta = await FinalizeOfflineFile.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: userUid,
fileUuid: info.fileId,
fileHash,
});
} catch (err) {
log.warn('c2c file finalize (0xE37_800) failed, sending without field6: %s',
err instanceof Error ? err.message : String(err));
}
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
const fileExtraBytes = protobuf_encode<FileExtra>({
const fileExtra: FileExtra = {
file: {
fileType: 0,
fileUuid: info.fileId,
@@ -289,7 +302,9 @@ export class MessageApi {
expireTime: nowSec + sevenDaysSec,
fileHash,
},
field6: {
};
if (meta) {
fileExtra.field6 = {
field2: {
field1: meta.field110,
fileUuid: info.fileId,
@@ -302,8 +317,9 @@ export class MessageApi {
selfUid,
destUid: userUid,
},
},
});
};
}
const fileExtraBytes = protobuf_encode<FileExtra>(fileExtra);
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
+31 -8
View File
@@ -5,18 +5,20 @@ import {
getQzoneMsgList,
publishQzoneMsg,
setQzoneLike,
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsResult,
type QzoneMsgListResult,
type QzonePublishResult,
type QzoneUploadImageResult,
} from '@snowluma/protocol/web/qzone';
import type { BridgeContext } from '../bridge-context';
/**
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
* comments — all over the cookie-backed qzone.qq.com CGIs, reusing the same
* `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi. Distinct from the
* group-album surface, which lives on GroupAlbumApi.
* comments, image upload — all over the cookie-backed qzone.qq.com CGIs,
* reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi.
* Distinct from the group-album surface, which lives on GroupAlbumApi.
*/
export class QzoneApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -40,10 +42,23 @@ export class QzoneApi {
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
}
/** 发表一条纯文字说说,返回新说说的 tid。始终发到机器人自己的空间。 */
async publish(content: string): Promise<QzonePublishResult> {
/**
* 从来源上传图片到 QQ 空间。
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
*/
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content);
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
}
/**
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
*/
async publish(content: string, richType?: number, richval?: string): Promise<QzonePublishResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval);
}
/** 删除机器人自己空间的一条说说(按 tid)。 */
@@ -66,11 +81,19 @@ export class QzoneApi {
/**
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
* (从 uploadImageFromSource 的 url 字段获取)。
*/
async comment(tid: string, content: string, targetUin: number | undefined): Promise<QzoneCommentResult> {
async comment(
tid: string,
content: string,
targetUin: number | undefined,
richType?: number,
richval?: string,
): Promise<QzoneCommentResult> {
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content);
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
}
}
+197
View File
@@ -0,0 +1,197 @@
// debug-tools — backend for the debug console's two heavier endpoints
// (Phase 2 of the debug-console expansion):
//
// • POST /api/debug/invoke-stream — drive a Stream API action and relay every
// frame to the browser over an SSE body. Unlike the live-activity stream
// (debug-stream.ts), this MUST NOT drop frames: a file transfer that loses a
// chunk is corrupt. So backpressure is handled by *waiting* for the consumer
// to drain, never by dropping.
// • POST /api/debug/upload — stream a browser-selected file to a temp path on
// the SERVER (the bot runs on the server, not the user's machine), so the
// returned path can be fed to a send action. Streamed straight to disk with a
// byte cap — never buffered whole, so large videos don't blow up memory.
//
// The pure pieces live here (path sanitisation, the size-capped disk sink, the
// stream-invoke Response builder) so they are unit-testable away from Hono.
import { createWriteStream } from 'fs';
import { mkdir, readdir, rm, stat } from 'fs/promises';
import os from 'os';
import path from 'path';
import { randomBytes } from 'crypto';
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
* kept distinct so the two cleanup stories don't entangle. */
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload');
/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */
export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
/** Uploads older than this are swept on the next upload (best-effort). */
const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
/** Reduce a client-supplied filename to a safe basename (extension preserved),
* with no path separators or traversal. The client path is NEVER trusted for
* placement — this is only used to keep the stored name human-readable. */
export function safeUploadName(raw: string | undefined): string {
// Treat both separators as path delimiters, then take the basename so any
// `../` / absolute prefix is discarded regardless of host platform.
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
const cleaned = base
.replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
.slice(0, 120);
return cleaned || 'file';
}
/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name.
* Throws if the composed path would escape the dir (defence in depth — it
* can't, given the random id + basename, but we assert anyway). */
export function uploadDestPath(safeName: string): string {
const id = randomBytes(12).toString('hex');
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
throw new Error('invalid upload path');
}
return dest;
}
/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing
* a byte cap. Returns the final server path + byte size. On overflow or any
* error the partial file is removed and the call rejects. Never buffers the
* whole body. */
export async function streamUploadToDisk(
body: ReadableStream<Uint8Array> | null,
filename: string | undefined,
opts: { maxBytes?: number } = {},
): Promise<{ path: string; size: number }> {
if (!body) throw new Error('empty body');
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
void sweepOldUploads(); // fire-and-forget TTL cleanup
const dest = uploadDestPath(safeUploadName(filename));
const out = createWriteStream(dest, { mode: 0o600 });
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
// background flush — typically while we're parked at reader.read() or waiting
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
// backpressured error would leave 'drain' to never fire (a forever-hung await
// + leaked fd). So turn it into a rejection and race it into every await; the
// catch below then destroys + unlinks the partial.
const errored = new Promise<never>((_, rej) => out.once('error', rej));
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
let size = 0;
try {
const reader = body.getReader();
for (;;) {
const { done, value } = await Promise.race([errored, reader.read()]);
if (done) break;
if (!value || value.byteLength === 0) continue;
size += value.byteLength;
if (size > maxBytes) throw new Error('上传超出大小上限');
// Respect the write stream's backpressure (but never hang on an error).
if (!out.write(value)) {
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
}
}
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
if (size === 0) throw new Error('empty body');
return { path: dest, size };
} catch (err) {
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
// opens the fd asynchronously, so a fast failure can reach `rm` before the
// file even exists on disk — then the late open would re-create it and leak
// the partial. 'close' guarantees the fd is settled and no more writes land.
out.destroy();
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
throw err;
}
}
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
let removed = 0;
try {
const names = await readdir(DEBUG_UPLOAD_DIR);
await Promise.all(
names.map(async (n) => {
const p = path.join(DEBUG_UPLOAD_DIR, n);
try {
const s = await stat(p);
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
await rm(p, { force: true, recursive: true });
removed += 1;
}
} catch { /* racing cleanup / vanished file */ }
}),
);
} catch { /* dir absent yet */ }
return removed;
}
/** Drives a stream-capable action and relays its frames. The driver is the
* instance's `invokeStream` (which itself handles non-stream actions by emitting
* a single frame). */
export type StreamInvokeDriver = (
rawRequest: string,
emit: (json: string) => Promise<void>,
isAlive: () => boolean,
) => Promise<void>;
/** How long emit() will wait for a backed-up consumer to drain before it gives
* up waiting and enqueues anyway (the request abort / action idle-watchdog are
* the real stall guards). */
const DRAIN_WAIT_MS = 20;
const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s
/** Build the SSE `Response` for `/api/debug/invoke-stream`: each relayed frame
* is one `data: <json>\n\n` event; no frame is ever dropped. A driver error
* becomes a terminal `failed` frame. Closing the request (signal abort) stops
* delivery. `delay` is injectable for tests. */
export function buildStreamInvokeResponse(
driver: StreamInvokeDriver,
rawRequest: string,
signal: AbortSignal,
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
const onAbort = () => { closed = true; };
signal.addEventListener('abort', onAbort);
const isAlive = () => !closed && !signal.aborted;
const emit = async (json: string): Promise<void> => {
if (!isAlive()) throw new Error('stream transport closed');
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
let spins = 0;
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
await delay(DRAIN_WAIT_MS);
spins += 1;
}
if (!isAlive()) throw new Error('stream transport closed');
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
};
try {
await driver(rawRequest, emit, isAlive);
} catch (err) {
if (isAlive()) {
const msg = err instanceof Error ? err.message : 'stream error';
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
} catch { /* controller already torn down */ }
}
} finally {
signal.removeEventListener('abort', onAbort);
try { controller.close(); } catch { /* already closed */ }
}
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
}
+37
View File
@@ -22,6 +22,7 @@ import { coerceSettingsPatch } from './system-settings';
import { buildBackup, planRestore, validateBackup } from './backup';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
@@ -929,6 +930,42 @@ export async function initWebUI(
return c.json(result);
});
// Invoke a Stream API action (or any action) and relay every frame to the
// browser over an SSE body. The frontend reads this with fetch()+a stream
// reader (Bearer auth in the header), so — unlike /api/debug/stream — it does
// NOT need a query-token allowlist entry. Frames are never dropped.
app.post('/api/debug/invoke-stream', async (c) => {
let body: unknown;
try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); }
const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown };
if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400);
if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400);
if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) {
return c.json({ status: 'failed', message: 'params 必须是对象' }, 400);
}
const inst = oneBotManager.getInstance(uin);
if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404);
const rawRequest = JSON.stringify({ action, params: params ?? {} });
return buildStreamInvokeResponse(
(rq, emit, alive) => inst.invokeStream(rq, emit, alive),
rawRequest,
c.req.raw.signal,
);
});
// Stream a browser-selected file to a temp path on THIS server (the bot runs
// here, not on the operator's machine), so the returned path can be fed to a
// send action's file/image/record/video param. Raw bytes in the body,
// `?filename=` for a human-readable suffix; streamed to disk with a byte cap.
app.post('/api/debug/upload', async (c) => {
try {
const result = await streamUploadToDisk(c.req.raw.body as ReadableStream<Uint8Array> | null, c.req.query('filename'));
return c.json({ status: 'ok', path: result.path, size: result.size });
} catch (err) {
return c.json({ status: 'failed', message: err instanceof Error ? err.message : '上传失败' }, 400);
}
});
// Live merged SSE of OneBot events + action calls across all accounts. Taps
// are attached only while a client is connected (on-demand). A slow client is
// dropped (not back-pressured onto the bot) with a periodic drop marker.
@@ -151,3 +151,71 @@ describe('actions/forward', () => {
expect(sendRawPacket).toHaveBeenCalledOnce();
});
});
describe('actions/forward — sender name enrichment (#174)', () => {
function apiWith(contacts: { fetchGroupMemberList: any; fetchUserProfile: any }) {
return new ForwardApi({ apis: { contacts } } as any);
}
it('fills empty / "QQ用户" names via the group member list (L3), card preferred', async () => {
const fetchGroupMemberList = vi.fn(async () => [
{ uin: 10001, nickname: 'AliceNick', card: 'AliceCard' },
{ uin: 10002, nickname: 'BobNick', card: '' },
]);
const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'Stranger' }));
const api = apiWith({ fetchGroupMemberList, fetchUserProfile });
const nodes: any[] = [
{ userUin: 10001, nickname: '', groupId: 700, messageType: 'group', elements: [] },
{ userUin: 10002, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] },
{ userUin: 10003, nickname: '', groupId: 700, messageType: 'group', elements: [] }, // not in list
{ userUin: 10009, nickname: '', messageType: 'private', elements: [] }, // private
{ userUin: 10005, nickname: 'KeepMe', groupId: 700, messageType: 'group', elements: [] },
];
const changed = await (api as any).enrichSenders(nodes);
expect(changed).toBe(true);
expect(nodes[0].nickname).toBe('AliceCard'); // card preferred over nick
expect(nodes[0].senderCard).toBe('AliceCard');
expect(nodes[1].nickname).toBe('BobNick'); // card empty → nickname
expect(nodes[2].nickname).toBe('Stranger'); // not in member list → L4 profile
expect(nodes[3].nickname).toBe('Stranger'); // private node → L4 profile
expect(nodes[4].nickname).toBe('KeepMe'); // already named → untouched
expect(fetchGroupMemberList).toHaveBeenCalledTimes(1); // one fetch covers the whole group
});
it('is a no-op (no fetch) when every node already has a name', async () => {
const fetchGroupMemberList = vi.fn();
const fetchUserProfile = vi.fn();
const api = apiWith({ fetchGroupMemberList, fetchUserProfile });
const nodes: any[] = [{ userUin: 1, nickname: 'has-name', groupId: 7, messageType: 'group', elements: [] }];
expect(await (api as any).enrichSenders(nodes)).toBe(false);
expect(fetchGroupMemberList).not.toHaveBeenCalled();
});
it('keeps the placeholder and never throws when resolution fails', async () => {
const api = apiWith({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net down'); }),
fetchUserProfile: vi.fn(async () => { throw new Error('net down'); }),
});
const nodes: any[] = [{ userUin: 10001, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] }];
await expect((api as any).enrichSenders(nodes)).resolves.toBe(false);
expect(nodes[0].nickname).toBe('QQ用户');
});
it('does NOT fan a member-list failure out to per-uin profile lookups (rate-limit guard)', async () => {
const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'X' }));
const api = apiWith({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
fetchUserProfile,
});
// 5 distinct group senders whose member list errors → must keep placeholder,
// NOT trigger 5 profile calls.
const nodes: any[] = Array.from({ length: 5 }, (_, i) => ({
userUin: 20000 + i, nickname: '', groupId: 700, messageType: 'group', elements: [],
}));
expect(await (api as any).enrichSenders(nodes)).toBe(false);
expect(fetchUserProfile).not.toHaveBeenCalled();
expect(nodes.every((n) => n.nickname === '')).toBe(true);
});
});
+54 -4
View File
@@ -49,16 +49,57 @@ describe('apis/qzone', () => {
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
});
it('publish posts to the bot\'s own space with the given content', async () => {
it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK', skey: 'SK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const uploadSpy = vi.spyOn(qzoneWeb, 'uploadQzoneImageFromSource').mockResolvedValue({
richval: ',12345,abc,abc,22,800,600,,800,600',
url: 'https://example.com/img.jpg',
albumid: '12345',
lloc: 'abc',
type: 22,
width: 600,
height: 800,
});
const out = await new QzoneApi(bridge as never).uploadImageFromSource('file:///path/to/image.jpg');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(uploadSpy).toHaveBeenCalledWith({ p_skey: 'PSK', skey: 'SK' }, '10001', 'file:///path/to/image.jpg');
expect(out.richval).toBe(',12345,abc,abc,22,800,600,,800,600');
expect(out.url).toBe('https://example.com/img.jpg');
});
it('publish posts to the bot\'s own space with the given content (text-only)', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
const out = await new QzoneApi(bridge as never).publish('hello');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined);
expect(out).toEqual({ tid: 'T', time: 1 });
});
it('publish posts with richtype and richval for image post', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T2', time: 2 });
const richval = ',12345,abc,abc,22,800,600,,800,600';
const out = await new QzoneApi(bridge as never).publish('look at this', 1, richval);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval);
expect(out).toEqual({ tid: 'T2', time: 2 });
});
it('publish posts with multiple images (richval joined with tab)', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T3', time: 3 });
const richval = ',12345,a,a,22,800,600,,800,600\t,12346,b,b,22,1024,768,,1024,768';
const out = await new QzoneApi(bridge as never).publish('two images', 1, richval);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval);
expect(out).toEqual({ tid: 'T3', time: 3 });
});
it('delete removes a feed by tid from the bot\'s own space', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
@@ -92,7 +133,7 @@ describe('apis/qzone', () => {
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '1' });
const out = await new QzoneApi(bridge as never).comment('TIDX', 'nice', undefined);
// selfUin='10001' commenter; owner defaults to self
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice');
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice', undefined, undefined);
expect(out).toEqual({ comment_id: '1' });
});
@@ -101,6 +142,15 @@ describe('apis/qzone', () => {
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '2' });
await new QzoneApi(bridge as never).comment('TIDX', 'nice', 20002);
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice');
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice', undefined, undefined);
});
it('comment with images (richType=1, richval=direct URLs joined with tab)', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '3' });
const richval = 'https://example.com/a.jpg\thttps://example.com/b.jpg';
await new QzoneApi(bridge as never).comment('TIDX', 'nice pic', undefined, 1, richval);
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice pic', 1, richval);
});
});
@@ -136,8 +136,9 @@ 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.
// issue #157: when the 0xE37_800 finalize succeeds, its download routing
// rides along in field6 (best-effort enrichment on top of the always-
// present NotOnlineFile).
expect(bridge.finalizeCmd).toBe('OidbSvcTrpcTcp.0xe37_800');
expect(fileExtra?.field6?.field2).toMatchObject({
fileUuid: 'uuid-abc-123',
@@ -157,4 +158,46 @@ describe('Bridge private media routing', () => {
// c2c-file path.
expect(request?.contentHead?.c2cCmd ?? 0).toBe(0);
});
it('c2c file send survives a failing 0xE37_800 finalize — sends without field6 (#157 best-effort)', async () => {
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | 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> {
// Finalize fails (server error → OidbError). The send must NOT fail
// because of it.
if (cmd.includes('0xe37_800')) {
return { success: false, gotResponse: true, errorCode: 9999, errorMessage: 'finalize boom', responseData: Buffer.alloc(0) };
}
this.capturedBody = body;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000,
})),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
// Should resolve (not throw) despite the finalize error.
await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
fileId: 'uuid-abc-123', fileName: 'doc.txt', fileSize: 1024,
fileMd5: new Uint8Array([1, 2, 3, 4]), fileHash: 'hash-xyz',
});
// PbSendMsg still went out, carrying the file but NO field6.
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
const fileExtra = protobuf_decode<FileExtra>(request!.messageBody!.msgContent as Uint8Array);
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
});
});
+4 -106
View File
@@ -283,112 +283,10 @@ describe('pipeline — runNtv2Upload', () => {
}))).rejects.toThrow(/image fast-upload not available/);
});
// ─────────── forceFullOnFastPath (video stale-resource fallback, #145) ───────────
// Bridge whose sendRawPacket returns a different OIDB response per call,
// so we can model "round 1 fast-paths the main file, round 2 demands the
// bytes after we disable fast-upload".
function makeSequencedBridge(responses: Buffer[]) {
let call = 0;
const sendRawPacket = vi.fn<(cmd: string, body: Uint8Array) => Promise<SendPacketResult>>(
async () => {
const responseData = responses[Math.min(call, responses.length - 1)]!;
call += 1;
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
},
);
return { sendRawPacket };
}
it('forceFullOnFastPath: re-requests with fast-upload disabled when the flagged main file is fast-pathed', async () => {
const bridge = makeSequencedBridge([
// Round 1: server fast-paths the main file (no uKey) but demands nothing.
encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } /* no uKey */ } }),
// Round 2 (fast-upload disabled): server now hands back a uKey.
encodeOidbResponse({
upload: {
uKey: 'fresh-ukey',
ipv4s: [{ ipv4: '1.2.3.4', port: 80 }],
msgInfo: { msgInfoBody: [], extBizInfo: {} },
},
}),
]);
const upload = await runNtv2Upload(baseParams({
bridge,
label: 'video',
uploads: [{
source: 'top',
cmdId: 1003,
bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16),
sha1: new Uint8Array(20),
forceFullOnFastPath: true,
}],
}));
// Two OIDB requests went out; the second omits tryFastUploadCompleted
// (proton drops `false`), which the server reads as "no fast-upload".
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
const firstReq: any = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[0]![1] as Uint8Array);
const secondReq: any = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[1]![1] as Uint8Array);
expect(firstReq.body.upload.tryFastUploadCompleted).toBe(true);
expect(secondReq.body.upload.tryFastUploadCompleted ?? false).toBe(false);
// The forced full upload PUT ran, and the returned upload is round 2's.
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(upload.uKey).toBe('fresh-ukey');
});
it('forceFullOnFastPath: no retry when the flagged file gets a uKey on the first try', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
upload: { uKey: 'ukey-1', msgInfo: { msgInfoBody: [], extBizInfo: {} } },
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top', cmdId: 1003, bytes: new Uint8Array([1, 2, 3]),
md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true,
}],
}));
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('forceFullOnFastPath: no retry for a fast-pathed forward (no bytes to upload)', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [{
source: 'top', cmdId: 1003, bytes: new Uint8Array(0),
md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true,
}],
}));
// bytes.length === 0 → nothing to distrust; the fast-path stands.
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).not.toHaveBeenCalled();
});
it('a fast-pathed sub-file WITHOUT the flag (e.g. thumb) does not trigger a retry', async () => {
const bridge = makeBridge({
responseData: encodeOidbResponse({
// Main fully uploaded (has uKey); thumb fast-pathed (no subFileInfos).
upload: { uKey: 'main-ukey', msgInfo: { msgInfoBody: [], extBizInfo: {} } },
}),
});
await runNtv2Upload(baseParams({
bridge,
uploads: [
{ source: 'top', cmdId: 1001, bytes: new Uint8Array([1]), md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true },
{ source: 0, cmdId: 1002, bytes: new Uint8Array([2]), md5: new Uint8Array(16), sha1: new Uint8Array(20) /* no flag */ },
],
}));
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
});
// (Removed the forceFullOnFastPath retry tests with the feature itself — real-
// machine testing + kernel RE proved the tryFastUploadCompleted:false retry
// never forces a fresh upload; expired-but-indexed video resources are a
// platform limitation. See #145.)
it('silently skips a sub-file with empty bytes when no fastOnlyError is configured', async () => {
// This mirrors the video-thumb path where bytes are always synthesised
@@ -80,14 +80,14 @@ describe('video-upload', () => {
expect(uploads[1]!.fastOnlyError).toBeUndefined();
});
it('main file distrusts a server fast-path (forceFullOnFastPath); thumb does not (#145)', async () => {
// Group/c2c video resources expire server-side: a fast-path hit can
// reference a stale object the receiver shows as "资源已过期", so the
// main file forces a fresh full upload. The thumb stays fast-path-OK.
it('does NOT set a force-full retry flag on the main file (#145 — proven ineffective)', async () => {
// The old forceFullOnFastPath retry was removed: real-machine + kernel RE
// showed it never forces a fresh upload (the server fast-paths by md5
// metadata regardless of tryFastUploadCompleted). An expired-but-indexed
// video resource is a platform limitation, not an upload-flow fix.
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
expect(uploads[0]!.forceFullOnFastPath).toBe(true);
expect(uploads[1]!.forceFullOnFastPath).toBeUndefined();
expect((uploads[0] as unknown as Record<string, unknown>).forceFullOnFastPath).toBeUndefined();
});
it('uploadInfo carries TWO entries (main mp4 + thumb jpg) with subFileType 0 and 100', async () => {
@@ -0,0 +1,151 @@
import { afterAll, describe, expect, it } from 'vitest';
import { readdir, readFile, rm } from 'fs/promises';
import path from 'path';
import {
buildStreamInvokeResponse,
DEBUG_UPLOAD_DIR,
safeUploadName,
streamUploadToDisk,
uploadDestPath,
} from '../src/webui/debug-tools';
const written: string[] = [];
afterAll(async () => {
await Promise.all(written.map((p) => rm(p, { force: true }).catch(() => {})));
});
function streamOf(...chunks: Uint8Array[]): ReadableStream<Uint8Array> {
let i = 0;
return new ReadableStream<Uint8Array>({
pull(controller) {
if (i < chunks.length) controller.enqueue(chunks[i++]);
else controller.close();
},
});
}
async function readSse(res: Response): Promise<string[]> {
const text = await res.text();
return text.split('\n\n').filter((s) => s.startsWith('data: ')).map((s) => s.slice('data: '.length));
}
describe('safeUploadName', () => {
it('strips path traversal and separators to a bare basename', () => {
expect(safeUploadName('../../etc/passwd')).toBe('passwd');
expect(safeUploadName('/abs/secret.key')).toBe('secret.key');
expect(safeUploadName('a\\b\\c.png')).toBe('c.png');
expect(safeUploadName('..')).toBe('file'); // leading dots stripped → empty → fallback
expect(safeUploadName('...hidden')).toBe('hidden');
});
it('collapses exotic chars and falls back for empties', () => {
expect(safeUploadName('my pic!@#.jpg')).toBe('my_pic_.jpg');
expect(safeUploadName('')).toBe('file');
expect(safeUploadName(undefined)).toBe('file');
});
it('keeps the extension and caps length', () => {
const long = 'x'.repeat(500) + '.mp4';
const out = safeUploadName(long);
expect(out.length).toBeLessThanOrEqual(120);
expect(out.startsWith('x')).toBe(true);
});
});
describe('uploadDestPath', () => {
it('produces a unique path inside the upload dir', () => {
const a = uploadDestPath('pic.png');
const b = uploadDestPath('pic.png');
expect(a).not.toBe(b); // random id prefix
expect(path.dirname(a)).toBe(DEBUG_UPLOAD_DIR);
expect(a.endsWith('__pic.png')).toBe(true);
const rel = path.relative(DEBUG_UPLOAD_DIR, a);
expect(rel.startsWith('..')).toBe(false);
expect(path.isAbsolute(rel)).toBe(false);
});
});
describe('streamUploadToDisk', () => {
it('streams bytes to disk and reports the size', async () => {
const data = new TextEncoder().encode('hello debug upload');
const res = await streamUploadToDisk(streamOf(data.slice(0, 5), data.slice(5)), 'note.txt');
written.push(res.path);
expect(res.size).toBe(data.byteLength);
expect(path.dirname(res.path)).toBe(DEBUG_UPLOAD_DIR);
expect(await readFile(res.path, 'utf8')).toBe('hello debug upload');
});
it('rejects and removes the partial file when the cap is exceeded', async () => {
const big = new Uint8Array(64);
await expect(
streamUploadToDisk(streamOf(big, big), 'big.bin', { maxBytes: 100 }),
).rejects.toThrow(/大小上限/);
// the partial must not survive — no leftover `__big.bin` in the dir
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
expect(names.filter((n) => n.endsWith('__big.bin'))).toEqual([]);
});
it('rejects an empty body', async () => {
await expect(streamUploadToDisk(null, 'x')).rejects.toThrow(/empty/);
await expect(streamUploadToDisk(streamOf(), 'x')).rejects.toThrow(/empty/);
});
it('propagates a mid-transfer source error and removes the partial', async () => {
const failing = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode('partial-bytes'));
controller.error(new Error('source aborted'));
},
});
await expect(streamUploadToDisk(failing, 'oops.bin')).rejects.toThrow(/source aborted/);
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
expect(names.filter((n) => n.endsWith('__oops.bin'))).toEqual([]);
});
});
describe('buildStreamInvokeResponse', () => {
const noDelay = async () => {};
it('relays each emitted frame as one SSE event, in order', async () => {
const ac = new AbortController();
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
await emit(JSON.stringify({ data: { type: 'stream', i: 1 } }));
await emit(JSON.stringify({ data: { type: 'stream', i: 2 } }));
await emit(JSON.stringify({ status: 'ok', data: { type: 'response' } }));
};
const res = buildStreamInvokeResponse(driver, '{"action":"x"}', ac.signal, noDelay);
const frames = (await readSse(res)).map((s) => JSON.parse(s));
expect(frames).toHaveLength(3);
expect(frames[0].data.i).toBe(1);
expect(frames[2].data.type).toBe('response');
});
it('turns a driver error into a terminal failed frame', async () => {
const ac = new AbortController();
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
await emit(JSON.stringify({ data: { type: 'stream' } }));
throw new Error('disk exploded');
};
const res = buildStreamInvokeResponse(driver, '{}', ac.signal, noDelay);
const frames = (await readSse(res)).map((s) => JSON.parse(s));
expect(frames).toHaveLength(2);
expect(frames[1].status).toBe('failed');
expect(frames[1].message).toMatch(/disk exploded/);
});
it('passes the raw request through to the driver', async () => {
const ac = new AbortController();
let seen = '';
const driver = async (rq: string, emit: (j: string) => Promise<void>) => {
seen = rq;
await emit('{"data":{"type":"response"}}');
};
const res = buildStreamInvokeResponse(driver, '{"action":"test_download_stream"}', ac.signal, noDelay);
await readSse(res);
expect(seen).toBe('{"action":"test_download_stream"}');
});
it('exposes an SSE content-type', () => {
const ac = new AbortController();
const res = buildStreamInvokeResponse(async () => {}, '{}', ac.signal, noDelay);
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.10.4",
"version": "1.11.0",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+8
View File
@@ -11,6 +11,11 @@ export interface CatalogParam {
default?: unknown;
desc?: string;
values?: ReadonlyArray<string | number>;
/** Semantic role (group_id / user_id / member_id / image / face_id / …),
* orthogonal to `type`; drives smart-widget selection in the WebUI console.
* Kept as a loose string here so the package stays decoupled from onebot's
* FieldRole union. */
role?: string;
/** JSON Schema fragment for this single field. */
schema?: Record<string, unknown>;
}
@@ -27,6 +32,9 @@ export interface CatalogAction {
* read/write tool routing: read-only → query_action, else → invoke_action.
* Classified at the source spec by what the action's `run` actually does. */
readOnly: boolean;
/** True for Stream API actions (multi-frame transport). Absent ⇒ ordinary
* single-response action. */
stream?: boolean;
params: CatalogParam[];
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
invariants: string[];
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.10.4",
"version": "1.11.0",
"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>'`.",
+8 -2
View File
@@ -12,7 +12,7 @@
// deferred product decision; this module produces format-agnostic data plus a
// Markdown default. Point any renderer at `collectActionDocs()`.
import type { ActionDoc, ActionSpec, Field } from './action-kit';
import type { ActionDoc } from './action-kit';
import { actions as infoActions } from './actions/info';
import { actions as messageActions } from './actions/message';
import { actions as friendActions } from './actions/friend';
@@ -23,8 +23,13 @@ import { actions as requestActions } from './actions/request';
import { actions as extendedActions } from './actions/extended';
import { actions as groupAlbumActions } from './actions/group-album';
import { actions as qzoneActions } from './actions/qzone';
import { actions as streamFileActions } from './actions/stream-file';
import { actions as streamDownloadActions } from './actions/stream-download';
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
// The doc collector only ever calls `describe()`, so any spec carrying it
// qualifies — this admits both `defineAction` (ActionSpec) and
// `defineStreamAction` (StreamActionSpec) results without coupling to either.
type AnySpec = { describe(): ActionDoc };
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
@@ -38,6 +43,7 @@ const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
{ category: '扩展', specs: extendedActions },
{ category: '群相册', specs: groupAlbumActions },
{ category: '空间', specs: qzoneActions },
{ category: '流式接口', specs: [...streamFileActions, ...streamDownloadActions] },
];
/** Every declarative action's doc (with category), sorted by name. */
+166 -13
View File
@@ -21,6 +21,7 @@
import { RETCODE, failedResponse } from './types';
import type { ApiResponse, JsonObject, JsonValue } from './types';
import type { ApiActionContext, ApiHandler } from './api-handler';
import { type StreamSink, NOOP_SINK } from './streaming';
// ─────────────────────────── result currency ───────────────────────────
@@ -43,12 +44,33 @@ type Raw = JsonValue | typeof MISSING;
* them into an action's `inputSchema` (consumed by docs / the MCP). */
export type JsonSchema = Record<string, unknown>;
/** Semantic role of a param, orthogonal to `type` (which governs coercion).
* Two `uint` fields `group_id` and `user_id` coerce identically but mean
* different things — `role` is what a UI keys its picker/widget off of.
* Closed set: consumers (the WebUI debug console) switch on it exhaustively
* and fall back to the plain typed control for anything unrecognised. */
export type FieldRole =
| 'group_id'
| 'user_id'
| 'member_id' // a group member's uin — its picker depends on a sibling group_id
| 'message_id'
| 'file_id'
| 'file'
| 'image'
| 'record'
| 'video'
| 'duration'
| 'timestamp'
| 'face_id';
export interface FieldDoc {
type: string;
required: boolean;
default?: JsonValue;
desc?: string;
values?: readonly (string | number)[];
/** Semantic role driving UI widget selection; orthogonal to `type`. */
role?: FieldRole;
/** JSON Schema fragment for this field's value (constraints only; presence
* and default are applied at the object level by `describe()`). */
schema?: JsonSchema;
@@ -64,6 +86,10 @@ export interface Field<T> {
* numeric field is an error, not a silent fallback). */
default(value: T): Field<T>;
describe(text: string): Field<T>;
/** Stamp a semantic role (escape hatch for params whose name lies, or to
* override a preset). Most call sites use the `f.groupId()`-style semantic
* constructors instead. */
role(role: FieldRole): Field<T>;
/** Complete JSON Schema for this field's value (constraints + description +
* default). Object-level required-ness is handled by `describe()`. */
toJsonSchema(): JsonSchema;
@@ -103,10 +129,15 @@ class FieldImpl<T> implements Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
}
role(role: FieldRole): Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, role });
}
toJsonSchema(): JsonSchema {
const out: JsonSchema = { ...(this.doc.schema ?? {}) };
if (this.doc.desc) out.description = this.doc.desc;
if (this.doc.default !== undefined) out.default = this.doc.default;
if (this.doc.role) out['x-role'] = this.doc.role;
return out;
}
}
@@ -147,6 +178,21 @@ function strSchema(opts: StrOpts): JsonSchema {
return s;
}
/** Coerce to string (numbers/booleans stringify; matches legacy `asString`),
* then apply emptiness / length bounds. Shared by `f.string()` and the
* string-valued semantic constructors. */
function stringCore(opts: StrOpts): Core<string> {
return (raw, field) => {
let s: string;
if (typeof raw === 'string') s = raw;
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
else return err(field, 'expected a string');
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
return ok(s);
};
}
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
const core: Core<E[]> = (raw, field) => {
if (!Array.isArray(raw)) return err(field, 'expected an array');
@@ -180,7 +226,59 @@ export const f = {
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
* signed int32 hash) — do NOT use `uint()` for message_id. */
messageId(): Field<number> {
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) });
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, role: 'message_id', schema: intSchema({ nonZero: true }) });
},
// ── Semantic constructors (role-stamped) ──
// Each wraps a coercion primitive and stamps a `role` so the WebUI debug
// console renders the right picker. The Agent backfill replaces a bare
// `f.uint()` named `group_id` with `f.groupId()`, etc. — purely additive to
// coercion (a groupId still coerces exactly like a uint).
/** Group number (uint) → group picker. */
groupId(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'group_id', schema: intSchema({ min: 1 }) });
},
/** Friend / stranger uin (uint) → friend picker. */
userId(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'user_id', schema: intSchema({ min: 1 }) });
},
/** Group member's uin (uint) → member picker, linked to a sibling group_id. */
memberId(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'member_id', schema: intSchema({ min: 1 }) });
},
/** Opaque file id (string) → file picker / history. */
fileId(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file_id', schema: strSchema({ allowEmpty: false }) });
},
// Media sources reject '' (an empty path/URL is meaningless) — this matches
// the `f.string({ allowEmpty: false })` they replace during backfill, so the
// swap preserves the empty-string guard.
/** Local path / URL / base64 of a generic file → FileSource control. */
file(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file', schema: strSchema({ allowEmpty: false }) });
},
/** Image source (path / URL / base64) → FileSource control. */
image(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'image', schema: strSchema({ allowEmpty: false }) });
},
/** Voice/record source → FileSource control. */
record(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'record', schema: strSchema({ allowEmpty: false }) });
},
/** Video source → FileSource control. */
video(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'video', schema: strSchema({ allowEmpty: false }) });
},
/** Seconds (int ≥ 0) → duration control. */
duration(): Field<number> {
return new FieldImpl<number>(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'duration', schema: intSchema({ min: 0 }) });
},
/** Unix timestamp (int ≥ 0) → datetime control. */
timestamp(): Field<number> {
return new FieldImpl<number>(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'timestamp', schema: intSchema({ min: 0 }) });
},
/** QQ face id (non-negative int; face 0 is valid) → face grid. */
faceId(): Field<number> {
return new FieldImpl<number>(intCore('a non-negative integer', { min: 0 }), { type: 'int', required: true, role: 'face_id', schema: intSchema({ min: 0 }) });
},
/** Finite number (fractions allowed). */
number(): Field<number> {
@@ -193,15 +291,7 @@ export const f = {
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
* allowed by default; `{ allowEmpty: false }` rejects ''. */
string(opts: StrOpts = {}): Field<string> {
return new FieldImpl<string>((raw, field) => {
let s: string;
if (typeof raw === 'string') s = raw;
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
else return err(field, 'expected a string');
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
return ok(s);
}, { type: 'string', required: true, schema: strSchema(opts) });
return new FieldImpl<string>(stringCore(opts), { type: 'string', required: true, schema: strSchema(opts) });
},
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
bool(): Field<boolean> {
@@ -338,6 +428,10 @@ export interface ActionDoc {
/** 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;
/** True for Stream API actions (`defineStreamAction`) — they push multiple
* frames through a sink, so a caller must use the streaming transport rather
* than a single request/response. Absent ⇒ ordinary single-response action. */
stream?: boolean;
params: ParamDoc[];
invariants: string[];
/** Composed JSON Schema for the whole params object (properties + required). */
@@ -445,6 +539,63 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
};
}
// ─────────────────────────── defineStreamAction ───────────────────────────
// A Stream API action (#163): same param contract + doc machinery as
// `defineAction`, but `run` additionally receives a `StreamSink` to push
// intermediate frames, and it registers via `registerStreamAction` so the
// network adapter streams its output. The handler's return value is still the
// terminal `ApiResponse` (the final frame). Reuses `defineAction` for
// parse/describe so the two stay in lock-step.
interface StreamActionDef<S extends Spec> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
returnsSchema?: JsonSchema;
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
}
export interface StreamActionSpec<S extends Spec> {
readonly names: string[];
readonly params: S;
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): StreamActionSpec<S> {
// Borrow defineAction's parse + describe (run is never invoked — register
// below installs the sink-aware handler instead).
const base = defineAction<S>({
name: def.name,
summary: def.summary,
returns: def.returns,
returnsSchema: def.returnsSchema,
readOnly: def.readOnly,
params: def.params,
rules: def.rules,
run: () => failedResponse(RETCODE.INTERNAL_ERROR, 'stream action dispatched without a sink'),
});
return {
names: base.names,
params: def.params,
parse: base.parse,
describe: () => ({ ...base.describe(), stream: true }),
register: (h, ctx) => {
const handler = async (params: JsonObject, sink?: StreamSink): Promise<ApiResponse> => {
const r = base.parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params, sink ?? NOOP_SINK);
};
for (const name of base.names) h.registerStreamAction(name, handler);
},
};
}
// ─────────────────────────── presets ───────────────────────────
// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the
// dominant shape. The injected fields are surfaced in `describe()` so docs
@@ -466,7 +617,7 @@ interface PresetDef<S extends Spec, Extra> {
/** Pre-seeds `group_id` (uint, required). */
export function groupAction<S extends Spec>(def: PresetDef<S, { group_id: number }>): ActionSpec<WithGroup<S>> {
const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
const params = { group_id: f.groupId().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroup<S>>);
}
@@ -475,8 +626,10 @@ export function groupUserAction<S extends Spec>(
def: PresetDef<S, { group_id: number; user_id: number }>,
): ActionSpec<WithGroupUser<S>> {
const params = {
group_id: f.uint().describe('群号'),
user_id: f.uint().describe('QQ 号'),
group_id: f.groupId().describe('群号'),
// In a group action, the user_id is a member of *that* group — so its
// picker links to the sibling group_id (member_id role, not user_id).
user_id: f.memberId().describe('QQ 号'),
...(def.params ?? {}),
} as WithGroupUser<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
+60 -46
View File
@@ -141,7 +141,7 @@ export const actions = [
name: 'send_like',
summary: '点赞',
params: {
user_id: f.uint(),
user_id: f.userId(),
// 原实现用 `asNumber(times) || 1`,present 0 会被当作缺省 1。
times: f.int({ min: 0 }).default(1),
},
@@ -155,8 +155,8 @@ export const actions = [
name: 'friend_poke',
summary: '好友拍一拍',
params: {
user_id: f.uint(),
target_id: f.uint().optional(),
user_id: f.userId(),
target_id: f.userId().optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.interaction.sendPoke(false, p.user_id, p.target_id);
@@ -177,8 +177,8 @@ export const actions = [
name: 'send_poke',
summary: '拍一拍(群聊/私聊自动路由)',
params: {
user_id: f.uint(),
group_id: f.uint().optional(),
user_id: f.userId(),
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
if (p.group_id) {
@@ -233,7 +233,7 @@ export const actions = [
name: 'set_group_reaction',
summary: '群聊表情回应',
params: {
group_id: f.uint().optional(),
group_id: f.groupId().optional(),
message_id: f.messageId(),
code: f.string({ allowEmpty: false }),
is_set: f.bool().default(true),
@@ -272,7 +272,7 @@ export const actions = [
defineAction({
name: 'add_custom_face',
summary: '添加收藏表情',
params: { file: f.string({ allowEmpty: false }) },
params: { file: f.image() },
run: async (p, ctx) => {
try {
const emojiId = await ctx.bridge.apis.profile.addCustomFace(p.file);
@@ -339,7 +339,7 @@ export const actions = [
// param-validation time (retcode 1400) before run() ever fires. Use a
// plain signed int; `.default(0)` keeps absent/present-0 → "fetch latest"
// (matches the original `asNumber(message_id) || 0`). `count` stays ≥0.
message_id: f.int().default(0),
message_id: f.int().default(0).role('message_id'),
count: f.int({ min: 0 }).default(20),
},
run: async (p, ctx) => {
@@ -361,9 +361,9 @@ export const actions = [
required: ['messages'],
},
params: {
user_id: f.uint(),
user_id: f.userId(),
// Signed int32 hash, frequently negative — see get_group_msg_history.
message_id: f.int().default(0),
message_id: f.int().default(0).role('message_id'),
count: f.int({ min: 0 }).default(20),
},
run: async (p, ctx) => {
@@ -378,7 +378,7 @@ export const actions = [
summary: '标记群消息已读',
params: {
message_id: f.messageId(),
group_id: f.uint().optional(),
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
@@ -400,7 +400,7 @@ export const actions = [
summary: '标记私聊消息已读',
params: {
message_id: f.messageId(),
user_id: f.uint().optional(),
user_id: f.userId().optional(),
},
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
@@ -447,7 +447,7 @@ export const actions = [
summary: '发送群公告',
params: {
content: f.string({ allowEmpty: false }),
image: f.string().default(''),
image: f.string().default('').role('image'),
pinned: f.raw(),
type: f.raw(),
confirm_required: f.raw(),
@@ -490,7 +490,7 @@ export const actions = [
params: {
messages: f.message().optional(),
message: f.message().optional(),
group_id: f.uint().optional(),
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
const messages = p.messages ?? p.message;
@@ -514,7 +514,7 @@ export const actions = [
params: {
messages: f.message().optional(),
message: f.message().optional(),
group_id: f.uint().optional(),
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
const messages = p.messages ?? p.message;
@@ -531,8 +531,8 @@ export const actions = [
summary: '获取图片信息',
readOnly: true,
params: {
file: f.string().default(''),
file_id: f.string().default(''),
file: f.string().default('').role('image'),
file_id: f.string().default('').role('file_id'),
},
run: async (p, ctx) => {
const file = p.file || p.file_id;
@@ -545,18 +545,32 @@ export const actions = [
defineAction({
name: 'get_record',
summary: '获取语音信息',
summary: '获取语音信息;传 out_format 则服务端转码并附带 base64',
readOnly: true,
params: {
file: f.string().default(''),
file_id: f.string().default(''),
file: f.string().default('').role('record'),
file_id: f.string().default('').role('file_id'),
// Optional server-side transcode (#165): SILK/AMR → the requested
// container, returned as `data.base64`. Absent ⇒ behaviour unchanged.
out_format: f.enum('mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac').optional(),
},
run: async (p, ctx) => {
const file = p.file || p.file_id;
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
const info = await ctx.getRecordInfo(file);
if (info) return okResponse(info);
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
if (!info) return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
if (!p.out_format) return okResponse(info);
// Transcode from the record's download URL (fall back to file field).
const source = String(info.url || info.file || '');
if (!source) return failedResponse(RETCODE.ACTION_FAILED, 'record has no downloadable source');
try {
// Keep the original record info (file_size stays the source size, like
// NapCat) and just attach the transcoded payload.
const { base64 } = await ctx.bridge.apis.extras.convertRecord(source, p.out_format);
return okResponse({ ...info, out_format: p.out_format, base64 });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `语音转码失败:${e instanceof Error ? e.message : String(e)}`);
}
},
}),
@@ -574,7 +588,7 @@ export const actions = [
required: ['text'],
},
params: {
message_id: f.string().default(''),
message_id: f.string().default('').role('message_id'),
},
// `raw` so message_id works whether the client sends a number or a string.
run: async (_p, ctx, raw) => {
@@ -684,7 +698,7 @@ export const actions = [
name: 'set_friend_remark',
summary: '设置好友备注',
params: {
user_id: f.uint(),
user_id: f.userId(),
remark: f.string(),
},
run: async (p, ctx) => {
@@ -697,7 +711,7 @@ export const actions = [
name: 'set_group_remark',
summary: '设置群备注',
params: {
group_id: f.uint(),
group_id: f.groupId(),
remark: f.string(),
},
run: async (p, ctx) => {
@@ -822,7 +836,7 @@ export const actions = [
name: 'set_diy_online_status',
summary: '设置自定义在线状态',
params: {
face_id: f.uint(),
face_id: f.faceId(),
// 原实现用 `asNumber(face_type) || 1`,present 0 会被当作缺省 1。
face_type: f.int({ min: 0 }).default(1),
wording: f.string().default(''),
@@ -979,7 +993,7 @@ export const actions = [
summary: '转发单条消息给好友',
params: {
message_id: f.messageId(),
user_id: f.uint(),
user_id: f.userId(),
},
run: async (p, ctx) => {
try {
@@ -996,7 +1010,7 @@ export const actions = [
summary: '转发单条消息到群',
params: {
message_id: f.messageId(),
group_id: f.uint(),
group_id: f.groupId(),
},
run: async (p, ctx) => {
try {
@@ -1044,7 +1058,7 @@ export const actions = [
},
params: {
// 原实现 user_id 经 asNumber,无校验(0 也透传)。
user_id: f.int({ min: 0 }).default(0),
user_id: f.int({ min: 0 }).default(0).role('user_id'),
start: f.int({ min: 0 }).default(0),
count: f.int({ min: 0 }).default(10),
},
@@ -1367,8 +1381,8 @@ export const actions = [
required: ['arkMsg'],
},
params: {
user_id: f.uint().optional(),
group_id: f.uint().optional(),
user_id: f.userId().optional(),
group_id: f.groupId().optional(),
phone_number: f.string().default(''),
},
run: async (p, ctx) => {
@@ -1398,8 +1412,8 @@ export const actions = [
required: ['arkMsg'],
},
params: {
user_id: f.uint().optional(),
group_id: f.uint().optional(),
user_id: f.userId().optional(),
group_id: f.groupId().optional(),
phone_number: f.string().default(''),
},
run: async (p, ctx) => {
@@ -1427,7 +1441,7 @@ export const actions = [
readOnly: true,
returns: '服务端生成的群推荐 Ark 卡片 JSON 字符串。',
returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' },
params: { group_id: f.uint() },
params: { group_id: f.groupId() },
run: async (p, ctx) => {
try {
return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id));
@@ -1442,7 +1456,7 @@ export const actions = [
readOnly: true,
returns: '服务端生成的群推荐 Ark 卡片 JSON 字符串。',
returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' },
params: { group_id: f.uint() },
params: { group_id: f.groupId() },
run: async (p, ctx) => {
try {
return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id));
@@ -1565,7 +1579,7 @@ export const actions = [
defineAction({
name: 'set_qq_avatar',
summary: '设置 QQ 头像',
params: { file: f.string({ allowEmpty: false }) },
params: { file: f.image() },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setAvatar(p.file);
@@ -1580,7 +1594,7 @@ export const actions = [
name: 'set_input_status',
summary: '设置输入状态',
params: {
user_id: f.uint(),
user_id: f.userId(),
// event_type 可能为 0(取消输入状态);缺省也按 0 处理(与旧 asNumber 行为一致)。
event_type: f.int().default(0),
},
@@ -1598,7 +1612,7 @@ export const actions = [
name: 'get_group_info_ex',
summary: '获取群信息(扩展)',
readOnly: true,
params: { group_id: f.uint() },
params: { group_id: f.groupId() },
run: async (p, ctx) => {
if (ctx.getGroupInfo) {
return okResponse(await ctx.getGroupInfo(p.group_id));
@@ -1611,7 +1625,7 @@ export const actions = [
name: 'get_group_detail_info',
summary: '获取群详细信息',
readOnly: true,
params: { group_id: f.uint() },
params: { group_id: f.groupId() },
run: async (p, ctx) => {
if (ctx.getGroupInfo) {
return okResponse(await ctx.getGroupInfo(p.group_id));
@@ -1644,8 +1658,8 @@ export const actions = [
summary: '获取文件信息(仅图片/语音缓存;群文件请用 get_group_file_url)',
readOnly: true,
params: {
file_id: f.string().default(''),
file: f.string().default(''),
file_id: f.string().default('').role('file_id'),
file: f.string().default('').role('file'),
},
run: async (p, ctx) => {
const fileId = p.file || p.file_id;
@@ -1712,7 +1726,7 @@ export const actions = [
},
required: ['status', 'ext_status'],
},
params: { user_id: f.uint() },
params: { user_id: f.userId() },
run: async (p, ctx) => {
const status = await ctx.bridge.apis.extras.getStrangerStatus(p.user_id);
if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status');
@@ -1934,7 +1948,7 @@ export const actions = [
},
required: ['texts', 'language'],
},
params: { image: f.string({ allowEmpty: false }) },
params: { image: f.image() },
run: async (p, ctx) => {
// A passed-in http(s) URL is used verbatim (NOT re-signed) — if it is a
// stale CDN URL with an expired rkey the server fetch fails and surfaces
@@ -2022,7 +2036,7 @@ export const actions = [
name: 'send_private_forward_msg',
summary: '发送私聊合并转发',
returns: '{ message_id, res_id, forward_id }',
params: { user_id: f.uint(), messages: f.message().optional(), message: f.message().optional() },
params: { user_id: f.userId(), messages: f.message().optional(), message: f.message().optional() },
run: async (p, ctx, raw) => {
const messages = p.messages ?? p.message;
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
@@ -2407,8 +2421,8 @@ export const actions = [
returns: '{ message_id }',
params: {
fileset_id: f.string({ allowEmpty: false }),
user_id: f.uint().optional(),
group_id: f.uint().optional(),
user_id: f.userId().optional(),
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
if (!p.user_id && !p.group_id) {
+2 -2
View File
@@ -46,7 +46,7 @@ export const actions = [
},
required: ['user_id', 'nickname', 'sex', 'age'],
},
params: { user_id: f.uint().describe('QQ 号') },
params: { user_id: f.userId().describe('QQ 号') },
run: async (p, ctx) => {
const userId = p.user_id;
if (ctx.getStrangerInfo) {
@@ -60,7 +60,7 @@ export const actions = [
defineAction({
name: 'delete_friend',
summary: '删除好友',
params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) },
params: { user_id: f.userId().describe('QQ 号'), block: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
return okResponse();
+3 -3
View File
@@ -16,7 +16,7 @@ export const actions = [
groupAction({
name: 'set_group_kick_members',
summary: '批量踢出群成员',
params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) },
params: { user_id: f.array(f.memberId()).nonEmpty(), reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
@@ -26,7 +26,7 @@ export const actions = [
groupUserAction({
name: 'set_group_ban',
summary: '禁言群成员(duration=0 解除)',
params: { duration: f.int({ min: 0 }).default(1800) },
params: { duration: f.duration().default(1800) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
return okResponse();
@@ -118,7 +118,7 @@ export const actions = [
groupAction({
name: 'set_group_portrait',
summary: '设置群头像',
params: { file: f.string({ allowEmpty: false }) },
params: { file: f.image() },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
+1 -1
View File
@@ -91,7 +91,7 @@ export const actions = [
params: {
album_id: f.string({ allowEmpty: false }),
album_name: f.string({ allowEmpty: false }),
file: f.string({ allowEmpty: false }),
file: f.image(),
},
run: async (p, ctx) => {
try {
+9 -9
View File
@@ -26,7 +26,7 @@ export const actions = [
// non-empty wins, else '/'. Both default '' so the `||` chain matches the
// legacy `asString(folder) || asString(folder_id) || '/'`.
params: {
file: f.string({ allowEmpty: false }),
file: f.file(),
name: f.string().default(''),
folder: f.string().default(''),
folder_id: f.string().default(''),
@@ -44,8 +44,8 @@ export const actions = [
summary: '上传私聊文件',
returns: '{ file_id: string }',
params: {
user_id: f.uint(),
file: f.string({ allowEmpty: false }),
user_id: f.userId(),
file: f.file(),
name: f.string().default(''),
upload_file: f.bool().default(true),
},
@@ -67,7 +67,7 @@ export const actions = [
},
// 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() },
params: { file_id: f.fileId(), busid: f.raw() },
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, busidOr102(p.busid)) });
},
@@ -183,7 +183,7 @@ export const actions = [
groupAction({
name: 'delete_group_file',
summary: '删除群文件',
params: { file_id: f.string({ allowEmpty: false }) },
params: { file_id: f.fileId() },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id);
return okResponse();
@@ -194,7 +194,7 @@ export const actions = [
name: 'move_group_file',
summary: '移动群文件',
params: {
file_id: f.string({ allowEmpty: false }),
file_id: f.fileId(),
parent_directory: f.string({ allowEmpty: false }),
target_directory: f.string({ allowEmpty: false }),
},
@@ -210,7 +210,7 @@ export const actions = [
name: 'rename_group_file',
summary: '重命名群文件',
params: {
file_id: f.string({ allowEmpty: false }),
file_id: f.fileId(),
current_parent_directory: f.string().default('/'),
new_name: f.string({ allowEmpty: false }),
},
@@ -276,8 +276,8 @@ export const actions = [
// clients that only persist file_id, both user_id and file_hash are now
// optional; file_hash falls through empty when absent. See issue #147.
params: {
user_id: f.uint().optional(),
file_id: f.string({ allowEmpty: false }),
user_id: f.userId().optional(),
file_id: f.fileId(),
file_hash: f.string().default(''),
},
run: async (p, ctx) => {
+3 -3
View File
@@ -47,8 +47,8 @@ export const actions = [
params: {
message: f.message(),
message_type: f.string().optional(),
group_id: f.uint().optional(),
user_id: f.uint().optional(),
group_id: f.groupId().optional(),
user_id: f.userId().optional(),
auto_escape: f.bool().default(false),
},
run: async (p, ctx) => {
@@ -67,7 +67,7 @@ export const actions = [
name: 'send_private_msg',
summary: '发送私聊消息',
returns: '{ message_id: number }',
params: { user_id: f.uint(), message: f.message(), auto_escape: f.bool().default(false) },
params: { user_id: f.userId(), message: f.message(), auto_escape: f.bool().default(false) },
run: async (p, ctx) => {
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
+41 -9
View File
@@ -3,6 +3,24 @@ import type { ApiActionContext, ApiHandler } from '../api-handler';
import type { JsonValue } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
async function uploadQzoneImages(
ctx: ApiActionContext,
images: string[],
select: (upload: { richval: string; url: string }) => string,
): Promise<string> {
const parts: string[] = [];
for (let i = 0; i < images.length; i++) {
try {
const upload = await ctx.bridge.apis.qzone.uploadImageFromSource(images[i]);
parts.push(select(upload));
} catch (error) {
const message = error instanceof Error ? error.message : 'unknown error';
throw new Error(`第 ${i + 1} 张图片上传失败: ${message}`);
}
}
return parts.join('\t');
}
export const actions = [
// get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。
// 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。
@@ -36,7 +54,7 @@ export const actions = [
},
summary: '获取 QQ 空间说说列表(默认机器人自己的空间)',
params: {
target_uin: f.uint().describe('目标 QQ 号,省略则取机器人自己').optional(),
target_uin: f.userId().describe('目标 QQ 号,省略则取机器人自己').optional(),
pos: f.int({ min: 0 }).describe('起始偏移').default(0),
num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20),
},
@@ -96,17 +114,24 @@ export const actions = [
},
}),
// send_qzone_msg — 发表一条纯文字说说。写操作,发到机器人自己的空间。
// send_qzone_msg — 发表说说(纯文字或带图)。写操作,发到机器人自己的空间。
// 传入 images 数组,自动上传并发布。
// 返回新说说的 tid(供后续 delete/comment/like 使用)。
// 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。
defineAction({
name: 'send_qzone_msg',
summary: '发表一条纯文字说说(QQ 空间)',
summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)',
params: {
content: f.string({ allowEmpty: false }).describe('说说正文'),
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
},
run: async (p, ctx) => {
try {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval);
const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval);
return okResponse(res as unknown as JsonValue);
}
const res = await ctx.bridge.apis.qzone.publish(p.content);
return okResponse(res as unknown as JsonValue);
} catch (error) {
@@ -142,8 +167,8 @@ export const actions = [
summary: '给一条说说点赞(QQ 空间)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'),
},
run: async (p, ctx) => {
try {
@@ -163,8 +188,8 @@ export const actions = [
summary: '取消对一条说说的点赞(QQ 空间;取消赞端点待真机核实)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'),
},
run: async (p, ctx) => {
try {
@@ -178,17 +203,24 @@ export const actions = [
}),
// comment_qzone — 评论一条说说。target_uin=说说所属 QQ 号(省略=机器人自己空间)。
// 传入 images 数组,自动上传获取直链(多图用 tab 拼接)。
// 写操作;高频评论会被 Qzone 风控,调用方需限流。
defineAction({
name: 'comment_qzone',
summary: '评论一条说说(QQ 空间)',
summary: '评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
content: f.string({ allowEmpty: false }).describe('评论内容'),
target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
},
run: async (p, ctx) => {
try {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url);
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval);
return okResponse(res as unknown as JsonValue);
}
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin);
return okResponse(res as unknown as JsonValue);
} catch (error) {
@@ -0,0 +1,378 @@
// Stream API download actions (#163) — NapCat-compatible server-push streaming.
//
// download_file_stream / _image_stream / _record_stream answer one request with
// many frames: a `file_info` header, then N `file_chunk` frames (base64), then a
// terminal `file_complete`. The bytes come from one of three sources, resolved
// from the `file` arg:
// • a local file UNDER the stream temp root (e.g. something a client just
// pushed via upload_file_stream) — streamed straight off disk;
// • an http(s) URL — fetched and re-streamed;
// • a cached image/voice id from a received message — resolved to its QQ CDN
// URL, then fetched.
// test_download_stream pushes 10 canned frames so a client can verify the
// streaming transport without touching QQ.
//
// Hardening beyond the NapCat original (which streams ANY local path and
// fetches ANY URL): local reads are fenced inside the stream temp root (no
// arbitrary-file read via a leaked token), and URL fetches are SSRF-guarded
// (no private/loopback/link-local targets) + size-capped.
import fs from 'fs';
import path from 'path';
import net from 'net';
import dns from 'dns/promises';
import { resolveLocalFilePath } from '@snowluma/protocol/highway/utils';
import { defineStreamAction, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types';
import { type StreamSink, StreamStatus } from '../streaming';
import { STREAM_ROOT } from './stream-file';
const DEFAULT_CHUNK_BYTES = 64 * 1024;
const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size
const MAX_DOWNLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB total
const FETCH_CONNECT_TIMEOUT_MS = 30_000; // TTFB only — cleared once headers arrive (not the whole transfer)
const IDLE_TIMEOUT_MS = 60_000; // abort if no chunk arrives for this long (anti-stall)
const MAX_REDIRECTS = 5;
const DOWNLOAD_USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
class DownloadError extends Error {}
// ─────────────────────────── source resolution ───────────────────────────
function isWithinStreamRoot(p: string): boolean {
// Resolve the root through any symlinks too (e.g. macOS /tmp → /private/tmp),
// so a realpath'd target compares against a realpath'd root — otherwise a
// legitimate file reads as "outside" purely from the tmpdir symlink.
let root = path.resolve(STREAM_ROOT);
try { root = fs.realpathSync(STREAM_ROOT); } catch { /* root may not exist yet */ }
const rel = path.relative(root, path.resolve(p));
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
}
function isPrivateV4(o: number[]): boolean {
return (
o[0] === 0 || o[0] === 127 || o[0] === 10 ||
(o[0] === 192 && o[1] === 168) ||
(o[0] === 172 && o[1] >= 16 && o[1] <= 31) ||
(o[0] === 169 && o[1] === 254) || // link-local
(o[0] === 100 && o[1] >= 64 && o[1] <= 127) // CGNAT
);
}
/** Parse an IPv6 string (any form, incl. `::` compression and embedded IPv4)
* to its 16 bytes. `new URL().hostname` normalises v4-mapped addresses to hex
* (`::ffff:7f00:1`), so string matching is unreliable — we work on bytes. */
function ipv6ToBytes(input: string): Uint8Array | null {
let s = input.replace(/^\[|\]$/g, '');
if (net.isIP(s) !== 6) return null;
const v4m = /:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s); // embedded IPv4 tail
if (v4m) {
const o = v4m[1].split('.').map(Number);
if (o.some((n) => n > 255)) return null;
s = s.slice(0, v4m.index) + ':' + `${((o[0] << 8) | o[1]).toString(16)}:${((o[2] << 8) | o[3]).toString(16)}`;
}
const halves = s.split('::');
if (halves.length > 2) return null;
const head = halves[0] ? halves[0].split(':') : [];
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
let groups: string[];
if (halves.length === 2) {
const missing = 8 - head.length - tail.length;
if (missing < 0) return null;
groups = [...head, ...new Array(missing).fill('0'), ...tail];
} else {
groups = head;
}
if (groups.length !== 8) return null;
const bytes = new Uint8Array(16);
for (let i = 0; i < 8; i++) {
const g = parseInt(groups[i] || '0', 16);
if (Number.isNaN(g) || g < 0 || g > 0xffff) return null;
bytes[i * 2] = g >> 8;
bytes[i * 2 + 1] = g & 0xff;
}
return bytes;
}
function isPrivateIp(ip: string): boolean {
const host = ip.replace(/^\[|\]$/g, '');
const fam = net.isIP(host);
if (fam === 4) return isPrivateV4(host.split('.').map(Number));
if (fam === 6) {
const b = ipv6ToBytes(host);
if (!b) return true; // unparseable IPv6 → treat as unsafe
if (b.every((x) => x === 0)) return true; // ::
if (b.slice(0, 15).every((x) => x === 0) && b[15] === 1) return true; // ::1
if ((b[0] & 0xfe) === 0xfc) return true; // fc00::/7 unique-local
if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) return true; // fe80::/10 link-local
// v4-mapped ::ffff:a.b.c.d / v4-compatible ::a.b.c.d
if (b.slice(0, 10).every((x) => x === 0) && ((b[10] === 0xff && b[11] === 0xff) || (b[10] === 0 && b[11] === 0))) {
return isPrivateV4([b[12], b[13], b[14], b[15]]);
}
// NAT64 64:ff9b::/96
if (b[0] === 0x00 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b && b.slice(4, 12).every((x) => x === 0)) {
return isPrivateV4([b[12], b[13], b[14], b[15]]);
}
return false;
}
return false;
}
/** Parse + SSRF-guard a URL: http(s) only, and neither the literal host nor any
* DNS-resolved address may be private/loopback/link-local. Not bulletproof
* against DNS rebinding, but blocks the obvious metadata-endpoint / internal
* service reach. */
async function assertSafeUrl(raw: string): Promise<URL> {
let u: URL;
try { u = new URL(raw); } catch { throw new DownloadError('invalid URL'); }
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new DownloadError('only http(s) URLs are allowed');
const host = u.hostname.replace(/^\[|\]$/g, '');
if (net.isIP(host)) {
if (isPrivateIp(host)) throw new DownloadError('refusing to fetch a private/loopback address');
return u;
}
let addrs: Array<{ address: string }>;
try { addrs = await dns.lookup(host, { all: true }); } catch { throw new DownloadError(`cannot resolve host: ${host}`); }
for (const a of addrs) {
if (isPrivateIp(a.address)) throw new DownloadError('refusing to fetch a host that resolves to a private address');
}
return u;
}
interface DownloadSource {
name: string;
size: number; // 0 when unknown
iterable: AsyncIterable<Uint8Array>;
/** Force the underlying source closed (idle-timeout watchdog / abort). */
abort?: () => void;
}
const asStr = (v: JsonValue | undefined): string => (typeof v === 'string' ? v : '');
const asNum = (v: JsonValue | undefined): number => {
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : 0;
};
/** Follow redirects MANUALLY, SSRF-guarding every hop. Default fetch follows
* redirects automatically and would NOT re-check the target, so a public URL
* could 302 to a private/metadata address — re-validating each Location closes
* that. Each hop gets a TTFB-only timeout (cleared once headers arrive, so a
* legitimate slow/large body isn't cut mid-transfer); the final hop's
* AbortController is returned so the caller's idle watchdog can kill a stalled
* body. (DNS rebinding between our check and undici's own connect remains a
* known residual — it needs connect-time peer-IP validation to fully close.) */
async function fetchGuarded(rawUrl: string): Promise<{ resp: Response; abort: () => void }> {
let current = rawUrl;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
const u = await assertSafeUrl(current);
const ac = new AbortController();
const t = setTimeout(() => ac.abort(), FETCH_CONNECT_TIMEOUT_MS);
let resp: Response;
try {
resp = await fetch(u, { headers: { 'User-Agent': DOWNLOAD_USER_AGENT }, redirect: 'manual', signal: ac.signal });
} finally {
clearTimeout(t);
}
if (resp.status >= 300 && resp.status < 400) {
const loc = resp.headers.get('location');
await resp.body?.cancel().catch(() => { /* ignore */ });
if (!loc) throw new DownloadError(`download failed: ${resp.status} redirect without Location`);
current = new URL(loc, u).toString();
continue;
}
return { resp, abort: () => ac.abort() };
}
throw new DownloadError('download failed: too many redirects');
}
async function openUrl(rawUrl: string, name: string, knownSize: number): Promise<DownloadSource> {
const { resp, abort } = await fetchGuarded(rawUrl);
if (!resp.ok) {
await resp.body?.cancel().catch(() => { /* ignore */ });
throw new DownloadError(`download failed: HTTP ${resp.status}`);
}
const declared = Number(resp.headers.get('content-length') ?? '');
const size = (Number.isFinite(declared) && declared > 0 ? declared : 0) || knownSize;
if (!resp.body) throw new DownloadError('download failed: empty response body');
return { name: name || urlBasename(rawUrl), size, iterable: resp.body as unknown as AsyncIterable<Uint8Array>, abort };
}
function urlBasename(u: string): string {
try {
const name = path.basename(new URL(u).pathname);
return name && name !== '/' ? decodeURIComponent(name) : 'download.bin';
} catch { return 'download.bin'; }
}
async function resolveDownload(
target: string,
ctx: ApiActionContext,
prefer: 'auto' | 'image' | 'record',
chunkSize: number,
): Promise<DownloadSource> {
// 1. local file — but ONLY a real existing file, fenced inside the stream
// temp root. `resolveLocalFilePath` returns the input verbatim for any
// non-URL string (including cached-media ids), so we must NOT treat a
// non-existent "path" as local — that would shadow the cached-media branch
// below (the whole point of the *_image/_record_stream actions).
const local = resolveLocalFilePath(target);
if (local) {
let st: fs.Stats | null = null;
try { st = fs.statSync(local); } catch { st = null; }
if (st?.isFile()) {
// Fence against the *real* path so a symlink inside the root can't point
// out (lexical resolve alone would follow it).
let real = local;
try { real = fs.realpathSync(local); } catch { /* keep lexical */ }
if (!isWithinStreamRoot(real)) throw new DownloadError('local downloads are restricted to the stream temp directory');
const rs = fs.createReadStream(real, { highWaterMark: chunkSize });
return { name: path.basename(real), size: st.size, iterable: rs, abort: () => rs.destroy() };
}
}
// 2. explicit http(s) URL.
if (/^https?:\/\//i.test(target)) return openUrl(target, '', 0);
// 3. cached image / voice id → QQ CDN URL.
let info: JsonObject | null = null;
if (prefer !== 'record') info = await ctx.getImageInfo(target);
if (!info && prefer !== 'image') info = await ctx.getRecordInfo(target);
if (info) {
const url = asStr(info.url) || asStr(info.file);
if (/^https?:\/\//i.test(url)) return openUrl(url, asStr(info.file_name), asNum(info.file_size));
}
throw new DownloadError('file not found (expected a stream-dir path, an http(s) URL, or a cached image/voice id)');
}
// ─────────────────────────── push engine ───────────────────────────
async function streamChunks(
sink: StreamSink,
iterable: AsyncIterable<Uint8Array>,
totalSize: number,
dataType: string,
abort?: () => void,
): Promise<{ totalChunks: number; totalBytes: number }> {
let index = 0;
let bytesRead = 0;
// Anti-stall: if no chunk arrives for IDLE_TIMEOUT_MS, force the source closed
// so a server that sends headers then hangs can't pin a socket forever (the
// sink's own liveness check only fires when we actually send a frame).
let idle: NodeJS.Timeout | null = null;
const armIdle = (): void => {
if (idle) clearTimeout(idle);
idle = setTimeout(() => { abort?.(); }, IDLE_TIMEOUT_MS);
if (idle.unref) idle.unref();
};
armIdle();
try {
for await (const part of iterable) {
armIdle();
const buf = Buffer.isBuffer(part) ? part : Buffer.from(part);
bytesRead += buf.length;
if (bytesRead > MAX_DOWNLOAD_BYTES) throw new DownloadError(`download exceeds size limit (${MAX_DOWNLOAD_BYTES} bytes)`);
const b64 = buf.toString('base64');
await sink.send({
type: StreamStatus.Stream,
data_type: dataType,
index,
data: b64,
size: buf.length,
progress: totalSize > 0 ? Math.min(100, Math.round((bytesRead / totalSize) * 100)) : 0,
base64_size: b64.length,
});
index++;
}
} finally {
if (idle) clearTimeout(idle);
}
return { totalChunks: index, totalBytes: bytesRead };
}
async function runDownload(
target: string,
chunkSizeReq: number | undefined,
ctx: ApiActionContext,
sink: StreamSink,
prefer: 'auto' | 'image' | 'record',
): Promise<ApiResponse> {
if (!target) throw new DownloadError('file is required');
let chunkSize = chunkSizeReq && chunkSizeReq > 0 ? chunkSizeReq : DEFAULT_CHUNK_BYTES;
if (chunkSize > MAX_CHUNK_REQUEST_BYTES) chunkSize = MAX_CHUNK_REQUEST_BYTES;
const src = await resolveDownload(target, ctx, prefer, chunkSize);
await sink.send({
type: StreamStatus.Stream,
data_type: 'file_info',
file_name: src.name,
file_size: src.size,
chunk_size: chunkSize,
});
const { totalChunks, totalBytes } = await streamChunks(sink, src.iterable, src.size, 'file_chunk', src.abort);
return okResponse({
type: StreamStatus.Response,
data_type: 'file_complete',
file_name: src.name,
total_chunks: totalChunks,
total_bytes: totalBytes,
message: 'Download completed',
});
}
// ─────────────────────────── action definitions ───────────────────────────
const downloadParams = {
file: f.string().optional().describe('文件路径(限 stream 临时目录)/ http(s) URL').role('file'),
file_id: f.string().optional().describe('文件 ID(缓存的图片/语音 id)').role('file_id'),
chunk_size: f.int({ min: 1 }).optional().describe('分块大小(字节,默认 64KB)'),
};
const downloadFileStream = defineStreamAction({
name: 'download_file_stream',
summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'),
});
const downloadFileImageStream = defineStreamAction({
name: 'download_file_image_stream',
summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'),
});
const downloadFileRecordStream = defineStreamAction({
name: 'download_file_record_stream',
summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'),
});
const testDownloadStream = defineStreamAction({
name: 'test_download_stream',
summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)',
returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)',
params: { error: f.bool().default(false).describe('是否触发测试错误') },
run: async (p, _ctx, _raw, sink) => {
for (let i = 0; i < 10; i++) {
await sink.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: 'data_chunk' });
}
if (p.error) throw new DownloadError('This is a test error');
return okResponse({ type: StreamStatus.Response, data_type: 'data_complete', data: 'Stream transmission complete' });
},
});
export const actions = [downloadFileStream, downloadFileImageStream, downloadFileRecordStream, testDownloadStream];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
for (const a of actions) a.register(h, ctx);
}
// Exposed for tests.
export const __test = { resolveDownload, isWithinStreamRoot, isPrivateIp, assertSafeUrl, streamChunks, runDownload };
+369
View File
@@ -0,0 +1,369 @@
// Stream API file actions (#163) — NapCat-compatible chunked file transfer.
//
// upload_file_stream: a client (possibly on another machine) pushes a file to
// the bot in base64 chunks across repeated calls keyed by `stream_id`; the bot
// reassembles them into a local temp file and returns its path, which the
// client then feeds to a normal send action. This sidesteps the HTTP 2 MB body
// cap and the "client and bot share a filesystem" assumption of plain file://
// sends. Reassembly streams chunk-by-chunk to disk (no whole-file
// Buffer.concat) so an arbitrarily large upload won't OOM the bot.
//
// clean_stream_temp_file: wipe the stream temp dirs (upload + download), scoped
// so it never touches unrelated temp files.
//
// Hardening over the NapCat original (which has all of these holes): stream_id
// is allowlist-validated + every derived path is fenced inside the upload dir
// (no path traversal); total_chunks/chunk/stream/byte counts are all bounded
// (no single-request OOM or disk/fd exhaustion); chunk indices are claimed
// synchronously (no double-count race); state is namespaced per account.
import os from 'os';
import path from 'path';
import fs from 'fs';
import { createHash } from 'crypto';
import { createLogger } from '@snowluma/common/logger';
import { defineAction, defineStreamAction, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { okResponse, type ApiResponse } from '../types';
import { StreamStatus } from '../streaming';
const log = createLogger('OneBot.Stream');
export const STREAM_ROOT = path.join(os.tmpdir(), 'snowluma-stream');
export const STREAM_UPLOAD_DIR = path.join(STREAM_ROOT, 'upload');
export const STREAM_DOWNLOAD_DIR = path.join(STREAM_ROOT, 'download');
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; // idle stream reaped after 10 min
const DEFAULT_RETENTION_MS = 5 * 60 * 1000; // reassembled file auto-deleted after 5 min
// Resource caps (DoS guards — the whole point of the disk-streaming design is
// blown if a single request can still OOM, and an unbounded server can be
// flooded with streams/chunks/bytes).
const MAX_CONCURRENT_STREAMS = 64;
const MAX_CHUNKS = 200_000; // also bounds the completion scan
const MAX_CHUNK_BYTES = 32 * 1024 * 1024; // one decoded chunk
const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB cumulative per stream
// stream_id / account key allowlist: filename-safe, no separators, no dots
// (so no `.`/`..` traversal token can ever reach a path segment).
const SAFE_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
class StreamError extends Error {}
function validateStreamId(id: string): void {
if (!SAFE_ID_RE.test(id)) throw new StreamError('invalid stream_id (allowed: 1-128 chars of A-Z a-z 0-9 _ -)');
}
/** Account namespace for the in-memory map + on-disk dirs. Empty (tests / no
* login) → flat, un-namespaced. Sanitised so it can't widen the path either. */
function accountKey(ctx?: ApiActionContext): string {
let raw = '';
try { raw = String(ctx?.getLoginInfo?.().userId ?? ''); } catch { raw = ''; }
return raw.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64);
}
/** Belt-and-braces: assert a derived path stays inside the upload dir even if
* the allowlist above is ever weakened. */
function assertWithin(root: string, target: string): void {
const rel = path.relative(root, target);
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
throw new StreamError('resolved stream path escapes the upload directory');
}
}
// ─────────────────────────── upload state ───────────────────────────
interface UploadState {
/** Client-facing stream_id (echoed in frames). */
id: string;
/** Internal map key — `<account>:<id>` or just `<id>` when un-namespaced. */
key: string;
filename: string;
totalChunks: number;
/** Indices CLAIMED (sync, before the write await) — drives dedup + byte
* accounting so two concurrent calls for one index can't double-count. */
claimed: Set<number>;
/** Indices actually FLUSHED to disk (added after the write resolves) — drives
* completion + the reported count, so completion can't fire while a chunk
* file is still being written (which would read a truncated part). Neither
* set is pre-allocated to total_chunks (that would defeat the no-OOM goal). */
written: Set<number>;
bytesWritten: number;
fileSize?: number;
expectedSha256?: string;
tempDir: string;
finalPath: string;
fileRetention: number;
timeoutId: NodeJS.Timeout;
}
/** Process-wide. Key is account-namespaced so two accounts (same process) can't
* collide on a shared/non-UUID stream_id. */
const uploads = new Map<string, UploadState>();
function reapTimer(key: string): NodeJS.Timeout {
const t = setTimeout(() => { cleanupUpload(key, true); }, UPLOAD_TIMEOUT_MS);
if (typeof t.unref === 'function') t.unref(); // don't pin the event loop on a stalled upload
return t;
}
function cleanupUpload(key: string, deleteFinal: boolean): void {
const state = uploads.get(key);
if (!state) return;
clearTimeout(state.timeoutId);
try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch { /* best effort */ }
if (deleteFinal) {
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
}
uploads.delete(key);
}
function safeFilename(name: string | undefined, id: string): string {
const base = (name ?? '')
.replace(/[/\\]/g, '_') // no directory separators
.replace(/\.\.+/g, '_') // no `..` traversal tokens
.replace(/^\.+/, '') // no leading dots
.trim();
return base || `upload_${id}`;
}
function createUpload(p: UploadParams, account: string): UploadState {
if (!p.total_chunks || p.total_chunks <= 0) throw new StreamError('total_chunks required for new stream');
if (p.total_chunks > MAX_CHUNKS) throw new StreamError(`total_chunks exceeds limit (${MAX_CHUNKS})`);
if (p.file_size !== undefined && p.file_size > MAX_UPLOAD_BYTES) throw new StreamError(`file_size exceeds limit (${MAX_UPLOAD_BYTES} bytes)`);
if (uploads.size >= MAX_CONCURRENT_STREAMS) throw new StreamError(`too many concurrent upload streams (${MAX_CONCURRENT_STREAMS})`);
const filename = safeFilename(p.filename, p.stream_id);
const dirRoot = account ? path.join(STREAM_UPLOAD_DIR, account) : STREAM_UPLOAD_DIR;
const tempDir = path.join(dirRoot, p.stream_id);
const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`);
assertWithin(STREAM_UPLOAD_DIR, tempDir);
assertWithin(STREAM_UPLOAD_DIR, finalPath);
fs.mkdirSync(tempDir, { recursive: true });
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
const state: UploadState = {
id: p.stream_id,
key,
filename,
totalChunks: p.total_chunks,
claimed: new Set(),
written: new Set(),
bytesWritten: 0,
fileSize: p.file_size,
expectedSha256: p.expected_sha256,
tempDir,
finalPath,
fileRetention: p.file_retention,
timeoutId: reapTimer(key),
};
uploads.set(key, state);
return state;
}
function statusFrame(state: UploadState, status: string): ApiResponse {
return okResponse({
type: StreamStatus.Stream,
stream_id: state.id,
status,
received_chunks: state.written.size,
total_chunks: state.totalChunks,
});
}
function writeChunkToStream(stream: fs.WriteStream, buf: Buffer): Promise<void> {
return new Promise((resolve, reject) => {
stream.write(buf, (err) => (err ? reject(err) : resolve()));
});
}
async function completeUpload(state: UploadState): Promise<ApiResponse> {
if (state.written.size !== state.totalChunks) {
const missing: number[] = [];
for (let i = 0; i < state.totalChunks && missing.length < 16; i++) {
if (!state.written.has(i)) missing.push(i);
}
const more = state.totalChunks - state.written.size > missing.length ? '…' : '';
throw new StreamError(`incomplete stream: missing ${state.totalChunks - state.written.size} chunk(s) [${missing.join(',')}${more}]`);
}
// Stream each chunk file into the final file in order, hashing as we go — one
// chunk in memory at a time, never the whole payload.
const hash = createHash('sha256');
const out = fs.createWriteStream(state.finalPath);
try {
for (let i = 0; i < state.totalChunks; i++) {
const buf = await fs.promises.readFile(path.join(state.tempDir, `${i}.chunk`));
hash.update(buf);
await writeChunkToStream(out, buf);
}
await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve())));
} catch (err) {
out.destroy();
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
throw err;
}
const sha256 = hash.digest('hex');
if (state.expectedSha256 && sha256 !== state.expectedSha256) {
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
throw new StreamError(`sha256 mismatch (expected ${state.expectedSha256}, got ${sha256})`);
}
const finalPath = state.finalPath;
const fileSize = fs.statSync(finalPath).size;
const received = state.written.size;
const total = state.totalChunks;
const retention = state.fileRetention;
// Drop chunk parts + in-memory state but KEEP the reassembled file.
cleanupUpload(state.key, false);
if (retention > 0) {
const t = setTimeout(() => {
fs.rm(finalPath, { force: true }, (err) => {
if (err) log.warn('failed to delete retained stream file %s: %s', finalPath, err.message);
});
}, retention);
if (typeof t.unref === 'function') t.unref();
}
return okResponse({
type: StreamStatus.Response,
stream_id: state.id,
status: 'file_complete',
received_chunks: received,
total_chunks: total,
file_path: finalPath,
file_size: fileSize,
sha256,
});
}
async function handleUpload(p: UploadParams, account = ''): Promise<ApiResponse> {
validateStreamId(p.stream_id);
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
if (p.reset) {
cleanupUpload(key, true);
// NapCat surfaces reset as an error frame; mirror it for client parity.
throw new StreamError('Stream reset completed');
}
if (p.verify_only) {
const state = uploads.get(key);
if (!state) throw new StreamError('stream not found');
return statusFrame(state, 'file_created');
}
const state = uploads.get(key) ?? createUpload(p, account);
// Metadata may arrive on the creating call or any later one (e.g. the client
// only knows the whole-file sha256 when it sends `is_complete`).
if (p.expected_sha256 !== undefined) state.expectedSha256 = p.expected_sha256;
if (p.file_size !== undefined) state.fileSize = p.file_size;
if (p.chunk_data !== undefined && p.chunk_index !== undefined) {
const index = p.chunk_index;
if (index < 0 || index >= state.totalChunks) throw new StreamError(`invalid chunk index: ${index}`);
if (state.claimed.has(index)) return statusFrame(state, 'chunk_received'); // duplicate / in-flight — idempotent
const buf = Buffer.from(p.chunk_data, 'base64');
if (buf.length > MAX_CHUNK_BYTES) throw new StreamError(`chunk exceeds size limit (${MAX_CHUNK_BYTES} bytes)`);
if (state.bytesWritten + buf.length > MAX_UPLOAD_BYTES) throw new StreamError(`stream exceeds total size limit (${MAX_UPLOAD_BYTES} bytes)`);
// Claim the index synchronously (before the write await) so two concurrent
// calls for the same index can't both pass the dedup check or double-count
// bytes. `written` is only set AFTER the bytes hit disk, so completion can
// never fire while this chunk file is still being written.
state.claimed.add(index);
state.bytesWritten += buf.length;
try {
await fs.promises.writeFile(path.join(state.tempDir, `${index}.chunk`), buf);
} catch (err) {
state.claimed.delete(index);
state.bytesWritten -= buf.length;
throw err;
}
state.written.add(index);
clearTimeout(state.timeoutId);
state.timeoutId = reapTimer(state.key);
return statusFrame(state, 'chunk_received');
}
if (p.is_complete || state.written.size === state.totalChunks) {
return completeUpload(state);
}
return statusFrame(state, 'file_created');
}
// ─────────────────────────── action definitions ───────────────────────────
const uploadParams = {
stream_id: f.string({ allowEmpty: false }).describe('流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])'),
chunk_data: f.string().optional().describe('分块数据(Base64)'),
chunk_index: f.int({ min: 0 }).optional().describe('分块索引(从 0 开始)'),
total_chunks: f.int({ min: 1 }).optional().describe('总分块数(新流必填)'),
file_size: f.int({ min: 0 }).optional().describe('文件总大小(字节)'),
expected_sha256: f.string().optional().describe('期望的整文件 SHA256(校验)'),
is_complete: f.bool().optional().describe('是否为最后一个分块/触发合并'),
filename: f.string().optional().describe('文件名'),
reset: f.bool().optional().describe('重置并丢弃该流'),
verify_only: f.bool().optional().describe('仅查询当前流状态'),
file_retention: f.int({ min: 0 }).default(DEFAULT_RETENTION_MS).describe('合并文件保留毫秒(0=不回收)'),
};
type UploadParams = {
stream_id: string;
chunk_data: string | undefined;
chunk_index: number | undefined;
total_chunks: number | undefined;
file_size: number | undefined;
expected_sha256: string | undefined;
is_complete: boolean | undefined;
filename: string | undefined;
reset: boolean | undefined;
verify_only: boolean | undefined;
file_retention: number;
};
const uploadFileStream = defineStreamAction({
name: 'upload_file_stream',
summary: '以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)',
returns: '流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)',
params: uploadParams,
run: (p, ctx) => handleUpload(p, accountKey(ctx)),
});
function cleanDir(dir: string): number {
let removed = 0;
let entries: string[];
try { entries = fs.readdirSync(dir); } catch { return 0; } // dir absent → nothing to clean
for (const name of entries) {
try { fs.rmSync(path.join(dir, name), { recursive: true, force: true }); removed++; } catch (err) {
log.warn('failed to remove stream temp %s: %s', path.join(dir, name), err instanceof Error ? err.message : String(err));
}
}
return removed;
}
const cleanStreamTempFile = defineAction({
name: 'clean_stream_temp_file',
summary: '清理流式传输临时文件(仅清理 stream 上传/下载目录)',
returns: '{ message, removed }',
params: {},
run: () => {
const removed = cleanDir(STREAM_UPLOAD_DIR) + cleanDir(STREAM_DOWNLOAD_DIR);
// Active uploads' chunk dirs may have been wiped — drop their state too.
for (const k of [...uploads.keys()]) cleanupUpload(k, false);
return okResponse({ message: 'success', removed });
},
});
export const actions = [uploadFileStream, cleanStreamTempFile];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
for (const a of actions) a.register(h, ctx);
}
// Exposed for tests.
export const __test = { uploads, handleUpload, cleanDir, validateStreamId, STREAM_UPLOAD_DIR, MAX_CONCURRENT_STREAMS, MAX_CHUNKS };
+67 -27
View File
@@ -11,9 +11,12 @@ import { register as registerInfo } from './actions/info';
import { register as registerMessage } from './actions/message';
import { register as registerQzone } from './actions/qzone';
import { register as registerRequest } from './actions/request';
import { register as registerStreamFile } from './actions/stream-file';
import { register as registerStreamDownload } from './actions/stream-download';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import { RETCODE, failedResponse } from './types';
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from './streaming';
const moduleLog = createLogger('Bridge.Action');
@@ -80,7 +83,7 @@ export interface ApiActionContext {
fetchPttText: (messageId: number) => Promise<{ text: string }>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise<import('./types').ApiResponse>;
/** A handled-action record handed to debug observers. */
export interface ActionRecord {
@@ -93,6 +96,9 @@ export type ActionObserver = (rec: ActionRecord) => void;
export class ApiHandler {
private readonly handlers = new Map<string, ActionHandler>();
/** Names that answer with a multi-frame Stream API response (#163). The
* network adapter consults this BEFORE dispatch to pick streaming output. */
private readonly streamActions = new Set<string>();
private readonly log: Logger;
/** Debug-stream taps — notified after every handled action. Attached
* on-demand (ref-counted) by the WebUI debug stream. */
@@ -116,13 +122,27 @@ export class ApiHandler {
registerExtended(this, context);
registerGroupAlbum(this, context);
registerQzone(this, context);
registerStreamFile(this, context);
registerStreamDownload(this, context);
}
registerAction(action: string, handler: ActionHandler): void {
this.handlers.set(action, handler);
}
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
/** Register a Stream API action — dispatched exactly like a normal action,
* but flagged so adapters stream its frames (the handler receives a sink). */
registerStreamAction(action: string, handler: ActionHandler): void {
this.handlers.set(action, handler);
this.streamActions.add(action);
}
/** Whether `action` answers with a multi-frame Stream API response. */
isStreamAction(action: string): boolean {
return this.streamActions.has(action);
}
async handle(action: string, params: JsonObject, sink?: StreamSink): Promise<import('./types').ApiResponse> {
const handler = this.handlers.get(action);
if (!handler) {
this.log.debug('unknown action %s', action);
@@ -134,15 +154,16 @@ export class ApiHandler {
// the wrap + id allocation when trace is actually live, so the default
// path stays allocation-free.
if (getLogLevel() !== 'trace') {
return this.runAction(action, handler, params);
return this.runAction(action, handler, params, sink);
}
return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params));
return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params, sink));
}
private async runAction(
action: string,
handler: ActionHandler,
params: JsonObject,
sink?: StreamSink,
): Promise<import('./types').ApiResponse> {
// Terse breadcrumb to the log file (debug, always persisted): lets the
// operator grep "what did the bot get asked to do" in post-mortems.
@@ -154,7 +175,7 @@ export class ApiHandler {
const startedAt = Date.now();
let response: import('./types').ApiResponse;
try {
response = await handler(params);
response = await handler(params, sink);
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
} catch (error) {
// Action failures are almost always param-shape problems coming
@@ -185,33 +206,52 @@ export class ApiHandler {
}
}
async processRequest(rawRequest: string): Promise<string> {
if (!rawRequest.trim()) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
/** WS dispatch supporting Stream API multi-frame responses. A normal action
* emits exactly one frame; a stream action emits each intermediate frame
* then the terminal frame — every frame carries the request's echo. `emit`
* writes one JSON string per frame; awaiting it lets the transport apply
* backpressure. `isAlive`, when supplied, is checked before each stream
* frame — returning false aborts the action (e.g. the client disconnected),
* so a dead client can't make a download keep pumping frames into the void. */
async processStreamRequest(
rawRequest: string,
emit: (json: string) => void | Promise<void>,
isAlive?: () => boolean,
): Promise<void> {
const bad = (): void => { void emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))); };
if (!rawRequest.trim()) { bad(); return; }
let action: string;
let params: JsonObject;
let echo: JsonValue | undefined;
try {
const parsed = JSON.parse(rawRequest) as unknown;
if (!isJsonObject(parsed)) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
const action = asString(parsed.action);
if (!action) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
const params = isJsonObject(parsed.params) ? parsed.params : {};
const echo = parsed.echo;
const response = await this.handle(action, params);
if (echo !== undefined) {
response.echo = toJsonValue(echo);
}
return JSON.stringify(response);
if (!isJsonObject(parsed)) { bad(); return; }
const a = asString(parsed.action);
if (!a) { bad(); return; }
action = a;
params = isJsonObject(parsed.params) ? parsed.params : {};
echo = parsed.echo !== undefined ? toJsonValue(parsed.echo) : undefined;
} catch {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
bad();
return;
}
if (!this.isStreamAction(action)) {
const response = await this.handle(action, params);
if (echo !== undefined) response.echo = echo;
await emit(JSON.stringify(response));
return;
}
const sink: StreamSink = {
send: async (frame) => {
if (isAlive && !isAlive()) throw new Error('stream transport closed');
await emit(JSON.stringify(wrapStreamFrame(frame, echo)));
},
};
const response = await this.handle(action, params, sink);
await emit(JSON.stringify(wrapStreamTerminal(response, echo)));
}
}
+10
View File
@@ -73,6 +73,16 @@ export class OneBotInstance {
invokeAction(action: string, params: JsonObject): Promise<ApiResponse> {
return this.apiHandler.handle(action, params);
}
/** Drive an action through the streaming seam (debug tester, stream actions).
* `rawRequest` is a `{action, params, echo?}` JSON string; `emit` receives
* each frame as a JSON string. Non-stream actions emit a single frame. */
invokeStream(
rawRequest: string,
emit: (json: string) => void | Promise<void>,
isAlive?: () => boolean,
): Promise<void> {
return this.apiHandler.processStreamRequest(rawRequest, emit, isAlive);
}
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) {
this.uin = uin;
@@ -583,6 +583,19 @@ export async function sendPrivateMessage(
let allFileElements = elements.filter(e => e.type === 'file');
let nonFileElements = elements.filter(e => e.type !== 'file');
// [#145] A video above QQ's ~100 MB video-resource cap (MAX_VIDEO_SIZE)
// uploads "successfully" but renders as 视频已过期 on the receiver — the
// server accepts the bytes yet never produces a valid video resource. The
// on-error fallback below can't catch it (the oversized upload doesn't
// throw), so route known-oversized videos to the file path up front.
{
const pre = splitVideoFileFallback(nonFileElements, false);
if (pre.fileEls.length > 0) {
allFileElements = [...allFileElements, ...pre.fileEls];
nonFileElements = pre.remaining;
}
}
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
if (nonFileElements.length > 0) {
try {
@@ -690,6 +703,16 @@ export async function sendGroupMessage(
let allFileElements = elements.filter(e => e.type === 'file');
let nonFileElements = elements.filter(e => e.type !== 'file');
// [#145] Route known-oversized videos (> MAX_VIDEO_SIZE) to the file path
// up front — they upload as a video without error but render expired.
{
const pre = splitVideoFileFallback(nonFileElements, false);
if (pre.fileEls.length > 0) {
allFileElements = [...allFileElements, ...pre.fileEls];
nonFileElements = pre.remaining;
}
}
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
if (nonFileElements.length > 0) {
try {
@@ -5,8 +5,10 @@ import {
type Server,
type ServerResponse,
} from 'http';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import type { ApiResponse, HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from '../streaming';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
@@ -181,6 +183,13 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
return;
}
// Stream API (#163): answer with chunked multi-frame output — each frame
// a JSON envelope delimited by `\r\n\r\n`, terminated by the final frame.
if (this.ctx.api.isStreamAction(action)) {
await streamHttpResponse(res, this.ctx.api, action, params as JsonObject, echo as JsonValue | undefined);
return;
}
const response = await this.ctx.api.handle(action, params as JsonObject);
if (echo !== undefined) {
response.echo = echo as JsonValue;
@@ -212,7 +221,41 @@ function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Prom
}
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
// A streaming response may already have flushed headers (and even ended); a
// late error must not double-send and trip ERR_HTTP_HEADERS_SENT.
if (res.headersSent || res.writableEnded) return;
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}
/** Stream a multi-frame Stream API response (#163): chunked transfer (no
* Content-Length → Node frames it), each frame a JSON envelope delimited by
* `\r\n\r\n`, the action's terminal response written last. Matches NapCat:
* the body is `\r\n\r\n`-joined JSON objects, NOT a single JSON document, so
* no `application/json` Content-Type is claimed. Each `res.write` is awaited
* (flush callback) for backpressure, and the sink aborts the action once the
* client disconnects so a big download stops pumping into a dead socket. */
async function streamHttpResponse(
res: ServerResponse,
api: ApiHandler,
action: string,
params: JsonObject,
echo: JsonValue | undefined,
): Promise<void> {
res.statusCode = 200;
const writeFrame = (frame: ApiResponse): Promise<void> =>
new Promise((resolve) => {
if (res.writableEnded || res.destroyed) { resolve(); return; }
res.write(JSON.stringify(frame) + '\r\n\r\n', () => resolve());
});
const sink: StreamSink = {
send: async (frame) => {
if (res.writableEnded || res.destroyed) throw new Error('stream client disconnected');
await writeFrame(wrapStreamFrame(frame, echo));
},
};
const response = await api.handle(action, params, sink);
await writeFrame(wrapStreamTerminal(response, echo));
if (!res.writableEnded && !res.destroyed) res.end();
}
+13
View File
@@ -31,6 +31,19 @@ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Err
});
}
/** Backpressure-aware send: resolves only once `ws` has flushed `payload` to
* the socket (the `send` callback fires post-write), so a streaming producer
* that awaits this won't outrun a slow client and balloon the send buffer.
* Never rejects — a closed socket or send error resolves quietly (the stream
* sink handles liveness/abort separately so a dead client can't crash the
* per-message handler with an unhandled rejection). */
export function safeSendAsync(socket: WebSocket, payload: string): Promise<void> {
return new Promise((resolve) => {
if (socket.readyState !== 1 /* WebSocket.OPEN */) { resolve(); return; }
socket.send(payload, () => resolve());
});
}
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
socket.close(code, reason);
@@ -8,7 +8,7 @@ import {
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
import { rawDataToString, safeClose, safeSend, safeSendAsync } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
@@ -146,8 +146,13 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
if (this.role !== 'Api' && this.role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
// Stream API (#163): one frame for a normal action, N for a streaming one.
// Async send = backpressure; liveness check aborts on disconnect.
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1,
);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
@@ -9,7 +9,7 @@ import {
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
@@ -119,7 +119,9 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
void this.handleApiMessage(socket, role, raw).catch((err) => {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
});
socket.on('close', () => this.connections.delete(socket));
socket.on('error', (err: Error) => {
@@ -135,8 +137,15 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
if (role !== 'Api' && role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
// Stream API (#163) emits multiple frames per request; processStreamRequest
// sends one frame for a normal action and N for a streaming one. The async
// send applies backpressure (awaits flush); the liveness check aborts a
// streaming action once the client goes away.
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1,
);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
+75
View File
@@ -0,0 +1,75 @@
// streaming — Stream API plumbing (#163, NapCat-compatible).
//
// A handful of OneBot actions ("Stream API") answer a single request with
// MANY response frames instead of one: an upload acks each chunk, a download
// pushes the file out chunk-by-chunk. SnowLuma's normal dispatch is strictly
// one-request → one-response, so streaming needs a small seam:
//
// • a `StreamSink` the action calls to emit intermediate frames, and
// • per-adapter wiring that writes each frame on the wire (HTTP chunked /
// repeated WS messages) instead of closing after the first.
//
// Wire format mirrors NapCat exactly so its client scripts work unchanged:
// every frame is an OB11 envelope carrying `stream:'stream-action'`, and the
// frame `data` is a StreamPacket whose `type` is one of stream/response/error.
import type { ApiResponse, JsonValue } from './types';
/** Marks an OB11 envelope as one frame of a streaming response. */
export const STREAM_MARK = 'stream-action';
/** Frame `type` discriminator carried inside each frame's `data`. */
export enum StreamStatus {
/** An intermediate chunk frame (transfer in progress). */
Stream = 'stream',
/** The terminal frame — the stream finished successfully. */
Response = 'response',
/** A stream was reset / aborted by the caller. */
Reset = 'reset',
/** The terminal frame — the stream failed. */
Error = 'error',
}
/** A sink an action uses to push intermediate stream frames. Each `send`
* carries the raw frame DATA (a StreamPacket: `{ type, data_type, ... }`);
* the network adapter wraps it in an OB11 envelope + the stream marker and
* flushes it on the wire. The action's eventual return value is the terminal
* frame, so do NOT `send` the final result through the sink. */
export interface StreamSink {
send(frame: JsonValue): Promise<void>;
}
/** Fallback sink for when a stream action is invoked over a transport that
* can't stream (or by a plain client): intermediate frames are dropped, the
* terminal response is still returned normally. */
export const NOOP_SINK: StreamSink = { send: async () => { /* dropped */ } };
/** Wrap a raw stream-frame `data` payload into an OB11 envelope carrying the
* stream marker (mirrors NapCat's `OB11Response.ok(data, echo, true)`). The
* empty `message`/`wording` pair matches NapCat — clients reading either key
* on an intermediate frame get `''`, never `undefined`. */
export function wrapStreamFrame(data: JsonValue, echo: JsonValue | undefined): ApiResponse {
const frame: ApiResponse = { status: 'ok', retcode: 0, data, message: '', wording: '', stream: STREAM_MARK };
if (echo !== undefined) frame.echo = echo;
return frame;
}
/** Turn an action's terminal `ApiResponse` into the final streaming frame:
* attach the stream marker + echo, mirror `wording` into `message` (NapCat
* sets both), and — on failure — normalise `data` to an error packet
* (`{ type:'error' }`) so NapCat clients see the error `type` while the
* human-readable reason stays in `message`/`wording`.
*
* Contract: on success the action's `data` MUST carry `type:'response'` (the
* client treats that frame as the stream terminator). Stream actions are
* responsible for that, mirroring NapCat's `BaseDownloadStream`. */
export function wrapStreamTerminal(response: ApiResponse, echo: JsonValue | undefined): ApiResponse {
const frame: ApiResponse = { ...response, stream: STREAM_MARK };
if (echo !== undefined) frame.echo = echo;
if (response.status === 'failed') {
frame.data = { type: StreamStatus.Error, data_type: 'error' };
}
frame.message = frame.wording ?? '';
if (frame.wording === undefined) frame.wording = '';
return frame;
}
+7
View File
@@ -7,6 +7,13 @@ export interface ApiResponse {
data: JsonValue;
echo?: JsonValue;
wording?: string;
/** Mirror of `wording` carried on Stream API frames — NapCat puts the
* message text in BOTH `message` and `wording`, so clients reading either
* key work. Only set on stream frames. */
message?: string;
/** Only set on Stream API frames — `'stream-action'`. Marks an envelope as
* one frame of a multi-frame streaming response (NapCat Stream API wire). */
stream?: string;
}
export interface OneBotRequest {
+41 -1
View File
@@ -167,7 +167,7 @@ describe('run raw escape hatch — original params as 3rd arg', () => {
describe('toJsonSchema / inputSchema (for the MCP)', () => {
it('emits a JSON Schema fragment per coercer', () => {
expect(f.uint().toJsonSchema()).toEqual({ type: 'integer', minimum: 1 });
expect(f.messageId().toJsonSchema()).toEqual({ type: 'integer', not: { const: 0 } });
expect(f.messageId().toJsonSchema()).toEqual({ type: 'integer', not: { const: 0 }, 'x-role': 'message_id' });
expect(f.int({ min: 0 }).default(1800).toJsonSchema()).toEqual({ type: 'integer', minimum: 0, default: 1800 });
expect(f.string({ allowEmpty: false }).toJsonSchema()).toEqual({ type: 'string', minLength: 1 });
expect(f.bool().toJsonSchema()).toEqual({ type: 'boolean' });
@@ -217,4 +217,44 @@ describe('describe — doc metadata for self-generated docs (D4)', () => {
const duration = doc.params.find((p) => p.name === 'duration');
expect(duration).toMatchObject({ type: 'int', required: false, default: 1800, desc: 'seconds; 0 unmutes' });
});
it('stamps semantic roles on preset-injected fields (group_id / member-like user_id)', () => {
const doc = spec.describe();
expect(doc.params.find((p) => p.name === 'group_id')?.role).toBe('group_id');
// In a group action the user_id is a member of that group → member_id role.
expect(doc.params.find((p) => p.name === 'user_id')?.role).toBe('member_id');
expect(doc.stream).toBeUndefined();
});
});
describe('FieldRole — semantic constructors and .role()', () => {
it('semantic constructors coerce like their primitive but carry a role', () => {
expect(f.groupId().doc).toMatchObject({ type: 'uint', role: 'group_id' });
expect(f.userId().doc).toMatchObject({ type: 'uint', role: 'user_id' });
expect(f.memberId().doc).toMatchObject({ type: 'uint', role: 'member_id' });
expect(f.image().doc).toMatchObject({ type: 'string', role: 'image' });
expect(f.duration().doc).toMatchObject({ type: 'int', role: 'duration' });
// Coercion is unchanged: a groupId still validates exactly like a uint.
const g = f.groupId().coerce('123', 'group_id');
expect(g.ok && g.value).toBe(123);
const bad = f.groupId().coerce('0', 'group_id');
expect(bad.ok).toBe(false);
});
it('.role() overrides/stamps a role and survives optional()/default()', () => {
expect(f.uint().role('group_id').doc.role).toBe('group_id');
expect(f.uint().role('group_id').optional().doc.role).toBe('group_id');
expect(f.string().role('file').default('').doc.role).toBe('file');
});
it("surfaces role through describe() params and toJsonSchema's x-role", () => {
const spec = defineAction({
name: 'demo',
params: { gid: f.groupId(), pic: f.image() },
run: () => okResponse(),
});
const doc = spec.describe();
expect(doc.params.find((p) => p.name === 'gid')?.role).toBe('group_id');
expect(f.groupId().toJsonSchema()).toMatchObject({ 'x-role': 'group_id' });
});
});
@@ -18,6 +18,7 @@ function fakeCtx(handleFn: (action: string, params: Record<string, unknown>) =>
const data = handleFn(action, params);
return { status: 'ok', retcode: 0, data };
}),
isStreamAction: () => false,
} as any,
buildLifecycleEvent: vi.fn(() => ({})),
buildHeartbeatEvent: vi.fn(() => ({})),
+4 -6
View File
@@ -326,15 +326,13 @@ describe('parseMessage', () => {
}], { bridge, groupId: 123456 });
// The video main file carries real bytes but the server fast-paths it
// (fileExist:true, no uKey) — #145's forceFullOnFastPath re-issues the
// OIDB request with fast-upload disabled, so two packets go out.
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
// (fileExist:true, no uKey). The send trusts that single fast-path
// response — the old forceFullOnFastPath retry was removed (proven
// ineffective, see #145), so exactly ONE OIDB request goes out.
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
expect(bridge.sendRawPacket).toHaveBeenNthCalledWith(1, 'OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
expect(bridge.sendRawPacket).toHaveBeenNthCalledWith(2, 'OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
const firstReq = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[0]![1] as Uint8Array);
const secondReq = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[1]![1] as Uint8Array);
expect(firstReq.body.upload.tryFastUploadCompleted).toBe(true);
expect(secondReq.body.upload.tryFastUploadCompleted ?? false).toBe(false);
expect(protoElems).toHaveLength(1);
expect(protoElems[0].commonElem?.serviceType).toBe(48);
expect(protoElems[0].commonElem?.businessType).toBe(21);
@@ -68,7 +68,7 @@ import type { JsonObject, WsClientNetwork, WsServerNetwork } from '../src/types'
function ctx(): NetworkAdapterContext {
return {
uin: '10001',
api: { processRequest: async () => '' } as never,
api: { processStreamRequest: async () => {} } as never,
buildLifecycleEvent: (sub) => ({ post_type: 'meta_event', meta_event_type: 'lifecycle', sub_type: sub }),
buildHeartbeatEvent: () => ({ post_type: 'meta_event', meta_event_type: 'heartbeat', interval: 5000 }),
};
@@ -52,7 +52,7 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
const NULL_CTX: NetworkAdapterContext = {
uin: '10001',
api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processRequest: async () => '' } as never,
api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processStreamRequest: async () => {} } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
@@ -0,0 +1,65 @@
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
function makeHandler(qzone: Record<string, unknown>): ApiHandler {
const bridge = { apis: { qzone } } as unknown as BridgeInterface;
const ctx = { bridge } as ApiActionContext;
return new ApiHandler(ctx);
}
describe('qzone actions', () => {
it('send_qzone_msg uploads images and publishes richvals joined with tab', async () => {
const uploadImageFromSource = vi.fn()
.mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' })
.mockResolvedValueOnce({ richval: 'RV2', url: 'URL2' });
const publish = vi.fn().mockResolvedValue({ tid: 'T1', time: 1 });
const handler = makeHandler({ uploadImageFromSource, publish });
const res = await handler.handle('send_qzone_msg', {
content: 'hello',
images: ['file:///a.jpg', 'file:///b.jpg'],
});
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { tid: 'T1', time: 1 } });
expect(uploadImageFromSource).toHaveBeenNthCalledWith(1, 'file:///a.jpg');
expect(uploadImageFromSource).toHaveBeenNthCalledWith(2, 'file:///b.jpg');
expect(publish).toHaveBeenCalledWith('hello', 1, 'RV1\tRV2');
});
it('comment_qzone uploads images and comments direct urls joined with tab', async () => {
const uploadImageFromSource = vi.fn()
.mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' })
.mockResolvedValueOnce({ richval: 'RV2', url: 'URL2' });
const comment = vi.fn().mockResolvedValue({ comment_id: 'C1' });
const handler = makeHandler({ uploadImageFromSource, comment });
const res = await handler.handle('comment_qzone', {
tid: 'T1',
content: 'nice',
target_uin: 20002,
images: ['file:///a.jpg', 'file:///b.jpg'],
});
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { comment_id: 'C1' } });
expect(comment).toHaveBeenCalledWith('T1', 'nice', 20002, 1, 'URL1\tURL2');
});
it('returns a clear error and skips publish when one image upload fails', async () => {
const uploadImageFromSource = vi.fn()
.mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' })
.mockRejectedValueOnce(new Error('network down'));
const publish = vi.fn();
const handler = makeHandler({ uploadImageFromSource, publish });
const res = await handler.handle('send_qzone_msg', {
content: 'hello',
images: ['file:///a.jpg', 'file:///b.jpg'],
});
expect(res).toMatchObject({ status: 'failed', retcode: 1200 });
expect(res.wording).toContain('第 2 张图片上传失败: network down');
expect(publish).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,116 @@
// Phase 3 — download stream actions (#163): server-push multi-frame.
import { describe, it, expect, afterEach } from 'vitest';
import fs from 'fs';
import path from 'path';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import { __test } from '../src/actions/stream-download';
import { STREAM_DOWNLOAD_DIR, __test as fileTest } from '../src/actions/stream-file';
const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record<string, any>);
afterEach(() => {
fileTest.cleanDir(STREAM_DOWNLOAD_DIR);
});
describe('test_download_stream', () => {
it('pushes 10 data frames then a data_complete terminal', async () => {
const h = new ApiHandler({} as ApiActionContext);
expect(h.isStreamAction('test_download_stream')).toBe(true);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'test_download_stream', params: {}, echo: 'T' }), (j) => frames.push(j));
const got = parse(frames);
expect(got).toHaveLength(11);
expect(got[0]).toMatchObject({ stream: 'stream-action', echo: 'T', data: { type: 'stream', data_type: 'data_chunk', data: 'Index-> 1' } });
expect(got[9]).toMatchObject({ data: { data: 'Index-> 10' } });
expect(got[10]).toMatchObject({ status: 'ok', data: { type: 'response', data_type: 'data_complete', data: 'Stream transmission complete' } });
});
it('error=true streams the 10 frames then terminates with an error frame', async () => {
const h = new ApiHandler({} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'test_download_stream', params: { error: true } }), (j) => frames.push(j));
const got = parse(frames);
expect(got).toHaveLength(11);
expect(got[9]).toMatchObject({ data: { data_type: 'data_chunk' } });
expect(got[10]).toMatchObject({ status: 'failed', data: { type: 'error' } });
});
});
describe('download_file_stream (local, fenced)', () => {
it('streams file_info → file_chunk* → file_complete and reassembles exactly', async () => {
fs.mkdirSync(STREAM_DOWNLOAD_DIR, { recursive: true });
const fp = path.join(STREAM_DOWNLOAD_DIR, 'dl.bin');
const content = Buffer.from('snowluma stream download payload '.repeat(4000)); // ~128 KB → multiple 64 KB chunks
fs.writeFileSync(fp, content);
const h = new ApiHandler({} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'download_file_stream', params: { file: fp, chunk_size: 65536 }, echo: 'D' }), (j) => frames.push(j));
const got = parse(frames);
expect(got[0]).toMatchObject({ stream: 'stream-action', echo: 'D', data: { data_type: 'file_info', file_name: 'dl.bin', file_size: content.length, chunk_size: 65536 } });
const chunks = got.filter((p) => p.data?.data_type === 'file_chunk');
expect(chunks.length).toBeGreaterThan(1);
// indices are sequential and progress is monotonic
chunks.forEach((c, i) => expect(c.data.index).toBe(i));
const last = got[got.length - 1];
expect(last).toMatchObject({ status: 'ok', data: { type: 'response', data_type: 'file_complete', total_bytes: content.length, total_chunks: chunks.length } });
const reassembled = Buffer.concat(chunks.map((c) => Buffer.from(c.data.data, 'base64')));
expect(reassembled.equals(content)).toBe(true);
});
it('refuses an arbitrary local path outside the stream root [arbitrary-read guard]', async () => {
await expect(__test.resolveDownload('/etc/passwd', {} as ApiActionContext, 'auto', 65536)).rejects.toThrow(/restricted to the stream temp/i);
await expect(__test.resolveDownload('file:///etc/hosts', {} as ApiActionContext, 'auto', 65536)).rejects.toThrow(/restricted to the stream temp/i);
// and end-to-end the dispatch surfaces it as an error frame, not a leak
const h = new ApiHandler({} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'download_file_stream', params: { file: '/etc/passwd' } }), (j) => frames.push(j));
expect(parse(frames).at(-1)).toMatchObject({ status: 'failed', data: { type: 'error' } });
});
});
describe('SSRF guard', () => {
it('classifies private/loopback/link-local addresses (incl. normalized v4-mapped IPv6) [C2]', () => {
const priv = [
'127.0.0.1', '10.0.0.5', '192.168.1.1', '172.16.0.1', '169.254.1.1', '0.0.0.0', '100.64.0.1',
'::1', 'fc00::1', 'fd12::1', 'fe80::1',
'::ffff:127.0.0.1', '::ffff:169.254.169.254', // dotted v4-mapped
'::ffff:7f00:1', '::ffff:a9fe:a9fe', // hex v4-mapped (what `new URL` produces)
'::127.0.0.1', '64:ff9b::7f00:1', // v4-compatible, NAT64-mapped loopback
];
for (const ip of priv) expect(__test.isPrivateIp(ip), ip).toBe(true);
for (const ip of ['8.8.8.8', '1.1.1.1', '203.0.113.4', '2606:4700:4700::1111', '::ffff:8.8.8.8']) {
expect(__test.isPrivateIp(ip), ip).toBe(false);
}
});
it('rejects non-http(s) schemes and private/loopback URL targets — incl. v4-mapped literals [C1/C2]', async () => {
await expect(__test.assertSafeUrl('ftp://example.com/x')).rejects.toThrow(/http\(s\)/i);
await expect(__test.assertSafeUrl('file:///etc/passwd')).rejects.toThrow(/http\(s\)/i);
await expect(__test.assertSafeUrl('http://127.0.0.1/x')).rejects.toThrow(/private\/loopback/i);
await expect(__test.assertSafeUrl('http://[::1]/x')).rejects.toThrow(/private\/loopback/i);
// v4-mapped IPv6 literal → new URL normalizes hostname to hex; must still block
await expect(__test.assertSafeUrl('http://[::ffff:127.0.0.1]/x')).rejects.toThrow(/private\/loopback/i);
await expect(__test.assertSafeUrl('http://[::ffff:169.254.169.254]/meta')).rejects.toThrow(/private\/loopback/i);
await expect(__test.assertSafeUrl('http://localhost/x')).rejects.toThrow(/private/i);
});
});
describe('cached image/voice id resolution reaches the media branch [M1]', () => {
it('a cache id flows past the local check to getImageInfo (then SSRF-guards its URL)', async () => {
const ctx = {
getImageInfo: async () => ({ url: 'http://10.0.0.7/cached.png', file: '', file_name: 'cached.png', file_size: '9' }),
getRecordInfo: async () => null,
} as unknown as ApiActionContext;
// 'abc123.image' is not a real file → must NOT be rejected as "restricted";
// it reaches getImageInfo, whose private URL is then blocked by the SSRF guard.
await expect(__test.resolveDownload('abc123.image', ctx, 'image', 65536)).rejects.toThrow(/private/i);
});
});
+184
View File
@@ -0,0 +1,184 @@
// Phase 2 — upload_file_stream + clean_stream_temp_file (#163).
import { describe, it, expect, afterEach } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { createHash } from 'crypto';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import { __test, STREAM_UPLOAD_DIR } from '../src/actions/stream-file';
const { handleUpload, cleanDir, uploads } = __test;
type UP = Parameters<typeof handleUpload>[0];
const b64 = (s: string | Buffer): string => Buffer.from(s).toString('base64');
// Fill every optional key so the direct handleUpload calls satisfy the type.
function mk(p: Partial<UP> & { stream_id: string }): UP {
return {
chunk_data: undefined, chunk_index: undefined, total_chunks: undefined,
file_size: undefined, expected_sha256: undefined, is_complete: undefined,
filename: undefined, reset: undefined, verify_only: undefined,
file_retention: 0, ...p,
};
}
afterEach(() => {
cleanDir(STREAM_UPLOAD_DIR);
uploads.clear();
});
describe('upload_file_stream', () => {
it('reassembles ordered chunks into a file with correct content + sha256', async () => {
const id = 'up-ordered';
const parts = ['hello ', 'streamed ', 'world!'];
const full = parts.join('');
const sha = createHash('sha256').update(full).digest('hex');
let r = await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64(parts[0]) }));
expect(r.data).toMatchObject({ type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 3 });
await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 1, chunk_data: b64(parts[1]) }));
r = await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 2, chunk_data: b64(parts[2]) }));
expect(r.data).toMatchObject({ received_chunks: 3 });
r = await handleUpload(mk({ stream_id: id, total_chunks: 3, is_complete: true, expected_sha256: sha }));
const data = r.data as Record<string, unknown>;
expect(data).toMatchObject({ type: 'response', status: 'file_complete', total_chunks: 3, file_size: full.length, sha256: sha });
expect(fs.readFileSync(String(data.file_path), 'utf8')).toBe(full);
// state dropped after completion, chunk dir gone
expect(uploads.has(id)).toBe(false);
});
it('accepts out-of-order chunks and dedups repeats idempotently', async () => {
const id = 'up-ooo';
await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 2, chunk_data: b64('C') }));
await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64('A') }));
// duplicate of an already-received chunk → no double count
const dup = await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 2, chunk_data: b64('C') }));
expect(dup.data).toMatchObject({ received_chunks: 2 });
await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 1, chunk_data: b64('B') }));
const r = await handleUpload(mk({ stream_id: id, total_chunks: 3, is_complete: true }));
expect(fs.readFileSync(String((r.data as Record<string, unknown>).file_path), 'utf8')).toBe('ABC');
});
it('rejects completion with a missing chunk', async () => {
const id = 'up-missing';
await handleUpload(mk({ stream_id: id, total_chunks: 2, chunk_index: 0, chunk_data: b64('only') }));
await expect(handleUpload(mk({ stream_id: id, total_chunks: 2, is_complete: true }))).rejects.toThrow(/missing/i);
});
it('rejects a sha256 mismatch and deletes the bad file', async () => {
const id = 'up-sha';
await handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('data') }));
await expect(handleUpload(mk({ stream_id: id, total_chunks: 1, is_complete: true, expected_sha256: 'deadbeef' }))).rejects.toThrow(/sha256 mismatch/i);
// A failed completion keeps the stream (client can reset+retry; the reaper
// reclaims it if abandoned), but the corrupt merged file is deleted.
expect(uploads.has(id)).toBe(true);
expect(fs.existsSync(uploads.get(id)!.finalPath)).toBe(false);
});
it('rejects an out-of-range chunk index and a new stream without total_chunks', async () => {
await expect(handleUpload(mk({ stream_id: 'up-oob', total_chunks: 2, chunk_index: 5, chunk_data: b64('x') }))).rejects.toThrow(/invalid chunk index/i);
await expect(handleUpload(mk({ stream_id: 'up-no-total', chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/total_chunks required/i);
});
it('reset discards the stream (surfaced as an error, NapCat parity)', async () => {
const id = 'up-reset';
await handleUpload(mk({ stream_id: id, total_chunks: 2, chunk_index: 0, chunk_data: b64('x') }));
expect(uploads.has(id)).toBe(true);
await expect(handleUpload(mk({ stream_id: id, reset: true }))).rejects.toThrow(/reset/i);
expect(uploads.has(id)).toBe(false);
});
it('verify_only reports status, errors on unknown stream', async () => {
const id = 'up-verify';
await handleUpload(mk({ stream_id: id, total_chunks: 4, chunk_index: 0, chunk_data: b64('x') }));
const r = await handleUpload(mk({ stream_id: id, verify_only: true }));
expect(r.data).toMatchObject({ type: 'stream', received_chunks: 1, total_chunks: 4 });
await expect(handleUpload(mk({ stream_id: 'nope', verify_only: true }))).rejects.toThrow(/not found/i);
});
it('strips path separators from filename (no temp-dir escape)', async () => {
const id = 'up-escape';
await handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x'), filename: '../../evil.sh' }));
const r = await handleUpload(mk({ stream_id: id, total_chunks: 1, is_complete: true }));
const fp = String((r.data as Record<string, unknown>).file_path);
expect(path.dirname(fp)).toBe(STREAM_UPLOAD_DIR);
expect(fp).not.toContain('..');
});
});
describe('upload_file_stream hardening', () => {
it('rejects path-traversal / illegal stream_id (no escape) [C1]', async () => {
const evil = ['../../../../tmp/victim', '..', 'a/b', 'a\\b', 'with space', 'x'.repeat(129), '', 'dot.dot'];
for (const id of evil) {
await expect(handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/invalid stream_id/i);
}
// a benign traversal attempt left nothing outside the upload dir
expect(fs.existsSync('/tmp/victim')).toBe(false);
// validateStreamId accepts UUID-ish ids, rejects separators/dots
expect(() => __test.validateStreamId('uuid-1234-5678_ABCdef')).not.toThrow();
expect(() => __test.validateStreamId('../x')).toThrow();
expect(() => __test.validateStreamId('a/b')).toThrow();
expect(() => __test.validateStreamId('a.b')).toThrow();
});
it('rejects total_chunks above the cap [M1]', async () => {
await expect(handleUpload(mk({ stream_id: 'up-huge', total_chunks: __test.MAX_CHUNKS + 1, chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/total_chunks exceeds limit/i);
});
it('caps concurrent streams [M2]', async () => {
for (let i = 0; i < __test.MAX_CONCURRENT_STREAMS; i++) {
await handleUpload(mk({ stream_id: `cap-${i}`, total_chunks: 2, chunk_index: 0, chunk_data: b64('x') }));
}
await expect(handleUpload(mk({ stream_id: 'cap-overflow', total_chunks: 2, chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/too many concurrent/i);
});
it('counts a concurrently-duplicated chunk index only once [M3]', async () => {
const id = 'up-race';
const [a, b] = await Promise.all([
handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64('A') })),
handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64('A') })),
]);
expect(a.status).toBe('ok');
expect(b.status).toBe('ok');
expect(uploads.get(id)!.written.size).toBe(1);
expect(uploads.get(id)!.claimed.size).toBe(1);
});
});
describe('upload_file_stream via the streaming dispatch', () => {
it('emits a stream-marked chunk frame end-to-end', async () => {
const h = new ApiHandler({} as ApiActionContext);
expect(h.isStreamAction('upload_file_stream')).toBe(true);
const frames: string[] = [];
await h.processStreamRequest(
JSON.stringify({ action: 'upload_file_stream', params: { stream_id: 'ws-up', total_chunks: 1, chunk_index: 0, chunk_data: b64('hi') }, echo: 'E' }),
(j) => frames.push(j),
);
expect(frames).toHaveLength(1);
expect(JSON.parse(frames[0])).toMatchObject({
status: 'ok', stream: 'stream-action', echo: 'E',
data: { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 1 },
});
});
});
describe('clean_stream_temp_file', () => {
it('removes stream temp entries and is scoped to the stream dirs', async () => {
fs.mkdirSync(STREAM_UPLOAD_DIR, { recursive: true });
const f1 = path.join(STREAM_UPLOAD_DIR, 'leftover.bin');
fs.writeFileSync(f1, 'junk');
// an unrelated temp file outside the stream dir must survive
const outside = path.join(os.tmpdir(), `snowluma-stream-unrelated-${Date.now()}.txt`);
fs.writeFileSync(outside, 'keep');
const h = new ApiHandler({} as ApiActionContext);
const r = await h.handle('clean_stream_temp_file', {});
expect(r.status).toBe('ok');
expect((r.data as Record<string, unknown>).message).toBe('success');
expect(fs.existsSync(f1)).toBe(false);
expect(fs.existsSync(outside)).toBe(true);
fs.rmSync(outside, { force: true });
});
});
+167
View File
@@ -0,0 +1,167 @@
// Phase 1 — Stream API plumbing (#163). Verifies the dispatch seam:
// defineStreamAction registers a streaming handler, processStreamRequest
// emits N intermediate frames + a terminal frame (all echo-tagged, marked
// `stream:'stream-action'`), normal actions stay single-frame, and failures
// terminate with an error frame. Wire format mirrors NapCat's Stream API.
import { describe, it, expect } from 'vitest';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import { defineAction, defineStreamAction, f } from '../src/action-kit';
import { okResponse, failedResponse } from '../src/types';
import { wrapStreamFrame, wrapStreamTerminal, STREAM_MARK } from '../src/streaming';
function newHandler(): ApiHandler {
// The real register* run lazily (handlers capture ctx, never call it at
// registration), so an empty ctx is enough to exercise the dispatch seam.
return new ApiHandler({} as ApiActionContext);
}
const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record<string, unknown>);
describe('Stream API plumbing', () => {
it('streams N intermediate frames + a terminal frame, all echo-tagged', async () => {
const h = newHandler();
defineStreamAction({
name: 'demo_stream',
params: { n: f.uint() },
run: async (p, _ctx, _raw, sink) => {
for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i });
return okResponse({ type: 'response', total: p.n });
},
}).register(h, {} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(
JSON.stringify({ action: 'demo_stream', params: { n: 2 }, echo: 'e1' }),
(j) => frames.push(j),
);
const got = parse(frames);
expect(got).toHaveLength(3);
expect(got[0]).toMatchObject({ status: 'ok', retcode: 0, stream: STREAM_MARK, echo: 'e1', data: { type: 'stream', index: 0 } });
expect(got[1]).toMatchObject({ stream: STREAM_MARK, echo: 'e1', data: { type: 'stream', index: 1 } });
expect(got[2]).toMatchObject({ status: 'ok', stream: STREAM_MARK, echo: 'e1', data: { type: 'response', total: 2 } });
});
it('marks the action as a stream action; normal actions are not', () => {
const h = newHandler();
defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext);
defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext);
expect(h.isStreamAction('demo_stream')).toBe(true);
expect(h.isStreamAction('demo_normal')).toBe(false);
expect(h.isStreamAction('nope')).toBe(false);
});
it('a normal action through processStreamRequest emits exactly one un-marked frame', async () => {
const h = newHandler();
defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'demo_normal', params: {}, echo: 'e2' }), (j) => frames.push(j));
expect(frames).toHaveLength(1);
const r = parse(frames)[0];
expect(r).toMatchObject({ status: 'ok', echo: 'e2', data: { ok: true } });
expect(r.stream).toBeUndefined();
});
it('a throwing stream action terminates with a single error frame', async () => {
const h = newHandler();
defineStreamAction({
name: 'demo_boom',
params: {},
run: async () => { throw new Error('boom'); },
}).register(h, {} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'demo_boom', params: {}, echo: 'e3' }), (j) => frames.push(j));
expect(frames).toHaveLength(1);
expect(parse(frames)[0]).toMatchObject({
status: 'failed', stream: STREAM_MARK, echo: 'e3', wording: 'boom', data: { type: 'error', data_type: 'error' },
});
});
it('emits already-sent frames before the terminal error when a stream throws mid-way', async () => {
const h = newHandler();
defineStreamAction({
name: 'demo_partial',
params: {},
run: async (_p, _ctx, _raw, sink) => {
await sink.send({ type: 'stream', index: 0 });
throw new Error('mid');
},
}).register(h, {} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'demo_partial', params: {} }), (j) => frames.push(j));
const got = parse(frames);
expect(got).toHaveLength(2);
expect(got[0]).toMatchObject({ stream: STREAM_MARK, data: { type: 'stream', index: 0 } });
expect(got[1]).toMatchObject({ status: 'failed', data: { type: 'error' } });
});
it('stream param validation fails terminate with an error frame', async () => {
const h = newHandler();
defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext);
const frames: string[] = [];
await h.processStreamRequest(JSON.stringify({ action: 'demo_needs', params: {} }), (j) => frames.push(j));
expect(frames).toHaveLength(1);
expect(parse(frames)[0]).toMatchObject({ status: 'failed', stream: STREAM_MARK, data: { type: 'error' } });
});
it('aborts a stream when isAlive turns false (client disconnect)', async () => {
const h = newHandler();
let sent = 0;
defineStreamAction({
name: 'demo_abort',
params: {},
run: async (_p, _ctx, _raw, sink) => {
for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; }
return okResponse({ type: 'response' });
},
}).register(h, {} as ApiActionContext);
const frames: string[] = [];
let alive = true;
await h.processStreamRequest(
JSON.stringify({ action: 'demo_abort', params: {} }),
(j) => { frames.push(j); if (frames.length >= 2) alive = false; },
() => alive,
);
expect(sent).toBeLessThan(5); // loop aborted once the client "left"
const got = parse(frames);
expect(got[got.length - 1]).toMatchObject({ status: 'failed', data: { type: 'error' } });
});
it('wrapStreamFrame / wrapStreamTerminal shape (NapCat message+wording mirror)', () => {
expect(wrapStreamFrame({ type: 'stream', x: 1 }, 'e')).toEqual({
status: 'ok', retcode: 0, data: { type: 'stream', x: 1 }, message: '', wording: '', stream: STREAM_MARK, echo: 'e',
});
// no echo → no echo key
expect(wrapStreamFrame({ type: 'stream' }, undefined)).toEqual({
status: 'ok', retcode: 0, data: { type: 'stream' }, message: '', wording: '', stream: STREAM_MARK,
});
// failed terminal → data normalised to an error packet; reason in BOTH message + wording
expect(wrapStreamTerminal(failedResponse(1404, 'nope'), 'e')).toMatchObject({
status: 'failed', retcode: 1404, message: 'nope', wording: 'nope', stream: STREAM_MARK, echo: 'e',
data: { type: 'error', data_type: 'error' },
});
// ok terminal → data passes through, message/wording empty
expect(wrapStreamTerminal(okResponse({ type: 'response', a: 1 }), undefined)).toMatchObject({
status: 'ok', stream: STREAM_MARK, message: '', data: { type: 'response', a: 1 },
});
});
it('malformed stream requests emit one bad-request frame', async () => {
const h = newHandler();
const frames: string[] = [];
await h.processStreamRequest('not json', (j) => frames.push(j));
await h.processStreamRequest('', (j) => frames.push(j));
await h.processStreamRequest(JSON.stringify({ params: {} }), (j) => frames.push(j)); // no action
expect(frames).toHaveLength(3);
for (const f of parse(frames)) expect(f).toMatchObject({ status: 'failed' });
});
});
@@ -70,7 +70,7 @@ import type { WsClientNetwork } from '../src/types';
function ctx(): NetworkAdapterContext {
return {
uin: '10001',
api: { processRequest: async () => '' } as never,
api: { processStreamRequest: async () => {} } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.10.4",
"version": "1.11.0",
"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).",
@@ -91,6 +91,10 @@
"./oidb-actions/ocr": {
"types": "./src/oidb-actions/ocr.ts",
"default": "./src/oidb-actions/ocr.ts"
},
"./oidb-actions/sys-faces": {
"types": "./src/oidb-actions/sys-faces.ts",
"default": "./src/oidb-actions/sys-faces.ts"
}
},
"scripts": {
+4 -1
View File
@@ -109,7 +109,10 @@ export interface OidbRenameMember {
body?: pb<3, OidbRenameMemberBody>;
}
export interface OidbRenameGroupBody {
targetName?: pb<1, string>;
// The group name lives at tag 3, NOT tag 1 — tags 1/2 make the server reject
// 0x89a_15 with OIDB error 1006 (#173). Confirmed against Lagrange's
// OidbSvcTrpcTcp0x89A_15Body (ProtoMember(3) TargetName).
targetName?: pb<3, string>;
}
export interface OidbRenameGroup {
groupUin?: pb<1, uint_32>;
@@ -0,0 +1,61 @@
// 0x9154_1 — system face / emoji catalog (sysface) protobuf shapes.
//
// Mirrors Lagrange.Core's FetchFullSysFacesService response: one round-trip
// returns every pack — common faces, "big"/super animated faces, and the
// magic-face pack. Each emoji carries its `aniSticker*` metadata, which the
// send path uses to pick the right wire encoding for a face id (classic
// FaceElem vs CommonElem 37/33). See protocol/oidb-services/sys-faces.
import type { pb, pb_repeated, int_32 } from '@snowluma/proton';
export interface OidbFaceResourceUrl {
baseUrl?: pb<1, string>;
advUrl?: pb<2, string>;
}
export interface OidbFaceEmoji {
qSid?: pb<1, string>;
qDes?: pb<2, string>;
emCode?: pb<3, string>;
qCid?: pb<4, int_32>;
aniStickerType?: pb<5, int_32>;
aniStickerPackId?: pb<6, int_32>;
aniStickerId?: pb<7, int_32>;
url?: pb<8, OidbFaceResourceUrl>;
emojiNameAlias?: pb_repeated<9, string>;
unknown10?: pb<10, int_32>;
aniStickerWidth?: pb<13, int_32>;
aniStickerHeight?: pb<14, int_32>;
}
export interface OidbFaceEmojiList {
emojiPackName?: pb<1, string>;
emojiDetail?: pb_repeated<2, OidbFaceEmoji>;
}
export interface OidbFaceContent {
emojiList?: pb_repeated<1, OidbFaceEmojiList>;
resourceUrl?: pb<2, OidbFaceResourceUrl>;
}
export interface OidbFaceMagicContentList {
emojiList?: pb_repeated<2, OidbFaceEmoji>;
}
export interface OidbFaceMagicContent {
field1?: pb<1, OidbFaceMagicContentList>;
resourceUrl?: pb<2, OidbFaceResourceUrl>;
}
export interface OidbFetchSysFacesReq {
field1?: pb<1, int_32>;
field2?: pb<2, int_32>;
field3?: pb<3, string>;
}
export interface OidbFetchSysFacesResp {
field1?: pb<1, int_32>;
commonFace?: pb<2, OidbFaceContent>;
specialBigFace?: pb<3, OidbFaceContent>;
specialMagicFace?: pb<4, OidbFaceMagicContent>;
}
+7 -3
View File
@@ -1,4 +1,4 @@
import type { pb, uint_32, uint_64, bytes } from '@snowluma/proton';
import type { pb, uint_32, uint_64 } from '@snowluma/proton';
/**
* Voice-to-text (语音转文字) request/response protobufs for the
@@ -28,7 +28,11 @@ export interface C2CPttTransItem {
size?: pb<6, uint_32>; // element 45405 (bytes)
format?: pb<7, uint_32>; // element 45907 (voice codec)
eventType?: pb<8, uint_32>; // element 45921
md5?: pb<9, bytes>; // element 45406 (raw 16-byte md5)
// QQ NT (EncodeC2CPtt) hex-encodes the md5 to a 32-char lowercase string
// before sending it (verified in wrapper.linux.node: field 9 = sub_7A02D80
// = bytes→hex). Sending the raw 16 bytes makes the server reject with
// errCode -1079. So this is a hex STRING, not bytes.
md5?: pb<9, string>; // element 45406 (32-char lowercase hex)
}
export interface GroupPttTransItem {
@@ -36,7 +40,7 @@ export interface GroupPttTransItem {
senderUin?: pb<2, uint_64>;
groupUin?: pb<3, uint_64>;
fileId?: pb<4, uint_32>; // element 45903 (group ptt numeric file id)
md5?: pb<5, bytes>; // element 45406
md5?: pb<5, string>; // element 45406 (32-char lowercase hex, see C2C note)
duration?: pb<6, uint_32>; // element 45906
size?: pb<7, uint_32>; // element 45405
format?: pb<8, uint_32>; // element 45907
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.10.4",
"version": "1.11.0",
"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>'`.",
+42 -6
View File
@@ -2,11 +2,12 @@ import type {
MarkdownData,
MentionExtraSend,
} from '@snowluma/proto-defs/action';
import type { Elem, GroupFileExtra, MarketFacePbReserve } from '@snowluma/proto-defs/element';
import type { Elem, GroupFileExtra, MarketFacePbReserve, QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element';
import { protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { deflateSync } from 'zlib';
import type { BridgeContext } from './bridge-context';
import { sysFaceStore } from './sys-face-store';
import type { MessageElement } from './events';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
@@ -39,10 +40,45 @@ function makeTextElem(text: string): ProtoElem {
};
}
function makeFaceElem(faceId: number): ProtoElem {
return {
face: { index: faceId },
};
// QQ-NT splits face ids across three wire encodings. The legacy FaceElem only
// renders classic small faces; newer "super" / animated faces sent that way are
// silently remapped by the server (e.g. 424→168, issue #168). The split is
// data-driven off the system-face catalog (0x9154_1, see sys-face-store):
// super (animated, aniSticker not pack (1,1)) → CommonElem 37 + QFaceExtra
// other id ≥ 260 → CommonElem 33 + QSmallFaceExtra
// classic id < 260 → legacy FaceElem
function makeFaceElem(faceId: number, ctx?: SendContext): ProtoElem {
// Keep the catalog warm so subsequent super-face sends are classified even if
// this one raced ahead of the first fetch.
if (ctx) sysFaceStore.ensureWarm(ctx.bridge);
const wire = sysFaceStore.classify(faceId);
if (wire.kind === 'super') {
return {
commonElem: {
serviceType: 37,
pbElem: protobuf_encode<QFaceExtra>({
packId: wire.packId,
stickerId: wire.stickerId,
qsid: faceId,
sourceType: 1,
stickerType: wire.stickerType,
randomType: 1,
}),
businessType: 1,
},
};
}
if (wire.kind === 'small') {
return {
commonElem: {
serviceType: 33,
pbElem: protobuf_encode<QSmallFaceExtra>({ faceId, preview: '', preview2: '' }),
businessType: 1,
},
};
}
return { face: { index: faceId } };
}
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
@@ -414,7 +450,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'face':
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId, ctx));
break;
case 'mface':
@@ -152,3 +152,64 @@ export async function encodeSilk(inputFile: string, tempDir: string): Promise<En
export function defaultPttTempDir(): string {
return path.join(os.tmpdir(), 'snowluma-ptt');
}
// ── audio transcode (get_record out_format, #165) ──
// The addon is a custom ffmpeg build that bundles a SILK decoder, so it can
// transcode a QQ voice (SILK/AMR) into a normal container in one convertFile
// call — mirroring NapCat's FFmpegService.convertAudioFmt.
/** Output formats accepted by `out_format` (mirrors NapCat's allowlist). */
export const AUDIO_OUT_FORMATS = ['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac'] as const;
export type AudioOutFormat = (typeof AUDIO_OUT_FORMATS)[number];
export function isAudioOutFormat(s: string): s is AudioOutFormat {
return (AUDIO_OUT_FORMATS as readonly string[]).includes(s);
}
/** Minimal addon surface the transcode needs — lets tests inject a fake. */
type AudioConvertAddon = Pick<FFmpegNativeAddon, 'convertFile'>;
/** Default ceiling on the transcoded output read into memory for base64. SILK→
* WAV/FLAC is a decompressing direction, so cap it even though real voices are
* tiny. Generous; overridable via deps. */
const DEFAULT_MAX_AUDIO_OUTPUT = 256 * 1024 * 1024; // 256 MiB
/**
* Transcode raw audio bytes (a QQ voice SILK/AMR) to `format`, returning the
* result as base64 + byte size. Writes the input + output to temp files (the
* native addon is file-based), always cleaning them up. `deps` injects a fake
* addon / tmp dir for tests. Throws on an unsupported format or a failed
* conversion (e.g. the binary lacks SILK decode).
*/
export async function convertAudioBytes(
bytes: Uint8Array,
format: string,
deps: { addon?: AudioConvertAddon; tmpDir?: string; maxOutputBytes?: number } = {},
): Promise<{ base64: string; size: number }> {
if (!isAudioOutFormat(format)) {
throw new Error(`unsupported out_format: ${format} (expected one of ${AUDIO_OUT_FORMATS.join(', ')})`);
}
const addon = deps.addon ?? getFFmpegAddon();
const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT;
const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'snowluma-rec');
fs.mkdirSync(dir, { recursive: true });
const id = crypto.randomBytes(8).toString('hex');
const inPath = path.join(dir, `${id}.in`);
const outPath = path.join(dir, `${id}.${format}`);
try {
await fs.promises.writeFile(inPath, bytes);
const res = await addon.convertFile(inPath, outPath, format);
if (!res?.success || !fs.existsSync(outPath)) throw new Error('audio conversion failed');
// Bound the output before reading it into memory (decompressing direction).
const stat = await fs.promises.stat(outPath);
if (stat.size > maxOut) throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`);
const out = await fs.promises.readFile(outPath);
return { base64: out.toString('base64'), size: out.length };
} finally {
// Await cleanup so no temp file lingers past the call (the bytes are
// already in memory by now). allSettled → a missing file never throws.
await Promise.allSettled([
fs.promises.rm(inPath, { force: true }),
fs.promises.rm(outPath, { force: true }),
]);
}
}
+15 -38
View File
@@ -51,16 +51,6 @@ export interface MediaSubFileUpload {
* Omit if the caller guarantees bytes always exist (e.g. video thumb
* always has FALLBACK_THUMB bytes). */
fastOnlyError?: string;
/** When true and the server fast-paths THIS sub-file (returns no uKey)
* even though we hold real bytes for it, `runNtv2Upload` re-issues the
* whole OIDB request with `tryFastUploadCompleted: false` to force a
* fresh full upload. Video sets this on the main file: group/c2c video
* resources expire server-side, so a fast-path hit can reference a
* stale object the receiver renders as "资源已过期". The thumb leaves
* this off — a cached thumb is harmless and not worth re-pushing the
* whole (potentially 100 MB) main video for. Forwarding paths carry no
* bytes (`bytes.length === 0`), so this never fires for them. */
forceFullOnFastPath?: boolean;
}
export interface NtV2UploadParams {
@@ -195,24 +185,18 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
return session;
};
// Run whatever PUTs the given `upload` response asks for. Returns true
// when a sub-file flagged `forceFullOnFastPath` was fast-pathed by the
// server (no uKey) while we hold real bytes for it — the caller uses
// that to force a non-fast-upload retry.
const runPuts = async (upload: NTV2UploadRespBody): Promise<boolean> => {
// Run whatever PUTs the given `upload` response asks for.
const runPuts = async (upload: NTV2UploadRespBody): Promise<void> => {
let didPut = false;
let staleFastPath = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
// No uKey: the server fast-pathed this sub-file (or msgInfo is absent
// entirely). When we actually hold bytes for it, the server is
// reusing a cached resource — surface it, and flag a stale fast-path
// when the caller asked us to distrust it for this sub-file.
// entirely) — it already holds (or claims to hold) the resource, so
// there are no bytes to push for it.
if (!uKey || !upload.msgInfo) {
if (!uKey && upload.msgInfo && sub.bytes.length > 0) {
log.debug('%s fast-upload hit for sub=%s (server reusing cached resource)', label, String(sub.source));
if (sub.forceFullOnFastPath) staleFastPath = true;
}
continue;
}
@@ -241,26 +225,19 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
if (!didPut) {
log.debug('%s fast-upload hit (server already had bytes)', label);
}
return staleFastPath;
};
let upload = await requestUpload(true);
const staleFastPath = await runPuts(upload);
// A flagged sub-file (video main) was fast-pathed to a server resource
// that may have expired. Re-issue without fast-upload so the server
// allocates a fresh resource and demands the bytes, then redo the PUTs
// against that response — the returned `upload` (and its msgInfo) must
// be the one we actually pushed bytes to.
if (staleFastPath) {
log.debug('%s forcing full upload — fast-path resource may be stale/expired', label);
upload = await requestUpload(false);
const stillFastPathed = await runPuts(upload);
if (stillFastPathed) {
log.debug('%s server still fast-pathed after forcing full upload — resource may remain stale', label);
}
}
// NOTE: a previous attempt re-issued the request with
// `tryFastUploadCompleted: false` when the server fast-pathed the main video,
// on the theory it would force a fresh upload of a possibly-expired resource.
// Real-machine testing + kernel RE proved that ineffective — the server's
// fast-path is driven by md5-metadata existence and ignores the flag, and the
// QQ NT kernel itself does no validity check either (HandleRspUploadV3 trusts
// `fileExist` and reports success). An expired-but-still-indexed video
// resource is a platform-level limitation, not something the upload flow can
// refresh. See #145.
const upload = await requestUpload(true);
await runPuts(upload);
return upload;
}
@@ -457,12 +457,6 @@ export async function uploadVideoMsgInfo(
sha1: video.sha1Blocks,
subFileIndex: 0,
fastOnlyError: 'video fast-upload not available (server requires bytes)',
// Distrust a server fast-path for the main video: group/c2c video
// resources expire server-side, so reusing a cached object can show
// "资源已过期" on the receiver even though the send "succeeded".
// When we hold the real bytes, force a fresh full upload instead.
// (Forwarding carries no bytes, so this never fires there.) See #145.
forceFullOnFastPath: true,
},
{
source: 0, // upload.subFileInfos[0]
@@ -0,0 +1,125 @@
// 0x9154_1 — fetch the bot's system face / emoji catalog.
//
// Mirrors Lagrange.Core's `FetchFullSysFacesService`. One server round-trip
// returns the entire pack list — common faces, "big"/super faces (the giant
// animated emoji), and the magic-face pack. The send path uses each emoji's
// `aniSticker*` metadata to pick the right wire encoding for a face id (see
// element-builder's makeFaceElem + sys-face-store).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbFaceEmoji,
OidbFetchSysFacesReq,
OidbFetchSysFacesResp,
} from '@snowluma/proto-defs/oidb-actions/sys-faces';
import { invokeOidb, type OidbSender } from '../../oidb-service';
/** A single system face / emoji. Field names match Lagrange's `SysFaceEntry`;
* `qSid` is the numeric face ID as a string. */
export interface SysFaceEntry {
qSid: string;
qDes: string;
emCode: string;
qCid: number | null;
aniStickerType: number | null;
aniStickerPackId: number | null;
aniStickerId: number | null;
url: string | null;
emojiNameAlias: string[];
aniStickerWidth: number | null;
aniStickerHeight: number | null;
}
/** One named pack of system faces (e.g. "经典", "MagicFace"). */
export interface SysFacePackEntry {
packName: string;
emojis: SysFaceEntry[];
}
function emojiToEntry(e: OidbFaceEmoji): SysFaceEntry {
return {
qSid: e.qSid ?? '',
qDes: e.qDes ?? '',
emCode: e.emCode ?? '',
qCid: e.qCid ?? null,
aniStickerType: e.aniStickerType ?? null,
aniStickerPackId: e.aniStickerPackId ?? null,
aniStickerId: e.aniStickerId ?? null,
url: e.url?.baseUrl ?? null,
emojiNameAlias: e.emojiNameAlias ?? [],
aniStickerWidth: e.aniStickerWidth ?? null,
aniStickerHeight: e.aniStickerHeight ?? null,
};
}
export namespace FetchSysFaces {
export const command = 0x9154;
export const subCommand = 1;
export type Params = Record<never, never>;
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, _p: Params): OidbFetchSysFacesReq => ({
field1: 0,
field2: 7,
field3: '0',
});
export const deserialize = (_ctx: Deps, body: OidbFetchSysFacesResp): SysFacePackEntry[] => {
const packs: SysFacePackEntry[] = [];
// common + special-big share the same content shape.
for (const content of [body.commonFace, body.specialBigFace]) {
for (const list of content?.emojiList ?? []) {
packs.push({
packName: list.emojiPackName ?? '',
emojis: (list.emojiDetail ?? []).map(emojiToEntry),
});
}
}
// Magic faces arrive as a single un-named bundle — Lagrange tags it
// "MagicFace" client-side, so we match for parity.
const magicEmojis = body.specialMagicFace?.field1?.emojiList ?? [];
if (magicEmojis.length > 0) {
packs.push({ packName: 'MagicFace', emojis: magicEmojis.map(emojiToEntry) });
}
return packs;
};
export const encode = (env: OidbBase<OidbFetchSysFacesReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbFetchSysFacesReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbFetchSysFacesResp> =>
protobuf_decode<OidbBase<OidbFetchSysFacesResp>>(bytes);
export const invoke = (deps: Deps, params: Params = {}): Promise<SysFacePackEntry[]> =>
invokeOidb(deps, FetchSysFaces, params);
}
/** Walk a pack list to find an emoji by its numeric face ID, or null. */
export function findFaceEntity(packs: SysFacePackEntry[], faceId: number): SysFaceEntry | null {
const idStr = String(faceId);
for (const pack of packs) {
for (const emoji of pack.emojis) {
if (emoji.qSid === idStr) return emoji;
}
}
return null;
}
/** True when `faceId` is an animated "super face" — has both aniStickerType
* and aniStickerPackId set, and is NOT the (1,1) pack (the regular static
* emojis). Matches Lagrange's `GetUniqueSuperQSids` filter. Super faces ride
* CommonElem serviceType 37 (QFaceExtra); the (1,1) ones ride serviceType 33. */
export function isSuperFaceEntry(emoji: SysFaceEntry): boolean {
if (emoji.aniStickerType == null || emoji.aniStickerPackId == null) return false;
return !(emoji.aniStickerType === 1 && emoji.aniStickerPackId === 1);
}
export function isSuperFaceId(packs: SysFacePackEntry[], faceId: number): boolean {
const emoji = findFaceEntity(packs, faceId);
return emoji !== null && isSuperFaceEntry(emoji);
}
+93
View File
@@ -0,0 +1,93 @@
// Process-wide cache of QQ's system-face catalog (fetched once via 0x9154_1),
// used by the send path to pick a face id's wire encoding. The catalog is the
// same for every account, so a single shared store is fetched lazily and reused.
//
// `classify` is synchronous (the element builder is sync); a face sent before
// the catalog is warm falls back to an id-range guess. `ensureWarm` kicks off
// the one-shot fetch — call it proactively at login so the first super-face
// send is already classified.
import { createLogger } from '@snowluma/common/logger';
import {
FetchSysFaces,
isSuperFaceEntry,
type SysFaceEntry,
type SysFacePackEntry,
} from './oidb-services/sys-faces/fetch-sys-faces';
import type { OidbSender } from './oidb-service';
const log = createLogger('SysFace');
/** Wire encoding a face id maps to. `classic` → legacy FaceElem; `small` →
* CommonElem serviceType 33 (QSmallFaceExtra); `super` → CommonElem
* serviceType 37 (QFaceExtra) for animated/super faces. */
export type FaceWire =
| { kind: 'classic' }
| { kind: 'small' }
| { kind: 'super'; packId: string; stickerId: string; stickerType: number };
/** Pure classification: a super face (per the catalog entry) → `super` with its
* pack/sticker ids; otherwise an id-range guess (`< 260` = classic, else
* small). Used both warm (entry from the catalog) and cold (entry undefined). */
export function faceWireFor(entry: SysFaceEntry | null | undefined, faceId: number): FaceWire {
if (entry && isSuperFaceEntry(entry)) {
return {
kind: 'super',
packId: String(entry.aniStickerPackId ?? 1),
stickerId: String(entry.aniStickerId ?? 0),
stickerType: entry.aniStickerType ?? 0,
};
}
return faceId < 260 ? { kind: 'classic' } : { kind: 'small' };
}
const RETRY_COOLDOWN_MS = 30_000;
class SysFaceStore {
private byId: Map<string, SysFaceEntry> | null = null;
private inflight: Promise<void> | null = null;
private lastFailedAt = 0;
/** Index a fetched catalog (also used by tests to seed without a network). */
load(packs: SysFacePackEntry[]): void {
this.byId = buildIndex(packs);
}
/** Synchronous classification. Falls back to an id-range guess when the
* catalog isn't warm yet or the id is unknown. */
classify(faceId: number): FaceWire {
return faceWireFor(this.byId?.get(String(faceId)), faceId);
}
/** Fire-and-forget one-shot warm. Coalesces concurrent callers; backs off
* briefly after a failure so a flaky fetch isn't hammered per message. */
ensureWarm(sender: OidbSender): void {
if (this.byId || this.inflight) return;
if (Date.now() - this.lastFailedAt < RETRY_COOLDOWN_MS) return;
this.inflight = FetchSysFaces.invoke(sender)
.then((packs) => {
this.load(packs);
log.info('system face catalog loaded: %d faces', this.byId?.size ?? 0);
})
.catch((err) => {
this.lastFailedAt = Date.now();
log.warn('failed to load system face catalog: %s', err instanceof Error ? err.message : String(err));
})
.finally(() => {
this.inflight = null;
});
}
}
function buildIndex(packs: SysFacePackEntry[]): Map<string, SysFaceEntry> {
const map = new Map<string, SysFaceEntry>();
for (const pack of packs) {
for (const emoji of pack.emojis) {
if (emoji.qSid) map.set(emoji.qSid, emoji);
}
}
return map;
}
/** Shared, process-wide catalog (the face set is account-independent). */
export const sysFaceStore = new SysFaceStore();
+241 -8
View File
@@ -80,6 +80,55 @@ export function parseQzoneJson<T>(text: string): T {
return JSON.parse(s.slice(start, end + 1)) as T;
}
function assertRichParams(richType?: number, richval?: string): void {
const hasRichType = richType !== undefined;
const hasRichval = richval !== undefined && richval.trim() !== '';
if (hasRichType !== hasRichval) {
throw new Error('richType and richval must be provided together');
}
if (richType !== undefined && (!Number.isInteger(richType) || richType < 1)) {
throw new Error('richType must be a positive integer');
}
}
function normalizeQzoneImageBase64(input: string): string {
let text = input.trim();
if (/^base64:\/\//i.test(text)) {
text = text.slice(9).trim();
}
if (/^data:/i.test(text)) {
const comma = text.indexOf(',');
if (comma === -1) {
throw new Error('imageBase64 data URI is missing base64 payload');
}
text = text.slice(comma + 1);
}
const compact = text.replace(/ /g, '+').replace(/[\r\n\t]/g, '');
if (!compact) {
throw new Error('imageBase64 is required');
}
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(compact)) {
throw new Error('imageBase64 is not valid base64');
}
const firstPadding = compact.indexOf('=');
if (firstPadding !== -1 && /[^=]/.test(compact.slice(firstPadding))) {
throw new Error('imageBase64 is not valid base64');
}
const unpadded = compact.replace(/=+$/, '');
const remainder = unpadded.length % 4;
if (remainder === 1) {
throw new Error('imageBase64 is not valid base64');
}
const base64 = unpadded + '='.repeat((4 - remainder) % 4);
const bytes = Buffer.from(base64, 'base64');
if (bytes.length === 0) {
throw new Error('imageBase64 is empty');
}
return base64;
}
/** Pick the largest picture URL variant a feed picture offers. */
function pickPicUrl(pic: RawPic): string | undefined {
return pic.url3 || pic.url2 || pic.url1 || pic.smallurl || undefined;
@@ -331,10 +380,14 @@ export interface QzonePublishResult {
}
/**
* Publish a text-only 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6
* CGI (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with
* Publish a 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6 CGI
* (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with
* `g_tk` in the query, on the bot's own space (`hostUin`).
*
* `richType` / `richval`: for image posts, set `richType=1` and pass the
* richval string(s) from {@link uploadQzoneImage} (multi-image: join with
* `\t`). Omit both for text-only posts.
*
* Errors PROPAGATE: a transport failure, a non-zero Qzone `code` (its error
* envelope, e.g. content rejected / rate-limited), or a success body that
* carries no `tid` all throw — we never report a publish as succeeded
@@ -344,6 +397,8 @@ export async function publishQzoneMsg(
cookieObject: Record<string, string>,
hostUin: string,
content: string,
richType?: number,
richval?: string,
): Promise<QzonePublishResult> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
@@ -351,6 +406,7 @@ export async function publishQzoneMsg(
if (!content) {
throw new Error('content is required');
}
assertRichParams(richType, richval);
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${bkn}`;
@@ -358,8 +414,8 @@ export async function publishQzoneMsg(
syn_tweet_verson: '1',
paramstr: '1',
pic_template: '',
richtype: '',
richval: '',
richtype: richType !== undefined ? String(richType) : '',
richval: richval ?? '',
special_url: '',
subrichtype: '',
con: content,
@@ -546,6 +602,172 @@ export async function setQzoneLike(
}
}
// ─────────────── 上传图片 (upload image) — cgi_upload_image ───────────────
// Uploads an image to Qzone's hosting and returns metadata for use in
// publish/comment. The image is POSTed as base64 to up.qzone.qq.com
// (bypassing the h5 proxy — the upload CGI is NOT behind
// h5.qzone.qq.com/proxy). Body is form-urlencoded with `base64=1` and the
// base64 payload in `picfile`. Response is a JSONP wrapper (parsed with the
// shared tolerant parser) carrying `albumid`, `lloc`, `height`, `width`,
// `type`, and `url`. The `richval` (for publish's richval param) is
// constructed as `,albumid,lloc,sloc,type,height,width,,height,width` — the
// double height/width mirrors the PHP impl. WRITE OP — rate-limit (though
// upload itself is not风控'd like publish, batching huge uploads is impolite).
// Confirmed against php-qzone/qzone.class.php:97-172.
interface RawUploadImageResponse {
code?: number;
subcode?: number;
message?: string;
data?: {
albumid?: string;
lloc?: string;
url?: string;
type?: number;
height?: number;
width?: number;
};
}
/** Result of uploading an image to Qzone. */
export interface QzoneUploadImageResult {
[key: string]: JsonValue;
/** Richval string for publish's `richval` param (multi-image: join with `\t`). */
richval: string;
/** Direct URL to the uploaded image. */
url: string;
albumid: string;
lloc: string;
type: number;
width: number;
height: number;
}
/**
* Upload an image from a source (file:// / http:// / base64://) to Qzone
* hosting. Loads the image via {@link loadBinarySource}, converts to base64,
* and uploads via {@link uploadQzoneImage}.
*
* `source` supports:
* - `file://` local file path
* - `http://` or `https://` remote URL
* - `base64://` base64-encoded data (with or without data-URI prefix)
*
* Errors PROPAGATE from both the load step and the upload step.
*/
export async function uploadQzoneImageFromSource(
cookieObject: Record<string, string>,
hostUin: string,
source: string,
): Promise<QzoneUploadImageResult> {
if (/^base64:\/\//i.test(source)) {
return uploadQzoneImage(cookieObject, hostUin, source);
}
// Import loadBinarySource at function level to avoid circular deps
const { loadBinarySource } = await import('../highway/utils');
const loaded = await loadBinarySource(source, 'qzone-image');
const base64 = Buffer.from(loaded.bytes).toString('base64');
return uploadQzoneImage(cookieObject, hostUin, base64);
}
/**
* Upload an image (as base64) to Qzone hosting via up.qzone.qq.com's
* cgi_upload_image CGI. Returns metadata including the `richval` string
* (for use in {@link publishQzoneMsg}'s richval param) and the direct URL.
* Multi-image publish: call this once per image and join the richval strings
* with `\t`.
*
* `imageBase64` is the raw base64-encoded image bytes; a data-URI prefix is
* tolerated and stripped. Errors PROPAGATE: invalid base64, a transport
* failure, a non-zero Qzone `code`/`subcode`, or a success body missing
* required fields all throw.
*/
export async function uploadQzoneImage(
cookieObject: Record<string, string>,
hostUin: string,
imageBase64: string,
): Promise<QzoneUploadImageResult> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
}
if (!imageBase64) {
throw new Error('imageBase64 is required');
}
const base64 = normalizeQzoneImageBase64(imageBase64);
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || '';
const bkn = getBknFromCookie(cookieObject);
const url = `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${bkn}`;
const body = new URLSearchParams({
filename: 'filename',
uin: hostUin,
skey,
zzpaneluin: hostUin,
p_uin: hostUin,
p_skey: pskey,
uploadtype: '1',
albumtype: '7',
exttype: '0',
refer: 'shuoshuo',
output_type: 'jsonhtml',
charset: 'utf-8',
output_charset: 'utf-8',
upload_hd: '1',
hd_width: '2048',
hd_height: '10000',
hd_quality: '96',
backUrls: `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${bkn}`,
base64: '1',
jsonhtml_callback: 'callback',
picfile: base64,
qzreferrer: `https://user.qzone.qq.com/${hostUin}/main`,
}).toString();
const text = await RequestUtil.HttpGetText(url, 'POST', body, {
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
});
// Response is `<script>frameElement.callback(...JSON...);</script>` — slice
// from the first `{` to the last `}` (same as parseQzoneJson, but the
// wrapper shape differs slightly).
let jsonText = text.trim();
const callbackStart = jsonText.indexOf('callback');
if (callbackStart !== -1) {
jsonText = jsonText.slice(callbackStart);
}
const data = parseQzoneJson<RawUploadImageResponse>(jsonText);
if (typeof data.code === 'number' && data.code !== 0) {
log.warn('uploadQzoneImage: non-zero code (uin=%s) code=%d msg=%s', hostUin, data.code, data.message);
throw new Error(`qzone upload image failed: code=${data.code} ${data.message ?? ''}`.trim());
}
if (typeof data.subcode === 'number' && data.subcode !== 0) {
log.warn('uploadQzoneImage: non-zero subcode (uin=%s) subcode=%d msg=%s', hostUin, data.subcode, data.message);
throw new Error(`qzone upload image failed: subcode=${data.subcode} ${data.message ?? ''}`.trim());
}
if (!data.data || !data.data.albumid || !data.data.lloc || !data.data.url) {
log.warn('uploadQzoneImage: missing required fields in response (uin=%s)', hostUin);
throw new Error('上传图片失败:响应缺少必要字段');
}
const { albumid, lloc, url: imageUrl, type, height, width } = data.data;
const sloc = lloc; // lloc and sloc are identical in the wire format
const richval = `,${albumid},${lloc},${sloc},${type ?? 0},${height ?? 0},${width ?? 0},,${height ?? 0},${width ?? 0}`;
return {
richval,
url: imageUrl,
albumid,
lloc,
type: type ?? 0,
width: width ?? 0,
height: height ?? 0,
};
}
// ─────────────── 评论说说 (comment) — emotion_cgi_re_feeds ───────────────
// Posts a comment on a 说说 owned by `hostUin`, as the bot (`selfUin`). Same
// form-POST mechanics + param family (paramstr/richtype/richval) as
@@ -576,7 +798,15 @@ export interface QzoneCommentResult {
/**
* Comment on a 说说 (`tid`, owned by `hostUin`) as the bot (`selfUin`) via
* taotao.qzone.qq.com's emotion_cgi_re_feeds CGI (proxied through h5.qzone).
* taotao.qzone.qq.com's emotion_cgi_re_feeds CGI (proxied through
* h5.qzone.qq.com, matching php-qzone's working request).
*
* `richType` / `richval`: for image comments, set `richType=1` and pass the
* direct image URL from {@link uploadQzoneImage}'s `url` field (NOT the
* richval string — comment uses the direct URL, unlike publish which uses
* richval). Multi-image comments use direct URLs joined with `\t`. Omit both
* for text-only comments.
*
* Resolves with the new comment id (best-effort) on success; THROWS on a
* transport failure or a non-zero Qzone `code`/`subcode` (e.g. comments
* disabled, no permission, or auth failure).
@@ -587,6 +817,8 @@ export async function commentQzoneMsg(
hostUin: string,
tid: string,
content: string,
richType?: number,
richval?: string,
): Promise<QzoneCommentResult> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
@@ -597,6 +829,7 @@ export async function commentQzoneMsg(
if (!content) {
throw new Error('content is required');
}
assertRichParams(richType, richval);
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_re_feeds?g_tk=${bkn}`;
@@ -606,14 +839,14 @@ export async function commentQzoneMsg(
inCharset: 'utf-8',
outCharset: 'utf-8',
hostUin,
format: 'fs',
format: 'json',
ref: 'feeds',
topicId: `${hostUin}_${tid}__1`,
feedsType: '100',
private: '0',
paramstr: '1',
richtype: '',
richval: '',
richtype: richType !== undefined ? String(richType) : '',
richval: richval ?? '',
isSignIn: '',
uin: selfUin,
content,
@@ -0,0 +1,67 @@
import { afterAll, describe, expect, it } from 'vitest';
import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'fs';
import os from 'os';
import path from 'path';
import { AUDIO_OUT_FORMATS, convertAudioBytes, isAudioOutFormat } from '@snowluma/protocol/highway/ffmpeg-addon';
// convertAudioBytes is the pure (#165) transcode seam: write input → addon
// convertFile → read output as base64 → always clean up temp files. The native
// addon is file-based and can't run in CI, so a fake addon stands in.
const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'sl-audio-test-'));
afterAll(() => rmSync(tmpDir, { recursive: true, force: true }));
/** Fake addon: writes deterministic bytes to the output path and reports ok. */
const fakeOk = {
convertFile: async (_in: string, out: string, _fmt: string) => {
writeFileSync(out, Buffer.from('WAVDATA')); // stand-in converted payload
return { success: true };
},
};
describe('isAudioOutFormat / AUDIO_OUT_FORMATS', () => {
it('accepts exactly NapCat\'s allowlist', () => {
expect([...AUDIO_OUT_FORMATS]).toEqual(['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac']);
expect(isAudioOutFormat('wav')).toBe(true);
expect(isAudioOutFormat('WAV')).toBe(false); // case-sensitive
expect(isAudioOutFormat('opus')).toBe(false);
expect(isAudioOutFormat('')).toBe(false);
});
});
describe('convertAudioBytes', () => {
it('transcodes and returns base64 + size of the addon output', async () => {
const r = await convertAudioBytes(new Uint8Array([1, 2, 3]), 'wav', { addon: fakeOk, tmpDir });
expect(Buffer.from(r.base64, 'base64').toString()).toBe('WAVDATA');
expect(r.size).toBe('WAVDATA'.length);
});
it('rejects an unsupported format before touching the addon', async () => {
let called = false;
const spy = { convertFile: async () => { called = true; return { success: true }; } };
await expect(convertAudioBytes(new Uint8Array([1]), 'opus', { addon: spy, tmpDir })).rejects.toThrow(/unsupported out_format/);
expect(called).toBe(false);
});
it('throws and cleans up when the addon reports failure', async () => {
const fakeFail = { convertFile: async () => ({ success: false }) };
await expect(convertAudioBytes(new Uint8Array([9]), 'mp3', { addon: fakeFail, tmpDir })).rejects.toThrow(/conversion failed/);
// no leftover temp files for this run
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.mp3') || n.endsWith('.in'));
expect(leftover).toEqual([]);
});
it('rejects (and cleans up) when the output exceeds the cap', async () => {
await expect(
convertAudioBytes(new Uint8Array([1]), 'wav', { addon: fakeOk, tmpDir, maxOutputBytes: 3 }),
).rejects.toThrow(/too large/);
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.wav') || n.endsWith('.in'));
expect(leftover).toEqual([]);
});
it('cleans up the temp input + output on success too', async () => {
await convertAudioBytes(new Uint8Array([4, 5]), 'flac', { addon: fakeOk, tmpDir });
const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.flac') || n.endsWith('.in'));
expect(leftover).toEqual([]);
});
});
+104
View File
@@ -0,0 +1,104 @@
import { describe, it, expect } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element';
import {
FetchSysFaces,
findFaceEntity,
isSuperFaceEntry,
isSuperFaceId,
type SysFaceEntry,
type SysFacePackEntry,
} from '../src/oidb-services/sys-faces/fetch-sys-faces';
import { faceWireFor, sysFaceStore } from '../src/sys-face-store';
import { buildSendElems } from '../src/element-builder';
function entry(qSid: string, aniStickerType: number | null, aniStickerPackId: number | null, aniStickerId: number | null): SysFaceEntry {
return {
qSid, qDes: '', emCode: '', qCid: null,
aniStickerType, aniStickerPackId, aniStickerId,
url: null, emojiNameAlias: [], aniStickerWidth: null, aniStickerHeight: null,
};
}
// 392 is a real non-(1,1) super face; 424 is a real (1,1) "new small" face.
const CATALOG: SysFacePackEntry[] = [
{ packName: '经典', emojis: [entry('14', null, null, null)] },
{ packName: '超级表情', emojis: [
entry('392', 3, 2, 38), // super → CommonElem 37
entry('424', 1, 1, 52), // (1,1) → small → CommonElem 33
entry('358', 2, 1, 33), // super (packId 1 but type 2) → CommonElem 37
] },
];
describe('isSuperFaceEntry / isSuperFaceId — the (1,1) rule', () => {
it('treats only non-(1,1) aniSticker faces as super', () => {
expect(isSuperFaceEntry(entry('x', 3, 2, 1))).toBe(true);
expect(isSuperFaceEntry(entry('x', 2, 1, 1))).toBe(true); // type≠1
expect(isSuperFaceEntry(entry('x', 1, 2, 1))).toBe(true); // pack≠1
expect(isSuperFaceEntry(entry('x', 1, 1, 52))).toBe(false); // the (1,1) pack
expect(isSuperFaceEntry(entry('x', null, null, null))).toBe(false); // not aniSticker
});
it('isSuperFaceId walks the packs by id', () => {
expect(isSuperFaceId(CATALOG, 392)).toBe(true);
expect(isSuperFaceId(CATALOG, 424)).toBe(false);
expect(isSuperFaceId(CATALOG, 14)).toBe(false);
expect(isSuperFaceId(CATALOG, 99999)).toBe(false); // unknown
});
it('findFaceEntity returns the matching emoji or null', () => {
expect(findFaceEntity(CATALOG, 392)?.qSid).toBe('392');
expect(findFaceEntity(CATALOG, 99999)).toBeNull();
});
});
describe('faceWireFor — classification', () => {
it('super face → super wire with pack/sticker ids', () => {
expect(faceWireFor(entry('392', 3, 2, 38), 392)).toEqual({
kind: 'super', packId: '2', stickerId: '38', stickerType: 3,
});
});
it('(1,1) face → small/classic by id range, not super', () => {
expect(faceWireFor(entry('424', 1, 1, 52), 424)).toEqual({ kind: 'small' });
});
it('cold (no catalog entry) → id-range guess', () => {
expect(faceWireFor(undefined, 14)).toEqual({ kind: 'classic' }); // < 260
expect(faceWireFor(undefined, 424)).toEqual({ kind: 'small' }); // ≥ 260
expect(faceWireFor(null, 100)).toEqual({ kind: 'classic' });
});
});
describe('FetchSysFaces.deserialize', () => {
it('flattens common + big + magic packs', () => {
const packs = FetchSysFaces.deserialize({} as never, {
commonFace: { emojiList: [{ emojiPackName: '经典', emojiDetail: [{ qSid: '14' }] }] },
specialBigFace: { emojiList: [{ emojiPackName: '超级', emojiDetail: [{ qSid: '392', aniStickerType: 3, aniStickerPackId: 2 }] }] },
specialMagicFace: { field1: { emojiList: [{ qSid: '999' }] } },
} as never);
expect(packs.map((p) => p.packName)).toEqual(['经典', '超级', 'MagicFace']);
expect(packs[1].emojis[0].aniStickerType).toBe(3);
});
});
describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () => {
const ctx = { bridge: {} as never };
it('encodes each face id by its catalog classification', async () => {
sysFaceStore.load(CATALOG); // warm → ensureWarm no-ops, classify uses the catalog
const [superElem] = await buildSendElems([{ type: 'face', faceId: 392 }], ctx);
expect(superElem.commonElem?.serviceType).toBe(37);
const big = protobuf_decode<QFaceExtra>(superElem.commonElem!.pbElem!);
expect(big.qsid).toBe(392);
expect(big.packId).toBe('2');
expect(big.stickerId).toBe('38');
const [smallElem] = await buildSendElems([{ type: 'face', faceId: 424 }], ctx);
expect(smallElem.commonElem?.serviceType).toBe(33);
const small = protobuf_decode<QSmallFaceExtra>(smallElem.commonElem!.pbElem!);
expect(small.faceId).toBe(424);
const [classicElem] = await buildSendElems([{ type: 'face', faceId: 14 }], ctx);
expect(classicElem.face?.index).toBe(14);
});
});
@@ -0,0 +1,105 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { uploadQzoneImage, uploadQzoneImageFromSource } from '../../src/web/qzone';
import { RequestUtil } from '../../src/web/request-util';
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' };
const expectedGtk = (() => {
let h = 5381;
for (const c of 'PSK') h += (h << 5) + c.charCodeAt(0);
return (h & 0x7fffffff).toString();
})();
const successBody = `<script>frameElement.callback({
"code": 0,
"subcode": 0,
"data": {
"albumid": "12345",
"lloc": "abc123",
"url": "https://example.qzone.qq.com/image.jpg",
"type": 22,
"height": 800,
"width": 600
}
});</script>`;
describe('qzone / uploadQzoneImage', () => {
afterEach(() => vi.restoreAllMocks());
it('POSTs the upload form and returns richval + direct url', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody);
const out = await uploadQzoneImage(cookies, '10000', 'AQID');
expect(out).toEqual({
richval: ',12345,abc123,abc123,22,800,600,,800,600',
url: 'https://example.qzone.qq.com/image.jpg',
albumid: '12345',
lloc: 'abc123',
type: 22,
width: 600,
height: 800,
});
const [url, method, body, headers] = spy.mock.calls[0]!;
expect(url).toBe(`https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${expectedGtk}`);
expect(method).toBe('POST');
const h = headers as Record<string, string>;
expect(h['Content-Type']).toBe('application/x-www-form-urlencoded');
expect(h.Cookie).toContain('p_skey=PSK');
expect(h.Cookie).toContain('skey=SK');
const form = new URLSearchParams(body as string);
expect(form.get('uin')).toBe('10000');
expect(form.get('p_uin')).toBe('10000');
expect(form.get('p_skey')).toBe('PSK');
expect(form.get('base64')).toBe('1');
expect(form.get('jsonhtml_callback')).toBe('callback');
expect(form.get('picfile')).toBe('AQID');
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000/main');
});
it('accepts base64:// data-URI sources and strips the prefix before upload', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody);
await uploadQzoneImageFromSource(cookies, '10000', 'base64://data:image/png;base64,AQID');
const form = new URLSearchParams(spy.mock.calls[0]![2] as string);
expect(form.get('picfile')).toBe('AQID');
});
it('defaults optional image metadata to 0 when the upload succeeds without it', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
'callback({"code":0,"data":{"albumid":"12345","lloc":"abc123","url":"https://example.qzone.qq.com/image.jpg"}});',
);
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).resolves.toMatchObject({
richval: ',12345,abc123,abc123,0,0,0,,0,0',
type: 0,
width: 0,
height: 0,
});
});
it('rejects invalid base64 before any request', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
await expect(uploadQzoneImage(cookies, '10000', 'not base64?')).rejects.toThrow('valid base64');
expect(spy).not.toHaveBeenCalled();
});
it('throws on non-zero code or subcode from Qzone', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
spy.mockResolvedValueOnce('callback({"code":-1,"message":"upload failed"});');
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('code=-1');
spy.mockResolvedValueOnce('callback({"code":0,"subcode":-2,"message":"sub failed"});');
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('subcode=-2');
});
it('throws when the success response lacks required upload fields', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('callback({"code":0,"data":{"albumid":"12345"}});');
await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('响应缺少必要字段');
});
});
+39 -1
View File
@@ -222,6 +222,19 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => {
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000');
});
it('threads image richType/richval into the publish form', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
'{"code":0,"t1_tid":"NEWTID","t1_time":"1700000000"}',
);
const richval = ',12345,abc,abc,22,800,600,,800,600\t,12346,def,def,22,640,480,,640,480';
await publishQzoneMsg(cookies, '10000', 'with images', 1, richval);
const form = new URLSearchParams(spy.mock.calls[0]![2] as string);
expect(form.get('richtype')).toBe('1');
expect(form.get('richval')).toBe(richval);
});
it('falls back to tid/now for alternate client builds', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"tid":"ALT","now":1700000001}');
await expect(publishQzoneMsg(cookies, '10000', 'hi')).resolves.toEqual({ tid: 'ALT', time: 1700000001 });
@@ -233,6 +246,13 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => {
expect(spy).not.toHaveBeenCalled();
});
it('rejects incomplete publish rich params before any request', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
await expect(publishQzoneMsg(cookies, '10000', 'hi', 1)).rejects.toThrow('richType and richval');
await expect(publishQzoneMsg(cookies, '10000', 'hi', undefined, ',123')).rejects.toThrow('richType and richval');
expect(spy).not.toHaveBeenCalled();
});
it('throws on a non-zero qzone code (rejected/rate-limited)', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-10000,"message":"too frequent"}');
await expect(publishQzoneMsg(cookies, '10000', 'hi')).rejects.toThrow('code=-10000');
@@ -378,7 +398,7 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => {
expect(form.get('uin')).toBe('10000');
expect(form.get('hostUin')).toBe('20002');
expect(form.get('content')).toBe('说得好 & 顶');
expect(form.get('format')).toBe('fs');
expect(form.get('format')).toBe('json');
// qzreferrer carries the commenter's own space (matches the impls)
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000');
// the re_feeds param family (3/3 impls) the publish sibling also sends
@@ -387,6 +407,17 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => {
expect(form.get('paramstr')).toBe('1');
});
it('threads image direct-url richval into the comment form', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"commentid":987}');
const richval = 'https://example.qzone.qq.com/a.jpg\thttps://example.qzone.qq.com/b.jpg';
await commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'pics', 1, richval);
const form = new URLSearchParams(spy.mock.calls[0]![2] as string);
expect(form.get('richtype')).toBe('1');
expect(form.get('richval')).toBe(richval);
});
it('resolves with empty comment_id on success when the response carries no id (field name varies)', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0}');
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi')).resolves.toEqual({ comment_id: '' });
@@ -404,6 +435,13 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => {
expect(spy).not.toHaveBeenCalled();
});
it('rejects incomplete comment rich params before any request', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi', 1)).rejects.toThrow('richType and richval');
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi', undefined, 'https://example.com/img.jpg')).rejects.toThrow('richType and richval');
expect(spy).not.toHaveBeenCalled();
});
it('throws on a non-zero code (comments disabled / no permission)', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"forbidden"}');
await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi')).rejects.toThrow('comment failed: code=-3000');
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.10.4",
"version": "1.11.0",
"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.4",
"version": "1.11.0",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.10.4",
"version": "1.11.0",
"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.4",
"version": "1.11.0",
"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.4",
"version": "1.11.0",
"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.4",
"version": "1.11.0",
"type": "module",
"scripts": {
"dev": "vite",
+6 -1
View File
@@ -7,6 +7,8 @@ import { LoginPage } from '@/components/pages/login-page';
import { ChangePasswordPage } from '@/components/pages/change-password-page';
import { ConsentPage } from '@/components/pages/consent-page';
import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api';
import { DebugTaskProvider } from '@/contexts/DebugTaskContext';
import { TaskBadge } from '@/components/debug/task-badge';
import type { AgreementsPayload } from '@/lib/api/types';
import { appRouter } from '@/router';
@@ -132,7 +134,10 @@ function AuthBoundary() {
return (
<ApiProvider client={client}>
<TooltipProvider delayDuration={150}>{view}</TooltipProvider>
<DebugTaskProvider>
<TooltipProvider delayDuration={150}>{view}</TooltipProvider>
<TaskBadge />
</DebugTaskProvider>
</ApiProvider>
);
}
@@ -0,0 +1,382 @@
// ActionTester — the debug console's centrepiece. Pick an account + action and
// invoke it; params render as role-driven smart controls (pickers, switches,
// file sources) with a raw-JSON escape hatch. Read-only actions are badged
// green, side-effecting ones amber; destructive ones confirm first. Stream API
// actions invoke over the streaming transport and render frames live (tracked
// in the app-level task registry). Every call lands in localStorage history
// with one-click replay. Responses render in a collapsible JsonTree.
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { AlertTriangle, FlaskConical, History, Loader2, Play, RotateCcw, ShieldCheck, Trash2, Zap } from 'lucide-react';
import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Picker } from '@/components/ui/picker';
import { JsonTree } from '@/components/ui/json-tree';
import { ParamField } from '@/components/debug/param-field';
import { Segmented } from '@/components/debug/segmented';
import { useApi } from '@/lib/api';
import { useDebugTasks } from '@/contexts/DebugTaskContext';
import { clearHistory, loadHistory, pushHistory, type InvokeRecord } from '@/lib/debug-history';
import { cn } from '@/lib/utils';
import type { DebugActionDoc, DebugStreamFrame, QQInfo } from '@/types';
const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm';
// Name patterns for genuinely destructive actions → require a confirm. False
// positives just add one extra click; false negatives skip a confirm — both low
// stakes (the amber banner already warns that any write is real).
const DESTRUCTIVE_RE = /(kick|ban|mute|recall|withdraw|delete|del_|dismiss|disband|leave|quit|remove|revoke)/i;
function coerceParam(type: string, raw: string): unknown {
if (raw === '') return undefined;
if (/int|uint|number|messageId/i.test(type)) {
const n = Number(raw);
return Number.isFinite(n) ? n : raw;
}
if (type === 'bool' || type === 'boolean') return raw === 'true' || raw === '1';
if (type === 'message') {
const t = raw.trim();
if ((t.startsWith('[') && t.endsWith(']')) || (t.startsWith('{') && t.endsWith('}'))) {
try { return JSON.parse(t); } catch { /* fall through to literal */ }
}
return raw;
}
return raw;
}
function Field({ label, children }: { label: ReactNode; children: ReactNode }) {
return (
<label className="flex flex-col gap-1.5">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
{children}
</label>
);
}
export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInfo[]; docs: DebugActionDoc[]; presetAction?: { name: string; nonce: number } }) {
const api = useApi();
const tasks = useDebugTasks();
const [uin, setUin] = useState('');
const [actionName, setActionName] = useState('');
const [fields, setFields] = useState<Record<string, string>>({});
const [paramMode, setParamMode] = useState<'form' | 'json'>('form');
const [rawJson, setRawJson] = useState('{}');
const [invoking, setInvoking] = useState(false);
const [result, setResult] = useState<DebugStreamFrame | { error: string } | null>(null);
const [frames, setFrames] = useState<DebugStreamFrame[]>([]);
const [confirmOpen, setConfirmOpen] = useState(false);
const [history, setHistory] = useState<InvokeRecord[]>([]);
const [showHistory, setShowHistory] = useState(false);
const streamAbort = useRef<AbortController | null>(null);
useEffect(() => { setHistory(loadHistory()); }, []);
useEffect(() => { if (accounts[0] && !uin) setUin(accounts[0].uin); }, [accounts, uin]);
// Prefill from the API browser's 试一下 (nonce lets the same action re-trigger).
useEffect(() => {
if (presetAction) { setActionName(presetAction.name); setParamMode('form'); setResult(null); setFrames([]); setShowHistory(false); }
}, [presetAction]);
const doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]);
const effectiveMode = paramMode === 'json' || !doc ? 'json' : 'form';
const isStream = !!doc?.stream;
const isDestructive = DESTRUCTIVE_RE.test(actionName);
const actionOptions = useMemo(
() => docs.map((d) => ({ value: d.name, label: d.name, sub: d.summary })),
[docs],
);
const buildParams = (): Record<string, unknown> | { __error: string } => {
if (effectiveMode === 'json') {
let parsed: unknown;
try { parsed = JSON.parse(rawJson || '{}'); } catch { return { __error: 'params JSON 无效' }; }
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { __error: 'params 必须是对象' };
return parsed as Record<string, unknown>;
}
const out: Record<string, unknown> = {};
if (doc) for (const p of doc.params) {
const v = coerceParam(p.type, fields[p.name] ?? '');
if (v !== undefined) out[p.name] = v;
}
return out;
};
const runInvoke = async () => {
if (!uin) { setResult({ error: '请选择账号' }); return; }
if (!actionName.trim()) { setResult({ error: '请填写 action' }); return; }
const params = buildParams();
if ('__error' in params) { setResult({ error: params.__error as string }); return; }
setInvoking(true);
setResult(null);
setFrames([]);
const startedAt = Date.now();
if (isStream) {
const ac = new AbortController();
streamAbort.current = ac;
const taskId = tasks.start({ kind: 'stream', label: `${actionName} @ ${uin}`, progress: undefined, cancel: () => ac.abort() });
let last: DebugStreamFrame | null = null;
try {
await api.debug.invokeStream(uin, actionName.trim(), params, (frame) => {
last = frame;
setFrames((prev) => [...prev, frame]);
const d = frame.data as { type?: string; progress?: number; transferred?: number; total?: number } | undefined;
if (d && typeof d.progress === 'number') tasks.update(taskId, { progress: d.progress });
else if (d && typeof d.transferred === 'number' && typeof d.total === 'number' && d.total > 0) tasks.update(taskId, { progress: d.transferred / d.total });
}, ac.signal);
// A clean success requires the terminal frame (status ok AND the
// NapCat terminal marker data.type==='response') — a stream that closed
// without emitting its terminator must not read as success.
const term = last as DebugStreamFrame | null;
const ok = !!term && term.status === 'ok' && (term.data as { type?: string } | undefined)?.type === 'response';
setResult(last);
tasks.finish(taskId, ok ? 'done' : 'failed');
setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok, ms: Date.now() - startedAt, stream: true }));
} catch (e) {
const aborted = ac.signal.aborted;
const msg = e instanceof Error ? e.message : '流式调用失败';
if (!aborted) setResult({ error: msg });
tasks.finish(taskId, aborted ? 'canceled' : 'failed', msg);
setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: false, ms: Date.now() - startedAt, stream: true }));
} finally {
streamAbort.current = null;
setInvoking(false);
}
return;
}
try {
const res = await api.debug.invoke(uin, actionName.trim(), params);
setResult(res);
setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: res.status === 'ok', ms: Date.now() - startedAt }));
} catch (e) {
setResult({ error: e instanceof Error ? e.message : '调用失败' });
setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: false, ms: Date.now() - startedAt }));
} finally {
setInvoking(false);
}
};
const onExecute = () => {
if (isDestructive) { setConfirmOpen(true); return; }
void runInvoke();
};
const replay = (rec: InvokeRecord) => {
setUin(rec.uin);
setActionName(rec.action);
setParamMode('json');
setRawJson(JSON.stringify(rec.params, null, 2));
setResult(null);
setFrames([]);
setShowHistory(false);
};
const resultFailed = !!result && ('error' in result || result.status === 'failed');
return (
<div className="grid grid-cols-1 gap-6 xl:grid-cols-12">
{/* tester */}
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35 }}
className={cn(cardCls, 'flex flex-col gap-5 p-6 xl:col-span-7')}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2.5">
<FlaskConical className="h-[18px] w-[18px] text-primary" />
<h2 className="text-[15px] font-semibold tracking-tight">Action 测试台</h2>
</div>
<button type="button" onClick={() => setShowHistory((v) => !v)}
className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground">
<History className="h-3.5 w-3.5" /> 历史 {history.length > 0 && <span className="tabular-nums">{history.length}</span>}
</button>
</div>
<div className="flex items-start gap-2 rounded-xl bg-amber-500/10 px-3 py-2 text-[12px] leading-relaxed text-amber-700 dark:text-amber-300">
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>调用会<strong className="font-semibold">真实生效</strong>(真发消息 / 真踢人等),请谨慎。</span>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<Field label="账号">
<Select value={uin} onChange={(e) => setUin(e.target.value)}>
{accounts.length === 0 && <option value="">(无在线账号)</option>}
{accounts.map((a) => <option key={a.uin} value={a.uin}>{a.nickname || a.uin}</option>)}
</Select>
</Field>
<Field label="Action">
<Picker
ariaLabel="选择 action"
value={actionName}
onChange={(v) => { setActionName(v); setResult(null); setFrames([]); }}
options={actionOptions}
placeholder="search action…"
validateRaw={(s) => s.trim().length > 0}
/>
</Field>
</div>
{doc && (
<div className="-mt-1 flex flex-wrap items-center gap-2 text-[12px] text-muted-foreground">
{doc.readOnly
? <span className="inline-flex items-center gap-1 rounded-md bg-emerald-500/12 px-1.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:text-emerald-300"><ShieldCheck className="h-3 w-3" /> 只读·安全</span>
: <span className="inline-flex items-center gap-1 rounded-md bg-amber-500/12 px-1.5 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300"><AlertTriangle className="h-3 w-3" /> 有副作用</span>}
{isStream && <span className="inline-flex items-center gap-1 rounded-md bg-primary/12 px-1.5 py-0.5 text-[11px] font-medium text-primary"><Zap className="h-3 w-3" /> 流式</span>}
<span>{doc.summary}{doc.returns ? <> · 返回 <code className="font-mono text-[11px]">{doc.returns}</code></> : null}</span>
</div>
)}
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">参数</span>
<Segmented value={effectiveMode} onChange={setParamMode}
options={[{ value: 'form', label: '表单' }, { value: 'json', label: 'JSON' }]} />
</div>
{effectiveMode === 'json' ? (
<Textarea className="min-h-28 rounded-xl font-mono text-xs" value={rawJson}
onChange={(e) => setRawJson(e.target.value)} placeholder='{ "group_id": 12345, "message": "hi" }' />
) : (
<div className="flex flex-col gap-3.5">
{doc!.params.length === 0 && <p className="text-[12px] text-muted-foreground">该接口无参数。</p>}
{doc!.params.map((p) => (
<Field key={p.name} label={<>{p.name}<span className="ml-1 font-normal text-muted-foreground/70">{p.type}{p.required ? ' · 必填' : ''}</span></>}>
<ParamField param={p} value={fields[p.name] ?? ''} uin={uin} groupContext={fields['group_id'] ?? ''}
onChange={(v) => setFields((f) => {
const next = { ...f, [p.name]: v };
// Changing the group resets any sibling member picker — its
// old uin belongs to the previous group.
if (p.role === 'group_id' && doc) for (const mp of doc.params) if (mp.role === 'member_id') next[mp.name] = '';
return next;
})} />
{p.desc && <span className="text-[11px] text-muted-foreground/70">{p.desc}</span>}
</Field>
))}
{doc!.invariants && doc!.invariants.length > 0 && (
<p className="text-[11px] text-muted-foreground/70">约束:{doc!.invariants.join(';')}</p>
)}
</div>
)}
<div className="flex gap-2">
<button type="button" onClick={onExecute} disabled={invoking}
className="inline-flex h-11 flex-1 items-center justify-center gap-2 rounded-xl bg-primary text-[15px] font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.99] disabled:opacity-50">
{invoking ? <Loader2 className="h-4 w-4 animate-spin" /> : isStream ? <Zap className="h-4 w-4" /> : <Play className="h-4 w-4" />}
{invoking ? '执行中…' : isStream ? '流式执行' : '执行'}
</button>
{invoking && isStream && streamAbort.current && (
<button type="button" onClick={() => streamAbort.current?.abort()}
className="inline-flex h-11 items-center justify-center gap-1.5 rounded-xl border border-border px-4 text-sm font-medium text-muted-foreground hover:bg-muted">
取消
</button>
)}
</div>
</motion.section>
{/* response / frames / history */}
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.05 }}
className={cn(cardCls, 'flex min-h-[20rem] flex-col gap-3 p-6 xl:col-span-5')}
>
{showHistory ? (
<>
<div className="flex items-center justify-between">
<h3 className="text-[15px] font-semibold tracking-tight">调用历史</h3>
{history.length > 0 && (
<button type="button" onClick={() => { clearHistory(); setHistory([]); }}
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-destructive"><Trash2 className="h-3.5 w-3.5" /> 清空</button>
)}
</div>
<div className="flex flex-col gap-1 overflow-auto">
{history.length === 0 ? <p className="py-8 text-center text-sm text-muted-foreground">暂无历史</p> : history.map((rec) => (
<button key={rec.id} type="button" onClick={() => replay(rec)}
className="group flex items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[13px] hover:bg-muted/50">
<span className={cn('h-1.5 w-1.5 shrink-0 rounded-full', rec.ok ? 'bg-emerald-500' : 'bg-destructive')} />
<span className="min-w-0 flex-1 truncate font-mono">{rec.action}</span>
<span className="shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums">{rec.uin}</span>
<span className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"><RotateCcw className="h-3.5 w-3.5" /></span>
</button>
))}
</div>
</>
) : (
<>
<div className="flex items-center gap-2">
<h3 className="text-[15px] font-semibold tracking-tight">{isStream ? '帧流' : '响应'}</h3>
{result && (
<span className={cn('text-xs font-medium', resultFailed ? 'text-destructive' : 'text-success')}>
{resultFailed ? '失败' : '成功'}
{!('error' in result) && resultFailed && (result.message || result.wording) ? ` · ${result.message || result.wording}` : ''}
</span>
)}
</div>
{frames.length > 0 && (
<div className="flex flex-col gap-1.5 overflow-auto">
<span className="text-xs text-muted-foreground tabular-nums">{frames.length} 帧</span>
{frames.map((f, i) => {
// On a failed frame the action's `data` is replaced with an
// {type:'error'} marker and the reason moves to message/wording
// — render the whole frame so the reason stays visible.
const failed = f.status === 'failed' || (f.data as { type?: string } | undefined)?.type === 'error';
return (
<div key={i} className="rounded-lg border border-border/50 bg-muted/20 p-2">
<JsonTree data={failed ? f : (f.data ?? f)} maxHeight="12rem" />
</div>
);
})}
</div>
)}
{result && !('error' in result) && frames.length === 0 && (
<JsonTree data={result} maxHeight="28rem" />
)}
{result && 'error' in result && (
<div className="rounded-xl bg-destructive/10 p-3 text-sm text-destructive">{result.error}</div>
)}
{!result && frames.length === 0 && (
<p className="flex flex-1 items-center justify-center py-12 text-center text-sm text-muted-foreground">执行后在此查看结果</p>
)}
</>
)}
</motion.section>
{confirmOpen && (
<ConfirmDestructive
action={actionName}
uin={uin}
onCancel={() => setConfirmOpen(false)}
onConfirm={() => { setConfirmOpen(false); void runInvoke(); }}
/>
)}
</div>
);
}
function ConfirmDestructive({ action, uin, onCancel, onConfirm }: { action: string; uin: string; onCancel: () => void; onConfirm: () => void }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onCancel(); };
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onCancel]);
return (
<div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/40 p-4 backdrop-blur-sm" onClick={onCancel}>
<motion.div
initial={{ opacity: 0, scale: 0.96 }} animate={{ opacity: 1, scale: 1 }}
onClick={(e) => e.stopPropagation()}
className="w-full max-w-sm rounded-2xl border border-border/60 bg-card p-5 shadow-xl"
>
<div className="flex items-center gap-2.5">
<div className="flex h-9 w-9 items-center justify-center rounded-xl bg-destructive/12 text-destructive"><AlertTriangle className="h-5 w-5" /></div>
<h3 className="text-base font-semibold">确认执行破坏性操作</h3>
</div>
<p className="mt-3 text-sm text-muted-foreground">
即将以账号 <code className="font-mono text-foreground">{uin}</code> 执行 <code className="font-mono text-foreground">{action}</code>,该操作会<strong className="text-foreground">真实生效且通常不可撤销</strong>。确认继续?
</p>
<div className="mt-5 flex justify-end gap-2">
<button type="button" onClick={onCancel} className="rounded-lg border border-border px-4 py-2 text-sm font-medium hover:bg-muted">取消</button>
<button type="button" onClick={onConfirm} className="rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground hover:bg-destructive/90">确认执行</button>
</div>
</motion.div>
</div>
);
}
@@ -0,0 +1,137 @@
// ApiBrowser — an embedded, searchable reference for every declarative action
// (~520), grouped by category, surfaced straight from /api/debug/actions (the
// same docs the tester uses). Each row expands to params / returns / invariants
// and a 试一下 button that prefills the tester. No hand-maintained docs — this
// is the live catalog.
import { useMemo, useState } from 'react';
import { motion } from 'motion/react';
import { BookOpen, ChevronRight, PlayCircle, Search, ShieldCheck, Zap } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { DebugActionDoc } from '@/types';
const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm';
function ActionRow({ doc, onTry }: { doc: DebugActionDoc; onTry: (name: string) => void }) {
const [open, setOpen] = useState(false);
return (
<div className="rounded-xl border border-border/50 bg-card/40">
<button type="button" onClick={() => setOpen((v) => !v)} className="flex w-full items-center gap-2 px-3 py-2 text-left">
<ChevronRight className={cn('h-3.5 w-3.5 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
<code className="shrink-0 font-mono text-[13px] font-medium">{doc.name}</code>
{doc.readOnly
? <ShieldCheck className="h-3.5 w-3.5 shrink-0 text-emerald-500" />
: <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500" title="有副作用" />}
{doc.stream && <Zap className="h-3.5 w-3.5 shrink-0 text-primary" />}
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{doc.summary}</span>
</button>
{open && (
<div className="flex flex-col gap-3 border-t border-border/50 px-3 py-3 text-[13px]">
{doc.aliases.length > 0 && (
<p className="text-xs text-muted-foreground">别名:{doc.aliases.map((a) => <code key={a} className="ml-1 font-mono">{a}</code>)}</p>
)}
{doc.params.length > 0 ? (
<div className="overflow-hidden rounded-lg border border-border/50">
<table className="w-full text-left text-xs">
<thead className="bg-muted/40 text-muted-foreground">
<tr><th className="px-2 py-1 font-medium">参数</th><th className="px-2 py-1 font-medium">类型</th><th className="px-2 py-1 font-medium">必填</th><th className="px-2 py-1 font-medium">说明</th></tr>
</thead>
<tbody>
{doc.params.map((p) => (
<tr key={p.name} className="border-t border-border/40">
<td className="px-2 py-1 font-mono">{p.name}</td>
<td className="px-2 py-1 font-mono text-muted-foreground">{p.values ? p.values.map(String).join(' | ') : p.type}{p.role ? <span className="ml-1 text-primary/70">·{p.role}</span> : null}</td>
<td className="px-2 py-1">{p.required ? '✓' : '–'}</td>
<td className="px-2 py-1 text-muted-foreground">{p.desc ?? ''}{p.default !== undefined ? ` (默认 ${JSON.stringify(p.default)})` : ''}</td>
</tr>
))}
</tbody>
</table>
</div>
) : <p className="text-xs text-muted-foreground">无参数</p>}
{doc.invariants && doc.invariants.length > 0 && (
<p className="text-xs text-muted-foreground">约束:{doc.invariants.join(';')}</p>
)}
{doc.returns && <p className="text-xs text-muted-foreground">返回:<code className="font-mono">{doc.returns}</code></p>}
<div>
<button type="button" onClick={() => onTry(doc.name)}
className="inline-flex items-center gap-1.5 rounded-lg bg-primary/10 px-2.5 py-1.5 text-xs font-medium text-primary hover:bg-primary/15">
<PlayCircle className="h-3.5 w-3.5" /> 试一下
</button>
</div>
</div>
)}
</div>
);
}
export function ApiBrowser({ docs, onTry }: { docs: DebugActionDoc[]; onTry: (name: string) => void }) {
const [query, setQuery] = useState('');
const [cat, setCat] = useState<string>('');
const categories = useMemo(() => {
const set = new Set<string>();
for (const d of docs) if (d.category) set.add(d.category);
return Array.from(set).sort();
}, [docs]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
return docs.filter((d) => {
if (cat && d.category !== cat) return false;
if (!q) return true;
return d.name.toLowerCase().includes(q)
|| (d.summary?.toLowerCase().includes(q) ?? false)
|| d.aliases.some((a) => a.toLowerCase().includes(q));
});
}, [docs, query, cat]);
const grouped = useMemo(() => {
const m = new Map<string, DebugActionDoc[]>();
for (const d of filtered) {
const k = d.category ?? '其他';
const arr = m.get(k) ?? [];
arr.push(d);
m.set(k, arr);
}
return Array.from(m.entries()).sort((a, b) => a[0].localeCompare(b[0]));
}, [filtered]);
return (
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35 }}
className={cn(cardCls, 'flex min-h-[28rem] flex-col gap-4 p-6')}
>
<div className="flex items-center gap-2.5">
<BookOpen className="h-[18px] w-[18px] text-primary" />
<h2 className="text-[15px] font-semibold tracking-tight">API 浏览器</h2>
<span className="text-xs text-muted-foreground tabular-nums">{filtered.length}/{docs.length}</span>
</div>
<div className="flex items-center gap-2 rounded-lg border border-border/60 px-2.5 py-1.5">
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="搜索 action 名 / 摘要 / 别名…"
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground" />
</div>
<div className="flex flex-wrap gap-1.5">
<button type="button" onClick={() => setCat('')}
className={cn('rounded-full px-2.5 py-1 text-xs font-medium transition-colors', cat === '' ? 'bg-primary text-primary-foreground' : 'bg-muted/70 text-muted-foreground hover:text-foreground')}>全部</button>
{categories.map((c) => (
<button key={c} type="button" onClick={() => setCat(c)}
className={cn('rounded-full px-2.5 py-1 text-xs font-medium transition-colors', cat === c ? 'bg-primary text-primary-foreground' : 'bg-muted/70 text-muted-foreground hover:text-foreground')}>{c}</button>
))}
</div>
<div className="flex flex-1 flex-col gap-4 overflow-auto">
{grouped.length === 0 ? (
<p className="py-12 text-center text-sm text-muted-foreground">无匹配 action</p>
) : grouped.map(([category, items]) => (
<div key={category} className="flex flex-col gap-1.5">
<h3 className="px-1 text-xs font-semibold text-muted-foreground">{category} <span className="font-normal tabular-nums">{items.length}</span></h3>
{items.map((d) => <ActionRow key={d.name} doc={d} onTry={onTry} />)}
</div>
))}
</div>
</motion.section>
);
}
@@ -0,0 +1,122 @@
// FileSource — the control behind a file/image/record/video param. The bot runs
// on the SERVER, so a browser-local path is meaningless to it; this offers three
// honest sources: a URL the bot fetches, a path that already exists on the
// server, or a browser upload that we stream to a server temp path (and then
// feed that path to the action). Upload progress flows through the app-level
// task registry so it survives tab switches.
import { useRef, useState } from 'react';
import { FileUp, Link2, Loader2, ServerCog, X } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { useApi } from '@/lib/api';
import { useDebugTasks } from '@/contexts/DebugTaskContext';
import { cn } from '@/lib/utils';
import type { FieldRole } from '@/types';
type Mode = 'url' | 'server' | 'upload';
const ACCEPT: Partial<Record<FieldRole, string>> = {
image: 'image/*',
record: 'audio/*',
video: 'video/*',
};
function Seg({ active, onClick, icon, label }: { active: boolean; onClick: () => void; icon: React.ReactNode; label: string }) {
return (
<button
type="button"
onClick={onClick}
className={cn('inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-xs font-medium transition-colors',
active ? 'bg-card text-foreground shadow-sm ring-1 ring-border/60' : 'text-muted-foreground hover:text-foreground')}
>
{icon}{label}
</button>
);
}
export function FileSource({ value, onChange, role, placeholder }: {
value: string;
onChange: (v: string) => void;
role?: FieldRole;
placeholder?: string;
}) {
const api = useApi();
const { start, update, finish } = useDebugTasks();
const [mode, setMode] = useState<Mode>('url');
const [uploading, setUploading] = useState(false);
const [uploadName, setUploadName] = useState<string | null>(null);
const [uploadErr, setUploadErr] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const accept = role ? ACCEPT[role] : undefined;
const doUpload = async (file: File) => {
setUploadErr(null);
setUploadName(file.name);
setUploading(true);
const ac = new AbortController();
const taskId = start({ kind: 'upload', label: `上传 ${file.name}`, progress: 0, cancel: () => ac.abort() });
try {
const res = await api.debug.upload(file, {
signal: ac.signal,
onProgress: (f) => update(taskId, { progress: f }),
});
if (!res.path) throw new Error(res.message || '上传失败');
onChange(res.path);
finish(taskId, 'done', res.path);
} catch (e) {
const msg = e instanceof Error ? e.message : '上传失败';
setUploadErr(msg);
finish(taskId, ac.signal.aborted ? 'canceled' : 'failed', msg);
} finally {
setUploading(false);
}
};
return (
<div className="flex flex-col gap-2">
<div className="inline-flex w-fit gap-0.5 rounded-xl bg-muted/70 p-0.5">
<Seg active={mode === 'url'} onClick={() => setMode('url')} icon={<Link2 className="h-3.5 w-3.5" />} label="URL" />
<Seg active={mode === 'server'} onClick={() => setMode('server')} icon={<ServerCog className="h-3.5 w-3.5" />} label="服务器路径" />
<Seg active={mode === 'upload'} onClick={() => setMode('upload')} icon={<FileUp className="h-3.5 w-3.5" />} label="上传" />
</div>
{mode === 'url' && (
<Input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder || 'https://…'} />
)}
{mode === 'server' && (
<div className="flex flex-col gap-1">
<Input value={value} onChange={(e) => onChange(e.target.value)} placeholder="/path/on/server/file.jpg" />
<span className="text-[11px] text-muted-foreground">这是 <strong>运行 bot 的服务器</strong> 上的路径,不是你本机的。</span>
</div>
)}
{mode === 'upload' && (
<div className="flex flex-col gap-1.5">
<input
ref={inputRef}
type="file"
accept={accept}
className="hidden"
onChange={(e) => { const f = e.target.files?.[0]; if (f) void doUpload(f); e.target.value = ''; }}
/>
<button
type="button"
disabled={uploading}
onClick={() => inputRef.current?.click()}
className={cn('flex items-center justify-center gap-2 rounded-xl border border-dashed border-border/70 px-3 py-3 text-sm text-muted-foreground transition-colors hover:border-primary/50 hover:text-foreground disabled:opacity-60')}
>
{uploading ? <><Loader2 className="h-4 w-4 animate-spin" /> 上传中…</> : <><FileUp className="h-4 w-4" /> 选择文件上传到服务器</>}
</button>
{value && uploadName && !uploading && (
<div className="flex items-center gap-2 rounded-lg bg-muted/40 px-2.5 py-1.5 text-[11px]">
<span className="truncate text-muted-foreground">已上传:{uploadName}</span>
<code className="ml-auto max-w-[55%] truncate font-mono text-muted-foreground/80" title={value}>{value}</code>
<button type="button" onClick={() => { onChange(''); setUploadName(null); }} className="shrink-0 text-muted-foreground hover:text-destructive"><X className="h-3.5 w-3.5" /></button>
</div>
)}
{uploadErr && <span className="text-[11px] text-destructive">{uploadErr}</span>}
</div>
)}
</div>
);
}
@@ -0,0 +1,179 @@
// LiveActivity — the merged live SSE of OneBot events + action calls across all
// accounts. Extracted from the debug page so it can stand alone as a console
// tab. Filter by kind, keyword-search, pause, clear, and export the buffer as
// JSON. Rows expand to a JsonTree of the full payload.
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { Activity, ChevronRight, Download, Pause, Play, RadioTower, Search, Trash2 } from 'lucide-react';
import { JsonTree } from '@/components/ui/json-tree';
import { Segmented } from '@/components/debug/segmented';
import { useApi } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { DebugStreamMessage } from '@/types';
const STREAM_CAP = 300;
const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm';
interface StreamRow { id: number; at: number; msg: Extract<DebugStreamMessage, { kind: 'event' | 'action' | 'dropped' }> }
function IconBtn({ onClick, title, children }: { onClick: () => void; title: string; children: ReactNode }) {
return (
<button type="button" onClick={onClick} title={title} aria-label={title}
className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
{children}
</button>
);
}
function StatusPill({ status }: { status: 'open' | 'reconnecting' | 'closed' }) {
const map = {
open: { dot: 'bg-emerald-500', label: '已连接', glow: 'shadow-[0_0_0_3px_rgb(16_185_129/0.15)]' },
reconnecting: { dot: 'bg-amber-500', label: '重连中', glow: 'shadow-[0_0_0_3px_rgb(245_158_11/0.15)]' },
closed: { dot: 'bg-muted-foreground/50', label: '未连接', glow: '' },
}[status];
return (
<div className="inline-flex items-center gap-2 rounded-full border border-border/60 bg-card/70 px-3 py-1.5 text-xs font-medium backdrop-blur-sm">
<span className={cn('h-2 w-2 rounded-full', map.dot, map.glow)} />
<span className="text-muted-foreground">{map.label}</span>
</div>
);
}
function rowLabel(msg: Extract<DebugStreamMessage, { kind: 'event' | 'action' }>): { label: string; detail: unknown; isAction: boolean; ok: boolean } {
if (msg.kind === 'event') {
const e = msg.event as Record<string, unknown>;
return {
label: `${e.post_type ?? 'event'}${e.message_type ? `.${e.message_type}` : e.notice_type ? `.${e.notice_type}` : ''}`,
detail: e, isAction: false, ok: true,
};
}
// action
return {
label: msg.action,
detail: { params: msg.params, response: msg.response },
isAction: true,
ok: (msg.response as { status?: string }).status === 'ok',
};
}
function StreamRowItem({ row }: { row: StreamRow }) {
const [open, setOpen] = useState(false);
const { msg } = row;
const time = new Date(row.at).toLocaleTimeString('zh-CN', { hour12: false });
if (msg.kind === 'dropped') {
return <div className="px-2 py-1.5 text-[11px] text-amber-600 dark:text-amber-400">因客户端过慢丢弃了 {msg.count} 条</div>;
}
const { label, detail, isAction, ok } = rowLabel(msg);
return (
<div className="group rounded-xl transition-colors hover:bg-muted/40">
<button type="button" aria-expanded={open} className="flex w-full items-center gap-2.5 px-2.5 py-2 text-left text-[13px]" onClick={() => setOpen((v) => !v)}>
<ChevronRight className={cn('h-3.5 w-3.5 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
<span className="shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums">{time}</span>
<span className={cn('shrink-0 rounded-md px-1.5 py-0.5 text-[10px] font-semibold', isAction ? 'bg-primary/12 text-primary' : 'bg-muted text-muted-foreground')}>
{isAction ? '调用' : '事件'}
</span>
<span className="shrink-0 font-mono text-[11px] text-muted-foreground/80">{msg.uin}</span>
<span className="min-w-0 flex-1 truncate font-mono text-foreground/90">{label}</span>
{msg.kind === 'action' && (
<span className={cn('shrink-0 text-[11px] tabular-nums', ok ? 'text-success' : 'text-destructive')}>
{ok ? 'ok' : 'failed'} · {msg.ms}ms
</span>
)}
</button>
{open && <div className="mx-2.5 mb-2"><JsonTree data={detail} maxHeight="18rem" /></div>}
</div>
);
}
export function LiveActivity() {
const api = useApi();
const [rows, setRows] = useState<StreamRow[]>([]);
const [paused, setPaused] = useState(false);
const [status, setStatus] = useState<'open' | 'reconnecting' | 'closed'>('closed');
const [kindFilter, setKindFilter] = useState<'all' | 'event' | 'action'>('all');
const [query, setQuery] = useState('');
const pausedRef = useRef(paused);
useEffect(() => { pausedRef.current = paused; }, [paused]);
const idRef = useRef(0);
useEffect(() => {
const off = api.debug.stream(
(m) => {
if (m.kind === 'ready' || pausedRef.current) return;
setRows((prev) => {
const next = [{ id: idRef.current++, at: Date.now(), msg: m }, ...prev];
return next.length > STREAM_CAP ? next.slice(0, STREAM_CAP) : next;
});
},
(s) => setStatus(s),
);
return off;
}, [api]);
const visible = useMemo(() => {
const q = query.trim().toLowerCase();
return rows.filter((r) => {
if (kindFilter !== 'all' && r.msg.kind !== kindFilter) return false;
if (!q) return true;
if (r.msg.kind === 'dropped') return false;
const { label } = rowLabel(r.msg);
return label.toLowerCase().includes(q) || r.msg.uin.includes(q) || JSON.stringify(r.msg).toLowerCase().includes(q);
});
}, [rows, kindFilter, query]);
const exportJson = () => {
const blob = new Blob([JSON.stringify(visible.map((r) => ({ at: r.at, ...r.msg })), null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `debug-activity-${visible.length}.json`;
document.body.appendChild(a);
a.click();
a.remove();
// Revoke after the download has had a chance to start (immediate revoke
// cancels it in some browsers).
setTimeout(() => URL.revokeObjectURL(url), 1000);
};
return (
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35 }}
className={cn(cardCls, 'flex min-h-[28rem] flex-col p-6')}
>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2.5">
<RadioTower className="h-[18px] w-[18px] text-primary" />
<h2 className="text-[15px] font-semibold tracking-tight">实时活动</h2>
<span className="text-xs text-muted-foreground tabular-nums">{visible.length}</span>
<StatusPill status={status} />
</div>
<div className="flex items-center gap-2">
<Segmented value={kindFilter} onChange={setKindFilter}
options={[{ value: 'all', label: '全部' }, { value: 'event', label: '事件' }, { value: 'action', label: '调用' }]} />
<IconBtn onClick={() => setPaused((v) => !v)} title={paused ? '继续' : '暂停'}>{paused ? <Play className="h-4 w-4" /> : <Pause className="h-4 w-4" />}</IconBtn>
<IconBtn onClick={exportJson} title="导出 JSON"><Download className="h-4 w-4" /></IconBtn>
<IconBtn onClick={() => setRows([])} title="清空"><Trash2 className="h-4 w-4" /></IconBtn>
</div>
</div>
<div className="mt-3 flex items-center gap-2 rounded-lg border border-border/60 px-2.5 py-1.5">
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="搜索类型 / 账号 / 内容…"
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground" />
</div>
<div className="mt-3 flex flex-1 flex-col gap-1 overflow-auto">
{visible.length === 0 ? (
<div className="flex flex-1 flex-col items-center justify-center gap-3 py-12 text-center">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-muted/60"><Activity className="h-6 w-6 text-muted-foreground/70" /></div>
<p className="text-sm text-muted-foreground">{paused ? '已暂停' : query || kindFilter !== 'all' ? '无匹配' : '等待事件…'}</p>
</div>
) : (
visible.map((r) => <StreamRowItem key={r.id} row={r} />)
)}
</div>
</motion.section>
);
}
@@ -0,0 +1,313 @@
// MessageBuilder — a visual OneBot message composer so you never hand-write a
// segment array. Common segments are first-class (text / @ / image / face /
// reply / record / video); advanced ones fold away (file / mface / poke / json
// / xml / markdown / forward-node). `node` nests a full builder (merged
// forward). Rows reorder by drag. Emits the live OneBot segment array up.
import { useState } from 'react';
import {
AtSign, ChevronDown, Code2, FileText, Film, Forward, GripVertical, Hand, Image as ImageIcon,
Mic, Plus, Quote, Smile, Sticker, Trash2, Type,
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Picker } from '@/components/ui/picker';
import { FaceGrid } from '@/components/ui/face-grid';
import { FileSource } from '@/components/debug/file-source';
import { useGroupMembers } from '@/hooks/use-debug-contacts';
// ── segment model ──
// `_id` is a stable React key tied to a segment's identity (so editing one field
// doesn't remount the row and lose focus / inner control state); it is NOT
// serialised. SegBody is the discriminated union; Seg adds the id.
type SegBody =
| { k: 'text'; text: string }
| { k: 'at'; qq: string }
| { k: 'image'; file: string }
| { k: 'face'; id: string }
| { k: 'reply'; id: string }
| { k: 'record'; file: string }
| { k: 'video'; file: string }
| { k: 'file'; file: string; name: string }
| { k: 'mface'; emoji_id: string; emoji_package_id: string; key: string; summary: string }
| { k: 'poke'; type: string }
| { k: 'json'; data: string }
| { k: 'xml'; data: string }
| { k: 'markdown'; content: string }
| { k: 'node'; user_id: string; nickname: string; content: Seg[] };
export type Seg = SegBody & { _id: string };
let segSeq = 0;
const nid = () => `s${segSeq++}`;
const BLANK: Record<SegBody['k'], () => SegBody> = {
text: () => ({ k: 'text', text: '' }),
at: () => ({ k: 'at', qq: '' }),
image: () => ({ k: 'image', file: '' }),
face: () => ({ k: 'face', id: '' }),
reply: () => ({ k: 'reply', id: '' }),
record: () => ({ k: 'record', file: '' }),
video: () => ({ k: 'video', file: '' }),
file: () => ({ k: 'file', file: '', name: '' }),
mface: () => ({ k: 'mface', emoji_id: '', emoji_package_id: '', key: '', summary: '' }),
poke: () => ({ k: 'poke', type: '1' }),
json: () => ({ k: 'json', data: '' }),
xml: () => ({ k: 'xml', data: '' }),
markdown: () => ({ k: 'markdown', content: '' }),
node: () => ({ k: 'node', user_id: '', nickname: '', content: [] }),
};
/** A fresh segment with a stable id. */
export function newSeg(k: SegBody['k']): Seg {
return { ...BLANK[k](), _id: nid() } as Seg;
}
/** Serialise the builder model to a OneBot v11 segment array (drops `_id`). */
export function toOneBot(segs: Seg[]): Array<{ type: string; data: Record<string, unknown> }> {
return segs.map((s): { type: string; data: Record<string, unknown> } => {
switch (s.k) {
case 'text': return { type: 'text', data: { text: s.text } };
case 'at': return { type: 'at', data: { qq: s.qq } };
case 'image': return { type: 'image', data: { file: s.file } };
case 'face': return { type: 'face', data: { id: Number(s.id) || 0 } };
case 'reply': return { type: 'reply', data: { id: Number(s.id) || 0 } };
case 'record': return { type: 'record', data: { file: s.file } };
case 'video': return { type: 'video', data: { file: s.file } };
case 'file': return { type: 'file', data: { file: s.file, name: s.name } };
case 'mface': return { type: 'mface', data: { emoji_id: s.emoji_id, emoji_package_id: s.emoji_package_id, key: s.key, summary: s.summary } };
case 'poke': return { type: 'poke', data: { type: Number(s.type) || 1 } };
case 'json': return { type: 'json', data: { data: s.data } };
case 'xml': return { type: 'xml', data: { data: s.data } };
case 'markdown': return { type: 'markdown', data: { content: s.content } };
case 'node': return { type: 'node', data: { user_id: Number(s.user_id) || 0, nickname: s.nickname, content: toOneBot(s.content) } };
}
});
}
const COMMON: { k: SegBody['k']; label: string; icon: React.ReactNode }[] = [
{ k: 'text', label: '文本', icon: <Type className="h-4 w-4" /> },
{ k: 'at', label: '@', icon: <AtSign className="h-4 w-4" /> },
{ k: 'image', label: '图片', icon: <ImageIcon className="h-4 w-4" /> },
{ k: 'face', label: '表情', icon: <Smile className="h-4 w-4" /> },
{ k: 'reply', label: '回复', icon: <Quote className="h-4 w-4" /> },
{ k: 'record', label: '语音', icon: <Mic className="h-4 w-4" /> },
{ k: 'video', label: '视频', icon: <Film className="h-4 w-4" /> },
];
const ADVANCED: { k: SegBody['k']; label: string; icon: React.ReactNode }[] = [
{ k: 'file', label: '文件', icon: <FileText className="h-4 w-4" /> },
{ k: 'mface', label: '商城表情', icon: <Sticker className="h-4 w-4" /> },
{ k: 'poke', label: '戳一戳', icon: <Hand className="h-4 w-4" /> },
{ k: 'json', label: 'JSON 卡片', icon: <Code2 className="h-4 w-4" /> },
{ k: 'xml', label: 'XML 卡片', icon: <Code2 className="h-4 w-4" /> },
{ k: 'markdown', label: 'Markdown', icon: <Code2 className="h-4 w-4" /> },
{ k: 'node', label: '合并转发节点', icon: <Forward className="h-4 w-4" /> },
];
const LABELS: Record<SegBody['k'], string> = {
text: '文本', at: '@', image: '图片', face: '表情', reply: '回复', record: '语音', video: '视频',
file: '文件', mface: '商城表情', poke: '戳一戳', json: 'JSON', xml: 'XML', markdown: 'Markdown', node: '转发节点',
};
export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0 }: {
segments: Seg[];
onChange: (segs: Seg[]) => void;
uin: string;
/** group context for @ member picking (empty for private targets). */
groupId: string;
depth?: number;
}) {
const [showAdd, setShowAdd] = useState(false);
const [dragFrom, setDragFrom] = useState<number | null>(null);
const add = (k: SegBody['k']) => { onChange([...segments, newSeg(k)]); setShowAdd(false); };
const patch = (i: number, next: Seg) => onChange(segments.map((s, j) => (j === i ? next : s)));
const remove = (i: number) => onChange(segments.filter((_, j) => j !== i));
const move = (from: number, to: number) => {
if (to < 0 || to >= segments.length || from === to) return;
const next = segments.slice();
const [it] = next.splice(from, 1);
next.splice(to, 0, it);
onChange(next);
};
return (
// A bounded "compose canvas" at every level — so the empty hint reads as an
// intentional empty state inside a defined region rather than a stray
// centered line floating in the left-aligned form (Apple-HIG alignment).
<div className="flex flex-col gap-2 rounded-xl border border-border/50 bg-muted/20 p-2.5">
{segments.length === 0 && (
<p className="py-4 text-center text-xs text-muted-foreground">空消息 — 点下方「添加段」开始</p>
)}
{segments.map((s, i) => (
<div
key={s._id}
draggable
// stopPropagation makes the nested-builder boundary explicit: a child
// row's drag never reaches the parent node row.
onDragStart={(e) => { e.stopPropagation(); setDragFrom(i); }}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => { e.stopPropagation(); if (dragFrom !== null) move(dragFrom, i); setDragFrom(null); }}
onDragEnd={() => setDragFrom(null)}
className="flex items-start gap-2 rounded-xl border border-border/50 bg-card/60 p-2"
>
<GripVertical className="mt-1 h-4 w-4 shrink-0 cursor-grab text-muted-foreground/50" />
<div className="min-w-0 flex-1">
<div className="mb-1 flex items-center justify-between">
<span className="text-[11px] font-semibold text-muted-foreground">{LABELS[s.k]}</span>
<div className="flex items-center gap-0.5">
<button type="button" onClick={() => move(i, i - 1)} disabled={i === 0} className="rounded px-1 text-muted-foreground hover:bg-muted disabled:opacity-30" title="上移">↑</button>
<button type="button" onClick={() => move(i, i + 1)} disabled={i === segments.length - 1} className="rounded px-1 text-muted-foreground hover:bg-muted disabled:opacity-30" title="下移">↓</button>
<button type="button" onClick={() => remove(i)} className="rounded p-0.5 text-muted-foreground hover:text-destructive" title="删除"><Trash2 className="h-3.5 w-3.5" /></button>
</div>
</div>
<SegmentEditor seg={s} onChange={(n) => patch(i, n)} uin={uin} groupId={groupId} depth={depth} />
</div>
</div>
))}
<div className="relative">
<button type="button" onClick={() => setShowAdd((v) => !v)}
className="inline-flex items-center gap-1.5 rounded-lg border border-dashed border-border/70 px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:border-primary/50 hover:text-foreground">
<Plus className="h-3.5 w-3.5" /> 添加段
</button>
{showAdd && (
<div className="absolute z-30 mt-1.5 w-64 rounded-xl border border-border/60 bg-popover p-2 shadow-lg">
<div className="grid grid-cols-4 gap-1">
{COMMON.map((c) => (
<button key={c.k} type="button" onClick={() => add(c.k)}
className="flex flex-col items-center gap-1 rounded-lg p-2 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground">
{c.icon}{c.label}
</button>
))}
</div>
<details className="mt-1.5">
<summary className="cursor-pointer list-none px-1 text-[11px] text-muted-foreground hover:text-foreground"><span className="inline-flex items-center gap-1"><ChevronDown className="h-3 w-3" /> 进阶段</span></summary>
<div className="mt-1 grid grid-cols-4 gap-1">
{ADVANCED.map((c) => (
<button key={c.k} type="button" onClick={() => add(c.k)}
className="flex flex-col items-center gap-1 rounded-lg p-2 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground">
{c.icon}{c.label}
</button>
))}
</div>
</details>
</div>
)}
</div>
</div>
);
}
function AtEditor({ seg, onChange, uin, groupId }: { seg: Extract<Seg, { k: 'at' }>; onChange: (s: Seg) => void; uin: string; groupId: string }) {
const { items, loading, error, refresh } = useGroupMembers(uin, groupId);
const options = [{ value: 'all', label: '@全体成员', sub: 'all' }, ...items];
return (
<Picker ariaLabel="@某人" value={seg.qq} onChange={(v) => onChange({ ...seg, qq: v })}
options={options} loading={loading} error={error} onRefresh={refresh}
placeholder={groupId ? '选择成员 / @全体' : '输入 QQ 号(私聊无成员)'} validateRaw={(s) => s === 'all' || /^\d{3,}$/.test(s)} />
);
}
function SegmentEditor({ seg, onChange, uin, groupId, depth }: { seg: Seg; onChange: (s: Seg) => void; uin: string; groupId: string; depth: number }) {
switch (seg.k) {
case 'text':
return <textarea value={seg.text} onChange={(e) => onChange({ ...seg, text: e.target.value })} placeholder="文本内容"
className="min-h-16 w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40" />;
case 'at':
return <AtEditor seg={seg} onChange={onChange} uin={uin} groupId={groupId} />;
case 'image': return <FileSource role="image" value={seg.file} onChange={(v) => onChange({ ...seg, file: v })} />;
case 'record': return <FileSource role="record" value={seg.file} onChange={(v) => onChange({ ...seg, file: v })} />;
case 'video': return <FileSource role="video" value={seg.file} onChange={(v) => onChange({ ...seg, file: v })} />;
case 'file':
return (
<div className="flex flex-col gap-1.5">
<FileSource role="file" value={seg.file} onChange={(v) => onChange({ ...seg, file: v })} />
<Input value={seg.name} onChange={(e) => onChange({ ...seg, name: e.target.value })} placeholder="文件名(可选)" />
</div>
);
case 'face': return <FaceGrid value={seg.id} onChange={(v) => onChange({ ...seg, id: v })} />;
case 'reply': return <Input value={seg.id} onChange={(e) => onChange({ ...seg, id: e.target.value.replace(/[^\d-]/g, '') })} placeholder="回复的消息 id" className="font-mono" />;
case 'poke': return <Input value={seg.type} onChange={(e) => onChange({ ...seg, type: e.target.value.replace(/[^\d]/g, '') })} placeholder="戳一戳类型(默认 1)" className="font-mono" />;
case 'json': return <textarea value={seg.data} onChange={(e) => onChange({ ...seg, data: e.target.value })} placeholder='JSON 卡片原文 {"app":…}' className="min-h-16 w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs outline-none focus-visible:border-ring" />;
case 'xml': return <textarea value={seg.data} onChange={(e) => onChange({ ...seg, data: e.target.value })} placeholder="XML 卡片原文 <msg>…" className="min-h-16 w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs outline-none focus-visible:border-ring" />;
case 'markdown': return <textarea value={seg.content} onChange={(e) => onChange({ ...seg, content: e.target.value })} placeholder="Markdown 内容" className="min-h-16 w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs outline-none focus-visible:border-ring" />;
case 'mface':
return (
<div className="grid grid-cols-2 gap-1.5">
<Input value={seg.emoji_id} onChange={(e) => onChange({ ...seg, emoji_id: e.target.value })} placeholder="emoji_id" className="font-mono text-xs" />
<Input value={seg.emoji_package_id} onChange={(e) => onChange({ ...seg, emoji_package_id: e.target.value })} placeholder="emoji_package_id" className="font-mono text-xs" />
<Input value={seg.key} onChange={(e) => onChange({ ...seg, key: e.target.value })} placeholder="key" className="font-mono text-xs" />
<Input value={seg.summary} onChange={(e) => onChange({ ...seg, summary: e.target.value })} placeholder="summary(可选)" className="text-xs" />
</div>
);
case 'node':
return (
<div className="flex flex-col gap-2">
<div className="grid grid-cols-2 gap-1.5">
<Input value={seg.user_id} onChange={(e) => onChange({ ...seg, user_id: e.target.value.replace(/[^\d]/g, '') })} placeholder="发送者 QQ" className="font-mono text-xs" />
<Input value={seg.nickname} onChange={(e) => onChange({ ...seg, nickname: e.target.value })} placeholder="发送者昵称" className="text-xs" />
</div>
<div>
<span className="mb-1 block text-[11px] text-muted-foreground">节点内容(可再嵌套)</span>
{depth < 3 ? (
<MessageBuilder segments={seg.content} onChange={(c) => onChange({ ...seg, content: c })} uin={uin} groupId={groupId} depth={depth + 1} />
) : (
<p className="text-[11px] text-destructive">嵌套层级过深</p>
)}
</div>
</div>
);
}
}
/** A compact human-readable preview line of a built message. */
export function previewSegments(segs: Seg[]): string {
return segs.map((s) => {
switch (s.k) {
case 'text': return s.text;
case 'at': return s.qq === 'all' ? '@全体' : `@${s.qq}`;
case 'image': return '[图片]';
case 'face': return `[表情${s.id}]`;
case 'reply': return '[回复]';
case 'record': return '[语音]';
case 'video': return '[视频]';
case 'file': return `[文件${s.name ? ':' + s.name : ''}]`;
case 'mface': return '[商城表情]';
case 'poke': return '[戳一戳]';
case 'json': return '[JSON卡片]';
case 'xml': return '[XML卡片]';
case 'markdown': return '[Markdown]';
case 'node': return `[转发:${s.nickname || s.user_id}]`;
}
}).join('');
}
/** True if the message contains forward nodes (→ send via the forward action). */
export function hasNodes(segs: Seg[]): boolean {
return segs.some((s) => s.k === 'node');
}
/** Per-segment completeness check (recurses into node content). Returns the
* first problem string, or null. The forward "all nodes" rule is enforced
* separately at the top level (only the forward action's `messages` array must
* be all-nodes; a node's own content is a normal message). */
export function validateSegs(segs: Seg[]): string | null {
for (const s of segs) {
switch (s.k) {
case 'at': if (!s.qq.trim()) return '@ 段未选择对象'; break;
case 'image': if (!s.file.trim()) return '图片段未指定来源'; break;
case 'record': if (!s.file.trim()) return '语音段未指定来源'; break;
case 'video': if (!s.file.trim()) return '视频段未指定来源'; break;
case 'file': if (!s.file.trim()) return '文件段未指定来源'; break;
case 'reply': if (!s.id.trim()) return '回复段缺少消息 id'; break;
case 'node': {
if (!s.user_id.trim()) return '转发节点缺少发送者 QQ';
if (s.content.length === 0) return '转发节点内容为空';
const inner = validateSegs(s.content);
if (inner) return inner;
break;
}
default: break;
}
}
return null;
}
@@ -0,0 +1,148 @@
// MessageComposer — the standalone "消息构建" tab: pick a target (group or
// friend), build a message visually, preview it, send it. A message containing
// forward nodes goes through the forward-send action; otherwise the plain
// send_*_msg. The chosen group provides the @-member context to the builder.
import { useEffect, useMemo, useState } from 'react';
import { motion } from 'motion/react';
import { Loader2, MessageSquarePlus, Send } from 'lucide-react';
import { Select } from '@/components/ui/select';
import { Picker } from '@/components/ui/picker';
import { JsonTree } from '@/components/ui/json-tree';
import { Segmented } from '@/components/debug/segmented';
import { MessageBuilder, hasNodes, previewSegments, toOneBot, validateSegs, type Seg } from '@/components/debug/message-builder';
import { useFriends, useGroups } from '@/hooks/use-debug-contacts';
import { useApi } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { DebugInvokeResult, QQInfo } from '@/types';
const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm';
const looksLikeId = (s: string) => /^\d{3,}$/.test(s.trim());
function TargetPicker({ kind, uin, value, onChange }: { kind: 'group' | 'friend'; uin: string; value: string; onChange: (v: string) => void }) {
const groups = useGroups(kind === 'group' ? uin : '');
const friends = useFriends(kind === 'friend' ? uin : '');
const src = kind === 'group' ? groups : friends;
return (
<Picker ariaLabel={kind === 'group' ? '选择群' : '选择好友'} value={value} onChange={onChange}
options={src.items} loading={src.loading} error={src.error} onRefresh={src.refresh}
placeholder={kind === 'group' ? '选择群…' : '选择好友…'} validateRaw={looksLikeId} />
);
}
export function MessageComposer({ accounts }: { accounts: QQInfo[] }) {
const api = useApi();
const [uin, setUin] = useState('');
const [kind, setKind] = useState<'group' | 'friend'>('group');
const [target, setTarget] = useState('');
const [segs, setSegs] = useState<Seg[]>([]);
const [sending, setSending] = useState(false);
const [result, setResult] = useState<DebugInvokeResult | { error: string } | null>(null);
// default to the first account once loaded
useEffect(() => { if (!uin && accounts[0]) setUin(accounts[0].uin); }, [accounts, uin]);
const preview = useMemo(() => previewSegments(segs), [segs]);
const groupId = kind === 'group' ? target : '';
const send = async () => {
if (!uin) { setResult({ error: '请选择账号' }); return; }
if (!target) { setResult({ error: kind === 'group' ? '请选择群' : '请选择好友' }); return; }
if (segs.length === 0) { setResult({ error: '消息为空' }); return; }
const forward = hasNodes(segs);
// Forward messages must be ALL nodes: the backend silently drops top-level
// non-node segments, so a mixed message would send less than the preview
// shows. Block it with a clear message instead.
if (forward && !segs.every((s) => s.k === 'node')) {
setResult({ error: '合并转发消息只能由转发节点组成 — 请移除非节点段,或把它们放进某个转发节点内' });
return;
}
const incomplete = validateSegs(segs);
if (incomplete) { setResult({ error: incomplete }); return; }
const payload = toOneBot(segs);
const action = forward
? (kind === 'group' ? 'send_group_forward_msg' : 'send_private_forward_msg')
: (kind === 'group' ? 'send_group_msg' : 'send_private_msg');
const params: Record<string, unknown> = kind === 'group' ? { group_id: target } : { user_id: target };
params[forward ? 'messages' : 'message'] = payload;
setSending(true);
setResult(null);
try {
setResult(await api.debug.invoke(uin, action, params));
} catch (e) {
setResult({ error: e instanceof Error ? e.message : '发送失败' });
} finally {
setSending(false);
}
};
const resultFailed = !!result && ('error' in result || result.status === 'failed');
return (
<div className="grid grid-cols-1 gap-6 xl:grid-cols-12">
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35 }}
className={cn(cardCls, 'flex flex-col gap-5 p-6 xl:col-span-7')}
>
<div className="flex items-center gap-2.5">
<MessageSquarePlus className="h-[18px] w-[18px] text-primary" />
<h2 className="text-[15px] font-semibold tracking-tight">消息构建</h2>
</div>
<div className="grid gap-4 sm:grid-cols-[auto_1fr]">
<div className="flex flex-col gap-1.5">
{/* Fixed h-8 == the target column's segmented-control height, so both
label rows are exactly equal and the two selectors below share a
baseline (min-h-7 wasn't enough — the segmented is ~32px). */}
<div className="flex h-8 items-center">
<span className="text-xs font-medium text-muted-foreground">账号</span>
</div>
<Select value={uin} onChange={(e) => setUin(e.target.value)} className="w-full sm:w-44">
{accounts.length === 0 && <option value="">(无在线账号)</option>}
{accounts.map((a) => <option key={a.uin} value={a.uin}>{a.nickname || a.uin}</option>)}
</Select>
</div>
<div className="flex flex-col gap-1.5">
<div className="flex h-8 items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">目标</span>
<Segmented value={kind} onChange={(k) => { setKind(k); setTarget(''); }}
options={[{ value: 'group', label: '群聊' }, { value: 'friend', label: '私聊' }]} />
</div>
<TargetPicker kind={kind} uin={uin} value={target} onChange={setTarget} />
</div>
</div>
<div className="flex flex-col gap-2">
<span className="text-xs font-medium text-muted-foreground">消息内容</span>
<MessageBuilder segments={segs} onChange={setSegs} uin={uin} groupId={groupId} />
</div>
<button type="button" onClick={send} disabled={sending}
className="inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary text-[15px] font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.99] disabled:opacity-50">
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />} 发送{hasNodes(segs) ? '(合并转发)' : ''}
</button>
</motion.section>
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.05 }}
className={cn(cardCls, 'flex min-h-[20rem] flex-col gap-3 p-6 xl:col-span-5')}
>
<h3 className="text-[15px] font-semibold tracking-tight">预览</h3>
<div className="rounded-xl border border-border/60 bg-muted/30 p-3 text-sm">
{preview ? <span className="whitespace-pre-wrap break-words">{preview}</span> : <span className="text-muted-foreground">消息为空</span>}
</div>
<span className="text-xs font-medium text-muted-foreground">OneBot 段</span>
<JsonTree data={toOneBot(segs)} maxHeight="14rem" />
{result && (
<div className="flex flex-col gap-1.5">
<span className={cn('text-xs font-medium', resultFailed ? 'text-destructive' : 'text-success')}>{resultFailed ? '发送失败' : '已发送'}</span>
{'error' in result
? <div className="rounded-xl bg-destructive/10 p-3 text-sm text-destructive">{result.error}</div>
: <JsonTree data={result} maxHeight="12rem" />}
</div>
)}
</motion.section>
</div>
);
}
@@ -0,0 +1,144 @@
// ParamField — renders the right smart control for one action param, driven by
// its semantic `role` first, then its coercion `type`, with the plain typed
// input as the floor. This is what kills "hand-write the JSON": a group_id
// becomes a group picker, a member_id a member picker linked to the sibling
// group_id, an image a FileSource, a bool a switch, an enum a select.
import { useState } from 'react';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { Picker } from '@/components/ui/picker';
import { FaceGrid } from '@/components/ui/face-grid';
import { FileSource } from '@/components/debug/file-source';
import { Segmented } from '@/components/debug/segmented';
import { MessageBuilder, toOneBot, type Seg } from '@/components/debug/message-builder';
import { useFriends, useGroups, useGroupMembers } from '@/hooks/use-debug-contacts';
import type { DebugActionParam, FieldRole } from '@/types';
const isNumericType = (t: string) => /int|uint|number|messageId/i.test(t);
const looksLikeId = (s: string) => /^\d{3,}$/.test(s.trim());
function GroupPicker({ uin, value, onChange }: { uin: string; value: string; onChange: (v: string) => void }) {
const { items, loading, error, refresh } = useGroups(uin);
return <Picker ariaLabel="选择群" value={value} onChange={onChange} options={items} loading={loading} error={error} onRefresh={refresh} placeholder="选择群…" validateRaw={looksLikeId} />;
}
function FriendPicker({ uin, value, onChange }: { uin: string; value: string; onChange: (v: string) => void }) {
const { items, loading, error, refresh } = useFriends(uin);
return <Picker ariaLabel="选择好友" value={value} onChange={onChange} options={items} loading={loading} error={error} onRefresh={refresh} placeholder="选择好友…" validateRaw={looksLikeId} />;
}
function MemberPicker({ uin, groupId, value, onChange }: { uin: string; groupId: string; value: string; onChange: (v: string) => void }) {
const { items, loading, error, refresh } = useGroupMembers(uin, groupId);
return (
<Picker
ariaLabel="选择群成员"
value={value}
onChange={onChange}
options={items}
loading={loading}
error={error}
onRefresh={refresh}
placeholder={groupId ? '选择群成员…' : '请先选择群号'}
validateRaw={looksLikeId}
/>
);
}
const MEDIA_ROLES: FieldRole[] = ['file', 'image', 'record', 'video'];
export function ParamField({ param, value, onChange, uin, groupContext }: {
param: DebugActionParam;
value: string;
onChange: (v: string) => void;
uin: string;
/** value of the sibling group_id field (for member_id pickers). */
groupContext: string;
}) {
const role = param.role;
// ── role-driven widgets ──
if (role === 'group_id') return <GroupPicker uin={uin} value={value} onChange={onChange} />;
if (role === 'user_id') return <FriendPicker uin={uin} value={value} onChange={onChange} />;
if (role === 'member_id') return <MemberPicker uin={uin} groupId={groupContext} value={value} onChange={onChange} />;
if (role && MEDIA_ROLES.includes(role)) return <FileSource role={role} value={value} onChange={onChange} />;
if (role === 'face_id') return <FaceGrid value={value} onChange={onChange} />;
if (role === 'timestamp') {
// datetime-local <-> unix seconds
const local = (() => {
const n = Number(value);
if (!value || !Number.isFinite(n) || n <= 0) return '';
const d = new Date(n * 1000);
const pad = (x: number) => String(x).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
})();
return (
<div className="flex items-center gap-2">
<Input type="datetime-local" value={local}
onChange={(e) => { const v = e.target.value; onChange(v ? String(Math.floor(new Date(v).getTime() / 1000)) : ''); }} />
<Input value={value} onChange={(e) => onChange(e.target.value.replace(/[^\d]/g, ''))} placeholder="unix 秒" className="w-28 font-mono" aria-label="时间戳" />
</div>
);
}
// ── type-driven widgets ──
if (param.values && param.values.length > 0) {
return (
// Always render the empty option so a controlled <select value=""> has a
// matching option (otherwise the browser shows the first value while state
// stays '' — a "looks selected but sends nothing" trap for required enums).
<Select value={value} onChange={(e) => onChange(e.target.value)}>
<option value="">{param.required ? '(请选择)' : '(默认)'}</option>
{param.values.map((v) => <option key={String(v)} value={String(v)}>{String(v)}</option>)}
</Select>
);
}
if (param.type === 'bool' || param.type === 'boolean') {
return (
<div className="flex h-9 items-center">
<ToggleSwitch value={value === 'true' || value === '1'} onChange={(v) => onChange(v ? 'true' : 'false')} ariaLabel={param.name} />
</div>
);
}
if (param.type === 'message') {
return <MessageParamField value={value} onChange={onChange} uin={uin} groupContext={groupContext} />;
}
if (isNumericType(param.type)) {
return <Input type="number" value={value} onChange={(e) => onChange(e.target.value)}
placeholder={param.desc || (param.default !== undefined ? `默认 ${JSON.stringify(param.default)}` : '')} />;
}
return <Input value={value} onChange={(e) => onChange(e.target.value)}
placeholder={param.desc || (param.default !== undefined ? `默认 ${JSON.stringify(param.default)}` : '')} />;
}
// Message param: the visual builder (keeps its own Seg[] model and emits the
// serialized OneBot array as the string param value) with a raw-text escape
// hatch. The builder is one-way (builder → value); switching to 原文 edits the
// string directly — the tester's global JSON mode covers full raw editing.
function MessageParamField({ value, onChange, uin, groupContext }: { value: string; onChange: (v: string) => void; uin: string; groupContext: string }) {
const [mode, setMode] = useState<'build' | 'raw'>('build');
const [segs, setSegs] = useState<Seg[]>([]);
const updateSegs = (next: Seg[]) => {
setSegs(next);
onChange(next.length ? JSON.stringify(toOneBot(next)) : '');
};
return (
<div className="flex flex-col gap-2">
<div className="flex justify-end">
<Segmented value={mode} onChange={setMode} options={[{ value: 'build', label: '构建器' }, { value: 'raw', label: '原文' }]} />
</div>
{mode === 'build' ? (
<MessageBuilder segments={segs} onChange={updateSegs} uin={uin} groupId={groupContext} />
) : (
<textarea
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder='文本,或 OneBot 段数组 JSON:[{"type":"text","data":{"text":"hi"}}]'
className="min-h-20 w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40"
/>
)}
</div>
);
}
@@ -0,0 +1,39 @@
// Segmented — an iOS-style segmented control with a sliding active pill. Shared
// by the debug console's tester / stream panels. Extracted from the original
// debug page so multiple panels reuse one implementation.
import { useId, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { cn } from '@/lib/utils';
export function Segmented<T extends string>({ value, onChange, options }: {
value: T; onChange: (v: T) => void; options: { value: T; label: ReactNode }[];
}) {
const id = useId();
return (
<div role="radiogroup" className="inline-flex rounded-full bg-muted/70 p-0.5 text-sm">
{options.map((o) => {
const active = o.value === value;
return (
<button
key={o.value}
type="button"
role="radio"
aria-checked={active}
onClick={() => onChange(o.value)}
className={cn('relative rounded-full px-3.5 py-1 font-medium transition-colors',
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground')}
>
{active && (
<motion.span
layoutId={`seg-${id}`}
transition={{ type: 'spring', stiffness: 500, damping: 38 }}
className="absolute inset-0 rounded-full bg-card shadow-sm ring-1 ring-border/50"
/>
)}
<span className="relative z-10">{o.label}</span>
</button>
);
})}
</div>
);
}
@@ -0,0 +1,89 @@
// TaskBadge — the app-wide floating indicator for in-flight debug tasks. Sits
// bottom-right on every page so a streaming upload/download stays visible after
// you switch tabs. Collapsed: a chip with a ring-progress + count. Expanded: a
// list with per-task progress, cancel (running) / dismiss (finished). Renders
// nothing when there are no tasks at all.
import { useState } from 'react';
import { AnimatePresence, motion } from 'motion/react';
import { CheckCircle2, Loader2, X, XCircle } from 'lucide-react';
import { useDebugTasks, useRunningTaskSummary, type DebugTask } from '@/contexts/DebugTaskContext';
import { cn } from '@/lib/utils';
function StatusIcon({ status }: { status: DebugTask['status'] }) {
if (status === 'running') return <Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />;
if (status === 'done') return <CheckCircle2 className="h-3.5 w-3.5 text-success" />;
return <XCircle className="h-3.5 w-3.5 text-destructive" />;
}
function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) {
const pct = typeof task.progress === 'number' ? Math.round(task.progress * 100) : null;
return (
<div className="flex flex-col gap-1 rounded-lg px-2.5 py-2 hover:bg-muted/50">
<div className="flex items-center gap-2 text-xs">
<StatusIcon status={task.status} />
<span className="min-w-0 flex-1 truncate text-foreground/90">{task.label}</span>
{task.status === 'running' && task.cancel
? <button type="button" onClick={task.cancel} className="text-muted-foreground hover:text-destructive" title="取消"><X className="h-3.5 w-3.5" /></button>
: <button type="button" onClick={onDismiss} className="text-muted-foreground hover:text-foreground" title="移除"><X className="h-3.5 w-3.5" /></button>}
</div>
{task.status === 'running' && (
<div className="h-1 overflow-hidden rounded-full bg-muted">
<div
className={cn('h-full rounded-full bg-primary transition-all', pct === null && 'animate-pulse')}
style={{ width: pct === null ? '40%' : `${pct}%` }}
/>
</div>
)}
{task.detail && task.status !== 'running' && (
<span className="truncate text-[10px] text-muted-foreground" title={task.detail}>{task.detail}</span>
)}
</div>
);
}
export function TaskBadge() {
const { tasks, remove, clearFinished } = useDebugTasks();
const { count, progress } = useRunningTaskSummary();
const [open, setOpen] = useState(false);
if (tasks.length === 0) return null;
const ringPct = progress === null ? null : Math.round(progress * 100);
return (
<div className="fixed bottom-4 right-4 z-[60] flex flex-col items-end gap-2">
<AnimatePresence>
{open && (
<motion.div
initial={{ opacity: 0, y: 8, scale: 0.97 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 8, scale: 0.97 }}
transition={{ type: 'spring', stiffness: 480, damping: 36 }}
className="w-72 overflow-hidden rounded-2xl border border-border/60 bg-popover shadow-xl ring-1 ring-black/5"
>
<div className="flex items-center justify-between border-b border-border/60 px-3 py-2">
<span className="text-xs font-semibold">调试任务</span>
{tasks.some((t) => t.status !== 'running') && (
<button type="button" onClick={clearFinished} className="text-[11px] text-muted-foreground hover:text-foreground">清除已完成</button>
)}
</div>
<div className="max-h-72 overflow-auto p-1.5">
{tasks.map((t) => <Row key={t.id} task={t} onDismiss={() => remove(t.id)} />)}
</div>
</motion.div>
)}
</AnimatePresence>
<button
type="button"
onClick={() => setOpen((v) => !v)}
className="flex items-center gap-2 rounded-full border border-border/60 bg-card/90 px-3 py-2 text-xs font-medium shadow-lg ring-1 ring-black/5 backdrop-blur transition-colors hover:bg-card"
>
{count > 0 ? <Loader2 className="h-4 w-4 animate-spin text-primary" /> : <CheckCircle2 className="h-4 w-4 text-success" />}
{count > 0
? <span>{count} 个任务进行中{ringPct !== null ? ` · ${ringPct}%` : ''}</span>
: <span className="text-muted-foreground">任务完成</span>}
</button>
</div>
);
}
@@ -66,7 +66,13 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
}}
className="relative h-full shrink-0 overflow-hidden"
>
<Sidebar collapsed={showCollapsed} />
{/* Fixed-width inner: the rail's content is ALWAYS laid out at the
expanded width and the aside simply clips it as `width` animates.
Nothing reflows during the transition, so icons never shift and
labels never wrap — they're revealed/clipped, not re-laid-out. */}
<div className="h-full w-[248px]">
<Sidebar collapsed={showCollapsed} />
</div>
</motion.aside>
)}
@@ -1,11 +1,13 @@
import { Bug, Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react';
import { Bug, Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, Pin, PinOff, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react';
import { motion, Reorder } from 'motion/react';
import { Link, useRouterState } from '@tanstack/react-router';
import { ScrollArea } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
import { useAppState } from '@/contexts/AppStateContext';
import { useTheme } from '@/contexts/ThemeContext';
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import { useMediaQuery } from '@/hooks/use-media-query';
import type { AppPath } from '@/router';
export interface NavItem {
@@ -39,6 +41,9 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const { updateInfo } = useAppState();
const { navItems, setNavItems, editing, setEditing } = useLayout();
const { appearance, setAppearance } = useTheme();
const isDesktop = useMediaQuery('(min-width: 768px)');
const pinned = appearance.sidebarPinned;
// Full reconciled nav (incl. hidden) — pinned forced visible, forward-compat.
const reconciled = reconcileLayoutItems(navItems, NAV_ITEMS.map((i) => i.to), PINNED_NAV);
@@ -56,21 +61,23 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
setNavItems(reconciled.map((i) => (i.id === id ? { ...i, visible: !i.visible } : i)));
return (
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
{/* Brand */}
<div className={cn('flex h-16 items-center gap-3 px-4', collapsed && 'justify-center px-2')}>
<div className="relative flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-primary/10 ring-1 ring-primary/20">
<img src="/logo.png" alt="SnowLuma" className="size-7 object-contain" />
</div>
{!collapsed && (
<div className="min-w-0 flex-1">
<div className="flex items-baseline gap-1.5">
<span className="text-sm font-bold tracking-tight">{APP_NAME}</span>
<span className="text-[10px] font-medium text-muted-foreground tabular-nums">v{APP_VERSION}</span>
</div>
<span className="text-[10px] text-muted-foreground">OneBot v11 控制台</span>
<div className="flex h-full w-full flex-col overflow-hidden bg-sidebar text-sidebar-foreground">
{/* Brand — logo sits in a fixed 48px column centred in the collapsed
rail; the wordmark to its right is clipped (never unmounted) when the
rail narrows. */}
<div className="flex h-16 shrink-0 items-center px-2">
<div className="grid w-12 shrink-0 place-items-center">
<div className="relative flex size-9 items-center justify-center overflow-hidden rounded-xl bg-primary/10 ring-1 ring-primary/20">
<img src="/logo.png" alt="SnowLuma" className="size-7 object-contain" />
</div>
)}
</div>
<div className={cn('min-w-0 flex-1 overflow-hidden pr-2 transition-opacity duration-200', collapsed ? 'opacity-0' : 'opacity-100')}>
<div className="flex items-baseline gap-1.5 whitespace-nowrap">
<span className="text-sm font-bold tracking-tight">{APP_NAME}</span>
<span className="text-[10px] font-medium text-muted-foreground tabular-nums">v{APP_VERSION}</span>
</div>
<span className="block whitespace-nowrap text-[10px] text-muted-foreground">OneBot v11 控制台</span>
</div>
</div>
{/* Nav */}
@@ -92,7 +99,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
const meta = NAV_ITEMS.find((n) => n.to === item.id);
if (!meta) return null;
const Icon = meta.icon;
const pinned = (PINNED_NAV as string[]).includes(item.id);
const itemPinned = (PINNED_NAV as string[]).includes(item.id);
return (
<Reorder.Item
key={item.id}
@@ -105,7 +112,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
<GripVertical className="size-3.5 shrink-0 text-muted-foreground" />
<Icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{meta.label}</span>
{pinned ? (
{itemPinned ? (
<span title="必选项,不可隐藏" className="inline-flex size-7 items-center justify-center text-muted-foreground/50">
<Lock className="size-3.5" />
</span>
@@ -126,7 +133,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
</Reorder.Group>
</div>
) : (
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
<nav className="flex flex-col gap-1 px-2 py-2">
{orderedNav.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
@@ -137,8 +144,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
'group relative flex items-center rounded-lg py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
@@ -146,25 +152,34 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
>
{isActive && (
<>
{/* Highlight geometry is the ONLY thing that switches on
collapse: a full-row pill when open, a centred squircle
on the rail. Both are absolutely positioned, so they
morph (layout) without reflowing the row. */}
<motion.span
layoutId="sidebar-active-pill"
className="absolute inset-0 rounded-lg bg-sidebar-accent"
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
/>
<motion.span
layoutId="sidebar-active-bar"
className="absolute left-0 top-1/2 h-5 w-0.5 -translate-y-1/2 rounded-full bg-primary"
className={cn(
'absolute inset-y-0 rounded-lg bg-sidebar-accent',
collapsed ? 'left-0.5 w-11' : 'inset-x-0',
)}
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
/>
{!collapsed && (
<motion.span
layoutId="sidebar-active-bar"
className="absolute left-0 top-1/2 h-5 w-0.5 -translate-y-1/2 rounded-full bg-primary"
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
/>
)}
</>
)}
<Icon className={cn('relative z-10 size-4 shrink-0', isActive && 'text-primary')} />
{!collapsed && (
<span className="relative z-10 flex min-w-0 flex-1 flex-col items-start">
<span className="truncate leading-tight">{label}</span>
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
</span>
)}
<span className="relative z-10 grid w-12 shrink-0 place-items-center">
<Icon className={cn('size-4', isActive && 'text-primary')} />
</span>
<span className={cn('relative z-10 flex min-w-0 flex-1 flex-col items-start overflow-hidden pr-3 transition-opacity duration-200', collapsed ? 'opacity-0' : 'opacity-100')}>
<span className="w-full truncate whitespace-nowrap leading-tight">{label}</span>
<span className="w-full truncate whitespace-nowrap text-[10px] font-normal text-muted-foreground">{description}</span>
</span>
</Link>
);
})}
@@ -173,33 +188,57 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
</ScrollArea>
{updateInfo?.hasUpdate && (
<div className={cn('px-2 pt-2', collapsed && 'px-0')}>
<div className="shrink-0 px-2 pb-1">
<Link
to="/settings"
search={{ tab: 'about' }}
onClick={onItemClick}
title={updateInfo.latest ? `有新版本 v${updateInfo.latest} · 点击查看` : '有可用更新'}
title={collapsed ? (updateInfo.latest ? `有新版本 v${updateInfo.latest} · 点击查看` : '有可用更新') : undefined}
aria-label="有可用更新"
className={cn(
'group relative flex items-center gap-2.5 rounded-lg bg-primary/[0.1] px-3 py-2 text-left transition-colors hover:bg-primary/15',
collapsed && 'mx-auto w-10 justify-center px-0',
)}
className="group relative flex items-center py-2"
>
<Sparkles className="size-4 shrink-0 text-primary" />
{!collapsed && (
<span className="flex min-w-0 flex-1 flex-col">
<span className="text-xs font-medium leading-tight text-foreground">有新版本可用</span>
<span className="truncate text-[10px] text-muted-foreground">v{updateInfo.latest} · 点击查看</span>
</span>
)}
{collapsed && (
<span className="absolute right-1 top-1 size-2 rounded-full border-2 border-sidebar bg-primary" />
)}
{/* Background as an absolute layer so the collapsed rail shows a
centred squircle, not a full-width bar cut off with a hard edge. */}
<span
className={cn(
'absolute inset-y-0 rounded-lg bg-primary/10 transition-colors group-hover:bg-primary/[0.15]',
collapsed ? 'left-0.5 w-11' : 'inset-x-0',
)}
/>
<span className="relative z-10 grid w-12 shrink-0 place-items-center"><Sparkles className="size-4 text-primary" /></span>
<span className={cn('relative z-10 flex min-w-0 flex-1 flex-col overflow-hidden pr-3 transition-opacity duration-200', collapsed ? 'opacity-0' : 'opacity-100')}>
<span className="truncate whitespace-nowrap text-xs font-medium leading-tight text-foreground">有新版本可用</span>
<span className="truncate whitespace-nowrap text-[10px] text-muted-foreground">v{updateInfo.latest} · 点击查看</span>
</span>
</Link>
</div>
)}
<div className={cn('px-4 py-3 text-[10px] text-muted-foreground', collapsed && 'text-center px-2')}>
{collapsed ? '©' : `© ${new Date().getFullYear()} SnowLuma`}
{/* Footer: © + the pin toggle (desktop only). Pinning keeps the rail
expanded; unpinning returns it to the hover-to-peek rail. Mirrors the
「钉住侧栏展开」 appearance setting. */}
<div className={cn('flex shrink-0 items-center gap-2 py-3 pl-4 pr-2.5 transition-opacity duration-200', collapsed ? 'opacity-0' : 'opacity-100')}>
<span className="min-w-0 flex-1 truncate whitespace-nowrap text-[10px] text-muted-foreground">
© {new Date().getFullYear()} SnowLuma
</span>
{isDesktop && (
<button
type="button"
onClick={() => setAppearance({ sidebarPinned: !pinned })}
title={pinned ? '取消钉住(恢复悬停展开)' : '钉住侧栏(保持展开)'}
aria-label={pinned ? '取消钉住侧栏' : '钉住侧栏'}
aria-pressed={pinned}
tabIndex={collapsed ? -1 : 0}
className={cn(
'inline-flex size-7 shrink-0 items-center justify-center rounded-md transition-colors cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
pinned
? 'bg-primary/10 text-primary hover:bg-primary/15'
: 'text-muted-foreground hover:bg-sidebar-accent/50 hover:text-foreground',
)}
>
{pinned ? <Pin className="size-3.5" /> : <PinOff className="size-3.5" />}
</button>
)}
</div>
</div>
);
@@ -1,94 +1,27 @@
// Debug — a standalone top-level page (Wave A3, redesigned). Apple-HIG flavour:
// clarity (calm type hierarchy, generous whitespace), deference (translucent
// chrome, content-first), depth (soft layered cards, a sliding segmented
// control). Two tools over /api/debug/*:
// • Action 测试台 — pick account + action (schema form / raw JSON), invoke.
// • 实时活动 — merged live SSE of events + action calls.
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react';
// Debug — a multi-tab developer console over /api/debug/*. Tabs: the action
// tester, the visual message composer, the live activity feed, and an embedded
// API browser. The browser's 试一下 prefills the tester and switches to it.
// Apple-HIG flavour throughout (sliding-indicator tabs, translucent chrome).
import { useEffect, useState } from 'react';
import { motion } from 'motion/react';
import { Activity, Bug, ChevronRight, FlaskConical, Loader2, Pause, Play, RadioTower, Trash2 } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useApi } from '@/lib/api';
import { BookOpen, Bug, FlaskConical, MessageSquarePlus, RadioTower } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { DebugActionDoc, DebugInvokeResult, DebugStreamMessage, QQInfo } from '@/types';
import { Tabs } from '@/components/ui/tabs';
import { ActionTester } from '@/components/debug/action-tester';
import { MessageComposer } from '@/components/debug/message-composer';
import { LiveActivity } from '@/components/debug/live-activity';
import { ApiBrowser } from '@/components/debug/api-browser';
import { useApi } from '@/lib/api';
import type { DebugActionDoc, QQInfo } from '@/types';
const STREAM_CAP = 300;
interface StreamRow { id: number; at: number; msg: Extract<DebugStreamMessage, { kind: 'event' | 'action' | 'dropped' }> }
function coerceParam(type: string, raw: string): unknown {
if (raw === '') return undefined;
if (type.includes('int') || type === 'number' || type === 'uint') {
const n = Number(raw);
return Number.isFinite(n) ? n : raw;
}
if (type === 'bool' || type === 'boolean') return raw === 'true' || raw === '1';
return raw;
}
// ── iOS-style segmented control with a sliding active pill ──
function Segmented<T extends string>({ value, onChange, options }: {
value: T; onChange: (v: T) => void; options: { value: T; label: ReactNode }[];
}) {
const id = useId();
return (
<div role="radiogroup" className="inline-flex rounded-full bg-muted/70 p-0.5 text-sm">
{options.map((o) => {
const active = o.value === value;
return (
<button
key={o.value}
type="button"
role="radio"
aria-checked={active}
onClick={() => onChange(o.value)}
className={cn('relative rounded-full px-3.5 py-1 font-medium transition-colors',
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground')}
>
{active && (
<motion.span
layoutId={`seg-${id}`}
transition={{ type: 'spring', stiffness: 500, damping: 38 }}
className="absolute inset-0 rounded-full bg-card shadow-sm ring-1 ring-border/50"
/>
)}
<span className="relative z-10">{o.label}</span>
</button>
);
})}
</div>
);
}
function Field({ label, children }: { label: ReactNode; children: ReactNode }) {
return (
<label className="flex flex-col gap-1.5">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
{children}
</label>
);
}
const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm';
type Tab = 'tester' | 'compose' | 'activity' | 'api';
export function DebugPage() {
const api = useApi();
// ── action tester ──
const [accounts, setAccounts] = useState<QQInfo[]>([]);
const [docs, setDocs] = useState<DebugActionDoc[]>([]);
const [uin, setUin] = useState('');
const [actionName, setActionName] = useState('');
const [fields, setFields] = useState<Record<string, string>>({});
const [paramMode, setParamMode] = useState<'form' | 'json'>('form');
const [rawJson, setRawJson] = useState('{}');
const [invoking, setInvoking] = useState(false);
const [result, setResult] = useState<DebugInvokeResult | { error: string } | null>(null);
const doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]);
const effectiveMode = paramMode === 'json' || !doc ? 'json' : 'form';
const [tab, setTab] = useState<Tab>('tester');
const [preset, setPreset] = useState<{ name: string; nonce: number } | undefined>();
useEffect(() => {
void (async () => {
@@ -96,64 +29,20 @@ export function DebugPage() {
const [qq, acts] = await Promise.all([api.qqList(), api.debug.actions()]);
setAccounts(qq);
setDocs(acts.actions);
if (qq[0]) setUin(qq[0].uin);
} catch { /* surfaced lazily on invoke */ }
})();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}, [api]);
const invoke = async () => {
if (!uin) { setResult({ error: '请选择账号' }); return; }
if (!actionName.trim()) { setResult({ error: '请填写 action' }); return; }
let params: Record<string, unknown> = {};
if (effectiveMode === 'json') {
try { params = JSON.parse(rawJson || '{}'); } catch { setResult({ error: 'params JSON 无效' }); return; }
if (typeof params !== 'object' || params === null || Array.isArray(params)) { setResult({ error: 'params 必须是对象' }); return; }
} else if (doc) {
for (const p of doc.params) {
const v = coerceParam(p.type, fields[p.name] ?? '');
if (v !== undefined) params[p.name] = v;
}
}
setInvoking(true);
setResult(null);
try { setResult(await api.debug.invoke(uin, actionName.trim(), params)); }
catch (e) { setResult({ error: e instanceof Error ? e.message : '调用失败' }); }
finally { setInvoking(false); }
const tryAction = (name: string) => {
setPreset((p) => ({ name, nonce: (p?.nonce ?? 0) + 1 }));
setTab('tester');
};
const resultFailed = !!result && ('error' in result || result.status === 'failed');
// ── live stream ──
const [rows, setRows] = useState<StreamRow[]>([]);
const [paused, setPaused] = useState(false);
const [status, setStatus] = useState<'open' | 'reconnecting' | 'closed'>('closed');
const [kindFilter, setKindFilter] = useState<'all' | 'event' | 'action'>('all');
const pausedRef = useRef(paused);
pausedRef.current = paused;
const idRef = useRef(0);
useEffect(() => {
const off = api.debug.stream(
(m) => {
if (m.kind === 'ready' || pausedRef.current) return;
setRows((prev) => {
const next = [{ id: idRef.current++, at: Date.now(), msg: m }, ...prev];
return next.length > STREAM_CAP ? next.slice(0, STREAM_CAP) : next;
});
},
(s) => setStatus(s),
);
return off;
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const visible = rows.filter((r) => kindFilter === 'all' || r.msg.kind === kindFilter);
return (
<div className="mx-auto flex max-w-6xl flex-col gap-6">
{/* header */}
<motion.header
initial={{ opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }}
className="sticky top-0 z-10 -mx-1 flex items-center justify-between gap-4 rounded-b-2xl bg-background/60 px-1 py-3 backdrop-blur-xl"
className="sticky top-0 z-20 -mx-1 flex flex-col gap-3 rounded-b-2xl bg-background/60 px-1 py-3 backdrop-blur-xl"
>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-primary/10 text-primary">
@@ -161,201 +50,31 @@ export function DebugPage() {
</div>
<div>
<h1 className="text-2xl font-semibold tracking-tight">调试</h1>
<p className="text-sm text-muted-foreground">接口测试台与实时活动观测</p>
<p className="text-sm text-muted-foreground">接口测试 · 消息构建 · 实时观测 · API 参考</p>
</div>
</div>
<StatusPill status={status} />
<Tabs
aria-label="调试工具"
value={tab}
onChange={setTab}
items={[
{ value: 'tester', label: '测试台', icon: <FlaskConical className="h-4 w-4" /> },
{ value: 'compose', label: '消息构建', icon: <MessageSquarePlus className="h-4 w-4" /> },
{ value: 'activity', label: '实时活动', icon: <RadioTower className="h-4 w-4" /> },
{ value: 'api', label: 'API 浏览器', icon: <BookOpen className="h-4 w-4" />, badge: docs.length || undefined },
]}
/>
</motion.header>
<div className="grid grid-cols-1 gap-6 xl:grid-cols-12">
{/* tester */}
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.05 }}
className={cn(cardCls, 'flex flex-col gap-5 p-6 xl:col-span-5')}
>
<div className="flex items-center gap-2.5">
<FlaskConical className="h-[18px] w-[18px] text-primary" />
<h2 className="text-[15px] font-semibold tracking-tight">Action 测试台</h2>
</div>
<div className="flex items-start gap-2 rounded-xl bg-amber-500/10 px-3 py-2 text-[12px] leading-relaxed text-amber-700 dark:text-amber-300">
<span>调用会<strong className="font-semibold">真实生效</strong>(真发消息 / 真踢人等),请谨慎。</span>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<Field label="账号">
<Select value={uin} onChange={(e) => setUin(e.target.value)}>
{accounts.length === 0 && <option value="">(无在线账号)</option>}
{accounts.map((a) => <option key={a.uin} value={a.uin}>{a.nickname || a.uin}</option>)}
</Select>
</Field>
<Field label="Action">
<Input list="dbg-actions" value={actionName} placeholder="send_group_msg"
onChange={(e) => { setActionName(e.target.value); setResult(null); }} />
<datalist id="dbg-actions">
{docs.map((d) => <option key={d.name} value={d.name}>{d.summary}</option>)}
</datalist>
</Field>
</div>
{doc && (
<p className="-mt-1 text-[12px] text-muted-foreground">
{doc.summary}{doc.returns ? <> · 返回 <code className="font-mono text-[11px]">{doc.returns}</code></> : null}
</p>
)}
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">参数</span>
<Segmented
value={effectiveMode}
onChange={(m) => setParamMode(m)}
options={[{ value: 'form', label: '表单' }, { value: 'json', label: 'JSON' }]}
/>
</div>
{effectiveMode === 'json' ? (
<Textarea className="min-h-28 rounded-xl font-mono text-xs" value={rawJson}
onChange={(e) => setRawJson(e.target.value)} placeholder='{ "group_id": 12345, "message": "hi" }' />
) : (
<div className="flex flex-col gap-3">
{doc!.params.length === 0 && <p className="text-[12px] text-muted-foreground">该接口无参数。</p>}
{doc!.params.map((p) => (
<Field key={p.name} label={<>{p.name}<span className="ml-1 font-normal text-muted-foreground/70">{p.type}{p.required ? ' · 必填' : ''}</span></>}>
<Input value={fields[p.name] ?? ''}
onChange={(e) => setFields((f) => ({ ...f, [p.name]: e.target.value }))}
placeholder={p.desc || (p.default !== undefined ? `默认 ${JSON.stringify(p.default)}` : '')} />
</Field>
))}
</div>
)}
<button type="button" onClick={invoke} disabled={invoking}
className="inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary text-[15px] font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.99] disabled:opacity-50">
{invoking ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />} 执行
</button>
{result && (
<div className="flex flex-col gap-1.5">
<span className={cn('text-xs font-medium', resultFailed ? 'text-destructive' : 'text-success')}>
{resultFailed ? '失败' : '成功'}
</span>
<pre className={cn('max-h-72 overflow-auto rounded-xl border border-border/60 bg-muted/30 p-4 font-mono text-[11.5px] leading-relaxed',
resultFailed && 'text-destructive')}>
{JSON.stringify(result, null, 2)}
</pre>
</div>
)}
</motion.section>
{/* live stream */}
<motion.section
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.1 }}
className={cn(cardCls, 'flex min-h-[28rem] flex-col p-6 xl:col-span-7')}
>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2.5">
<RadioTower className="h-[18px] w-[18px] text-primary" />
<h2 className="text-[15px] font-semibold tracking-tight">实时活动</h2>
<span className="text-xs text-muted-foreground tabular-nums">{visible.length}</span>
</div>
<div className="flex items-center gap-2">
<Segmented
value={kindFilter}
onChange={setKindFilter}
options={[{ value: 'all', label: '全部' }, { value: 'event', label: '事件' }, { value: 'action', label: '调用' }]}
/>
<IconBtn onClick={() => setPaused((v) => !v)} title={paused ? '继续' : '暂停'}>
{paused ? <Play className="h-4 w-4" /> : <Pause className="h-4 w-4" />}
</IconBtn>
<IconBtn onClick={() => setRows([])} title="清空"><Trash2 className="h-4 w-4" /></IconBtn>
</div>
</div>
<div className="mt-4 flex flex-1 flex-col gap-1 overflow-auto">
{visible.length === 0 ? (
<div className="flex flex-1 flex-col items-center justify-center gap-3 py-12 text-center">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-muted/60">
<Activity className="h-6 w-6 text-muted-foreground/70" />
</div>
<p className="text-sm text-muted-foreground">{paused ? '已暂停' : '等待事件…'}</p>
</div>
) : (
visible.map((r) => <StreamRowItem key={r.id} row={r} />)
)}
</div>
</motion.section>
</div>
</div>
);
}
function IconBtn({ onClick, title, children }: { onClick: () => void; title: string; children: ReactNode }) {
return (
<button type="button" onClick={onClick} title={title} aria-label={title}
className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
{children}
</button>
);
}
function StatusPill({ status }: { status: 'open' | 'reconnecting' | 'closed' }) {
const map = {
open: { dot: 'bg-emerald-500', label: '已连接', glow: 'shadow-[0_0_0_3px_rgb(16_185_129/0.15)]' },
reconnecting: { dot: 'bg-amber-500', label: '重连中', glow: 'shadow-[0_0_0_3px_rgb(245_158_11/0.15)]' },
closed: { dot: 'bg-muted-foreground/50', label: '未连接', glow: '' },
}[status];
return (
<div className="inline-flex items-center gap-2 rounded-full border border-border/60 bg-card/70 px-3 py-1.5 text-xs font-medium backdrop-blur-sm">
<span className={cn('h-2 w-2 rounded-full', map.dot, map.glow)} />
<span className="text-muted-foreground">{map.label}</span>
</div>
);
}
function StreamRowItem({ row }: { row: StreamRow }) {
const [open, setOpen] = useState(false);
const { msg } = row;
const time = new Date(row.at).toLocaleTimeString('zh-CN', { hour12: false });
if (msg.kind === 'dropped') {
return <div className="px-2 py-1.5 text-[11px] text-amber-600 dark:text-amber-400">因客户端过慢丢弃了 {msg.count} 条</div>;
}
const isAction = msg.kind === 'action';
let label: string;
let detail: unknown;
let ok = true;
if (msg.kind === 'event') {
const e = msg.event as Record<string, unknown>;
label = `${e.post_type ?? 'event'}${e.message_type ? `.${e.message_type}` : e.notice_type ? `.${e.notice_type}` : ''}`;
detail = e;
} else {
ok = (msg.response as { status?: string }).status === 'ok';
label = msg.action;
detail = { params: msg.params, response: msg.response };
}
return (
<div className="group rounded-xl transition-colors hover:bg-muted/40">
<button type="button" aria-expanded={open} className="flex w-full items-center gap-2.5 px-2.5 py-2 text-left text-[13px]" onClick={() => setOpen((v) => !v)}>
<ChevronRight className={cn('h-3.5 w-3.5 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
<span className="shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums">{time}</span>
<span className={cn('shrink-0 rounded-md px-1.5 py-0.5 text-[10px] font-semibold',
isAction ? 'bg-primary/12 text-primary' : 'bg-muted text-muted-foreground')}>
{isAction ? '调用' : '事件'}
</span>
<span className="shrink-0 font-mono text-[11px] text-muted-foreground/80">{msg.uin}</span>
<span className="min-w-0 flex-1 truncate font-mono text-foreground/90">{label}</span>
{isAction && (
<span className={cn('shrink-0 text-[11px] tabular-nums', ok ? 'text-success' : 'text-destructive')}>
{ok ? 'ok' : 'failed'} · {msg.ms}ms
</span>
)}
</button>
{open && (
<pre className="mx-2.5 mb-2 max-h-72 overflow-auto rounded-lg bg-muted/40 p-3 font-mono text-[11px] leading-relaxed">
{JSON.stringify(detail, null, 2)}
</pre>
)}
{/* Tester / compose / activity stay MOUNTED and toggle via CSS so the
live feed's SSE never drops (it must capture events fired from other
tabs) and in-progress params/messages survive a peek at another tab.
ApiBrowser has no state worth preserving and is heavy (~520 rows), so
it mounts on demand. */}
<div className={cn(tab !== 'tester' && 'hidden')}><ActionTester accounts={accounts} docs={docs} presetAction={preset} /></div>
<div className={cn(tab !== 'compose' && 'hidden')}><MessageComposer accounts={accounts} /></div>
<div className={cn(tab !== 'activity' && 'hidden')}><LiveActivity /></div>
{tab === 'api' && <ApiBrowser docs={docs} onTry={tryAction} />}
</div>
);
}
@@ -0,0 +1,71 @@
// FaceGrid — pick a QQ classic face id. Renders the classic face sprites from
// QQ's long-standing public CDN; any id whose image 404s hides itself, so a
// curated-but-imperfect id list still looks clean. A manual id box is the
// escape hatch for faces outside the classic range.
import { useMemo, useState } from 'react';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
// Classic QQ face ids that resolve on the gtimg CDN. Curated to avoid the gaps
// in the 0..170 range (deprecated / never-existed ids) that would 404.
const CLASSIC_FACE_IDS: number[] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42,
43, 46, 49, 53, 60, 63, 64, 66, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 96, 97, 98, 99, 100, 101, 102, 103, 104, 106, 109, 111,
116, 118, 120, 122, 123, 124, 125, 129, 144, 147, 171, 173, 174, 175, 176,
179, 180, 181, 182, 183, 201, 203, 212, 214, 219, 222, 227,
];
const faceUrl = (id: number) => `https://qzonestyle.gtimg.cn/qzone/em/e${id}.png`;
export function FaceGrid({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const [q, setQ] = useState('');
const [broken, setBroken] = useState<Set<number>>(() => new Set());
const ids = useMemo(() => {
const qq = q.trim();
const base = CLASSIC_FACE_IDS.filter((id) => !broken.has(id));
if (!qq) return base;
return base.filter((id) => String(id).includes(qq));
}, [q, broken]);
const selected = value.trim();
return (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="按 id 过滤…" className="h-8 flex-1" />
<Input
value={value}
onChange={(e) => onChange(e.target.value.replace(/[^\d]/g, ''))}
placeholder="id"
inputMode="numeric"
className="h-8 w-20 text-center font-mono"
aria-label="表情 id"
/>
</div>
<div className="grid max-h-48 grid-cols-8 gap-1 overflow-auto rounded-xl border border-border/60 bg-muted/30 p-2 sm:grid-cols-10">
{ids.map((id) => (
<button
key={id}
type="button"
title={`face ${id}`}
onClick={() => onChange(String(id))}
className={cn('flex aspect-square items-center justify-center rounded-lg p-1 transition-colors hover:bg-accent',
selected === String(id) && 'bg-primary/15 ring-1 ring-primary/50')}
>
<img
src={faceUrl(id)}
alt={`face ${id}`}
className="h-full w-full object-contain"
loading="lazy"
onError={() => setBroken((prev) => { const n = new Set(prev); n.add(id); return n; })}
/>
</button>
))}
{ids.length === 0 && <span className="col-span-full py-4 text-center text-xs text-muted-foreground">无匹配表情</span>}
</div>
</div>
);
}
@@ -0,0 +1,152 @@
// JsonTree — a calm, collapsible JSON viewer for action responses / event
// payloads. Replaces a raw <pre> dump: nodes fold, values are colour-typed, the
// root offers copy, and a string that looks like an image URL gets an inline
// preview toggle. Read-only; no external deps.
import { useState, type ReactNode } from 'react';
import { Check, ChevronRight, Copy, Image as ImageIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
const IMAGE_URL_RE = /^https?:\/\/[^\s]+?\.(?:png|jpe?g|gif|webp|bmp)(?:[?#][^\s]*)?$/i;
// QQ multimedia rkey image URLs don't end in an extension but carry these hints.
const IMAGE_HINT_RE = /^https?:\/\/[^\s]*(?:rkey=|gchatpic|multimedia|c2cpicdw|offpic|gchat\.qpic)/i;
function isImageUrl(s: string): boolean {
return IMAGE_URL_RE.test(s) || IMAGE_HINT_RE.test(s);
}
function Punct({ children }: { children: ReactNode }) {
return <span className="text-muted-foreground/60">{children}</span>;
}
function Leaf({ value }: { value: string | number | boolean | null }) {
const [showImg, setShowImg] = useState(false);
if (value === null) return <span className="text-muted-foreground/70">null</span>;
if (typeof value === 'number') return <span className="text-sky-600 dark:text-sky-400 tabular-nums">{value}</span>;
if (typeof value === 'boolean') return <span className="text-violet-600 dark:text-violet-400">{String(value)}</span>;
// string
const img = isImageUrl(value);
return (
<span className="break-all">
<span className="text-emerald-700 dark:text-emerald-400">&quot;{value}&quot;</span>
{img && (
<>
<button
type="button"
onClick={() => setShowImg((v) => !v)}
className="ml-1.5 inline-flex items-center gap-0.5 rounded-md bg-muted/70 px-1 py-0.5 align-middle text-[10px] text-muted-foreground hover:text-foreground"
>
<ImageIcon className="h-3 w-3" /> {showImg ? '隐藏' : '预览'}
</button>
{showImg && (
<span className="mt-1.5 block">
<img src={value} alt="预览" className="max-h-48 rounded-lg border border-border/60" loading="lazy" />
</span>
)}
</>
)}
</span>
);
}
const NODE_CAP = 100; // render at most this many children before "show more"
function Node({ k, value, depth, defaultOpen }: { k?: string; value: unknown; depth: number; defaultOpen: boolean }) {
const isObj = typeof value === 'object' && value !== null;
const [open, setOpen] = useState(defaultOpen);
const [limit, setLimit] = useState(NODE_CAP);
const keyLabel = k != null ? <><span className="text-foreground/80">{k}</span><Punct>: </Punct></> : null;
if (!isObj) {
return (
<div className="flex gap-1 py-px pl-[1.1rem]" style={{ paddingLeft: `${depth * 0.9 + 1.1}rem` }}>
{keyLabel}
<Leaf value={value as string | number | boolean | null} />
</div>
);
}
const entries = Array.isArray(value)
? value.map((v, i) => [String(i), v] as const)
: Object.entries(value as Record<string, unknown>);
const openB = Array.isArray(value) ? '[' : '{';
const closeB = Array.isArray(value) ? ']' : '}';
const shown = open ? Math.min(entries.length, limit) : 0;
return (
<div>
<button
type="button"
onClick={() => setOpen((v) => !v)}
className="flex w-full items-center gap-1 py-px text-left hover:bg-muted/40"
style={{ paddingLeft: `${depth * 0.9}rem` }}
>
<ChevronRight className={cn('h-3 w-3 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
{keyLabel}
<Punct>{openB}</Punct>
{!open && <span className="text-muted-foreground/50">{entries.length}{Array.isArray(value) ? '' : ' keys'}<Punct>{closeB}</Punct></span>}
</button>
{open && (
<>
{entries.slice(0, shown).map(([ck, cv]) => (
<Node key={ck} k={Array.isArray(value) ? undefined : ck} value={cv} depth={depth + 1} defaultOpen={depth < 1} />
))}
{entries.length > shown && (
<button
type="button"
onClick={() => setLimit((l) => l + 500)}
className="py-0.5 text-[11px] text-primary hover:underline"
style={{ paddingLeft: `${depth * 0.9 + 1.1}rem` }}
>
还有 {entries.length - shown} 项,点击展开…
</button>
)}
<div style={{ paddingLeft: `${depth * 0.9 + 0.9}rem` }}><Punct>{closeB}</Punct></div>
</>
)}
</div>
);
}
export function JsonTree({ data, className, maxHeight = '20rem' }: { data: unknown; className?: string; maxHeight?: string }) {
const [copied, setCopied] = useState(false);
const text = (() => { try { return JSON.stringify(data, null, 2); } catch { return String(data); } })();
const copy = async () => {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
} else {
// navigator.clipboard is undefined on http LAN deployments — fall back
// to the legacy execCommand path so copy still works (and shows feedback).
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
setCopied(true);
setTimeout(() => setCopied(false), 1200);
} catch { /* clipboard blocked */ }
};
return (
<div className={cn('relative rounded-xl border border-border/60 bg-muted/30', className)}>
<button
type="button"
onClick={copy}
title="复制 JSON"
className="absolute right-2 top-2 z-10 inline-flex items-center gap-1 rounded-md bg-card/80 px-1.5 py-1 text-[11px] text-muted-foreground shadow-sm ring-1 ring-border/50 backdrop-blur hover:text-foreground"
>
{copied ? <Check className="h-3 w-3 text-success" /> : <Copy className="h-3 w-3" />}
{copied ? '已复制' : '复制'}
</button>
<div className="overflow-auto p-3 font-mono text-[11.5px] leading-relaxed" style={{ maxHeight }}>
<Node value={data} depth={0} defaultOpen />
</div>
</div>
);
}
+227
View File
@@ -0,0 +1,227 @@
// Picker — a searchable, windowed combobox for choosing from large lists
// (group members can be thousands). Apple-HIG flavour built on the same idiom
// as DropdownSelect: calm trigger matching Input height, a soft floating panel
// with a search field, virtualised rows (avatar + name + sub), keyboard nav,
// and an always-present escape hatch — if what you typed isn't in the list you
// can still commit it as a raw value. Loading / error / empty states degrade to
// the raw-value input so the picker never traps you.
import { useEffect, useMemo, useRef, useState } from 'react';
import { AnimatePresence, motion } from 'motion/react';
import { ChevronDown, Loader2, RefreshCw, Search } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface PickerOption {
value: string;
label: string;
/** Secondary line (e.g. the uin under a nickname). */
sub?: string;
/** Avatar URL. */
avatar?: string;
}
interface PickerProps {
value: string;
onChange: (v: string) => void;
options: ReadonlyArray<PickerOption>;
loading?: boolean;
error?: string | null;
onRefresh?: () => void;
placeholder?: string;
/** Validates a typed raw value before it can be committed via the escape
* hatch. Defaults to "non-empty". */
validateRaw?: (raw: string) => boolean;
ariaLabel: string;
className?: string;
disabled?: boolean;
}
const ROW_H = 44; // px — fixed row height drives the windowing math
const OVERSCAN = 6;
const PANEL_MAX = 264; // px of scroll viewport
export function Picker({
value, onChange, options, loading, error, onRefresh,
placeholder = '选择…', validateRaw, ariaLabel, className, disabled,
}: PickerProps) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [scrollTop, setScrollTop] = useState(0);
const [active, setActive] = useState(0);
const rootRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
const selected = options.find((o) => o.value === value);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return options;
return options.filter((o) => o.label.toLowerCase().includes(q) || o.value.includes(q) || (o.sub?.toLowerCase().includes(q) ?? false));
}, [options, query]);
// The escape-hatch row: show when the query is a committable raw value that
// isn't already an exact option.
const canRaw = query.trim() !== '' && (validateRaw ? validateRaw(query.trim()) : true)
&& !options.some((o) => o.value === query.trim());
const rawRow = canRaw ? query.trim() : null;
useEffect(() => {
if (!open) return;
setScrollTop(0);
setActive(0);
const t = setTimeout(() => searchRef.current?.focus(), 10);
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener('pointerdown', onPointer);
return () => { clearTimeout(t); document.removeEventListener('pointerdown', onPointer); };
}, [open]);
const totalRows = filtered.length + (rawRow ? 1 : 0);
// Keep the keyboard cursor in range when the list shrinks (refresh / typing)
// without a keystroke that would have reset it.
useEffect(() => {
setActive((a) => Math.min(a, Math.max(0, totalRows - 1)));
}, [totalRows]);
const viewH = Math.min(PANEL_MAX, totalRows * ROW_H);
const start = Math.max(0, Math.floor(scrollTop / ROW_H) - OVERSCAN);
const end = Math.min(totalRows, Math.ceil((scrollTop + viewH) / ROW_H) + OVERSCAN);
const commit = (v: string) => { onChange(v); setOpen(false); setQuery(''); };
const choose = (idx: number) => {
if (rawRow && idx === filtered.length) commit(rawRow);
else { const o = filtered[idx]; if (o) commit(o.value); }
};
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setOpen(false); return; }
if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => Math.min(totalRows - 1, a + 1)); }
else if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => Math.max(0, a - 1)); }
else if (e.key === 'Enter') { e.preventDefault(); choose(active); }
};
// Keep the active row scrolled into view.
useEffect(() => {
if (!open || !listRef.current) return;
const top = active * ROW_H;
const el = listRef.current;
if (top < el.scrollTop) el.scrollTop = top;
else if (top + ROW_H > el.scrollTop + el.clientHeight) el.scrollTop = top + ROW_H - el.clientHeight;
}, [active, open]);
const rows: { idx: number; opt: PickerOption | null }[] = [];
for (let i = start; i < end; i++) {
if (rawRow && i === filtered.length) rows.push({ idx: i, opt: null });
else rows.push({ idx: i, opt: filtered[i] ?? null });
}
return (
<div ref={rootRef} className={cn('relative', className)} onKeyDown={onKeyDown}>
<button
type="button"
disabled={disabled}
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
onClick={() => !disabled && setOpen((v) => !v)}
className={cn(
'flex h-9 w-full items-center gap-2 rounded-md border border-border bg-transparent px-3 text-sm outline-none transition-colors',
'focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring disabled:opacity-50',
!selected && !value && 'text-muted-foreground',
)}
>
{selected?.avatar && <img src={selected.avatar} alt="" className="h-5 w-5 shrink-0 rounded-full" />}
<span className="min-w-0 flex-1 truncate text-left">
{selected ? selected.label : value || placeholder}
{selected?.sub && <span className="ml-1.5 text-xs text-muted-foreground tabular-nums">{selected.sub}</span>}
</span>
<ChevronDown className={cn('h-4 w-4 shrink-0 text-muted-foreground transition-transform', open && 'rotate-180')} />
</button>
<AnimatePresence>
{open && (
<motion.div
initial={{ opacity: 0, y: -4, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -4, scale: 0.98 }}
transition={{ type: 'spring', stiffness: 500, damping: 38 }}
className="absolute z-50 mt-1.5 w-full overflow-hidden rounded-xl border border-border/60 bg-popover shadow-lg ring-1 ring-black/5"
>
<div className="flex items-center gap-2 border-b border-border/60 px-2.5 py-2">
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input
ref={searchRef}
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
setScrollTop(0);
if (listRef.current) listRef.current.scrollTop = 0;
}}
placeholder="搜索名称 / 号码…"
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
{onRefresh && (
<button type="button" title="刷新" onClick={onRefresh}
className="shrink-0 text-muted-foreground hover:text-foreground">
<RefreshCw className={cn('h-3.5 w-3.5', loading && 'animate-spin')} />
</button>
)}
</div>
{loading && options.length === 0 ? (
<div className="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> 加载中…
</div>
) : error ? (
<div className="px-3 py-6 text-center text-xs text-muted-foreground">
<p className="text-destructive">{error}</p>
<p className="mt-1">可直接在上方输入号码后回车使用</p>
</div>
) : totalRows === 0 ? (
<div className="px-3 py-6 text-center text-xs text-muted-foreground">无匹配项{query && ';输入完整号码可直接使用'}</div>
) : (
<div
ref={listRef}
role="listbox"
onScroll={(e) => setScrollTop((e.target as HTMLDivElement).scrollTop)}
className="overflow-auto"
style={{ height: viewH }}
>
<div style={{ height: totalRows * ROW_H, position: 'relative' }}>
{rows.map(({ idx, opt }) => (
<div
key={opt ? opt.value : `__raw-${idx}`}
role="option"
aria-selected={idx === active}
onMouseEnter={() => setActive(idx)}
onClick={() => choose(idx)}
className={cn(
'absolute left-0 right-0 flex cursor-pointer items-center gap-2.5 px-3',
idx === active ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
)}
style={{ top: idx * ROW_H, height: ROW_H }}
>
{opt ? (
<>
{opt.avatar
? <img src={opt.avatar} alt="" className="h-7 w-7 shrink-0 rounded-full" />
: <span className="h-7 w-7 shrink-0 rounded-full bg-muted" />}
<span className="min-w-0 flex-1 truncate text-sm">{opt.label}</span>
{opt.sub && <span className="shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums">{opt.sub}</span>}
</>
) : (
<span className="text-sm">使用 <span className="font-mono text-primary">{rawRow}</span></span>
)}
</div>
))}
</div>
</div>
)}
</motion.div>
)}
</AnimatePresence>
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
// Tabs — a horizontal tab bar with an Apple-HIG sliding indicator. Shares the
// spring-pill idiom of the debug page's segmented control but scaled up for
// top-level section switching, with full roving-tabindex keyboard support
// (←/→/Home/End). Generic over a string union of tab ids.
import { useId, useRef, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { cn } from '@/lib/utils';
export interface TabItem<T extends string> {
value: T;
label: ReactNode;
/** Optional leading icon (already sized by the caller, ~16px). */
icon?: ReactNode;
/** Optional trailing count / badge. */
badge?: ReactNode;
}
interface TabsProps<T extends string> {
value: T;
onChange: (v: T) => void;
items: ReadonlyArray<TabItem<T>>;
className?: string;
'aria-label'?: string;
}
export function Tabs<T extends string>({ value, onChange, items, className, ...rest }: TabsProps<T>) {
const layoutId = useId();
const refs = useRef<(HTMLButtonElement | null)[]>([]);
const move = (from: number, dir: 1 | -1 | 'home' | 'end') => {
const n = items.length;
let to: number;
if (dir === 'home') to = 0;
else if (dir === 'end') to = n - 1;
else to = (from + dir + n) % n;
const next = items[to];
if (next) { onChange(next.value); refs.current[to]?.focus(); }
};
return (
<div
role="tablist"
aria-label={rest['aria-label']}
className={cn('relative flex items-center gap-1 overflow-x-auto', className)}
>
{items.map((it, i) => {
const active = it.value === value;
return (
<button
key={it.value}
ref={(el) => { refs.current[i] = el; }}
role="tab"
type="button"
aria-selected={active}
tabIndex={active ? 0 : -1}
onClick={() => onChange(it.value)}
onKeyDown={(e) => {
if (e.key === 'ArrowRight') { e.preventDefault(); move(i, 1); }
else if (e.key === 'ArrowLeft') { e.preventDefault(); move(i, -1); }
else if (e.key === 'Home') { e.preventDefault(); move(i, 'home'); }
else if (e.key === 'End') { e.preventDefault(); move(i, 'end'); }
}}
className={cn(
'relative z-10 inline-flex shrink-0 items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-medium outline-none transition-colors',
'focus-visible:ring-[3px] focus-visible:ring-ring/40',
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
)}
>
{active && (
<motion.span
layoutId={`tabs-${layoutId}`}
transition={{ type: 'spring', stiffness: 500, damping: 40 }}
className="absolute inset-0 -z-10 rounded-xl bg-card shadow-sm ring-1 ring-border/60"
/>
)}
{it.icon}
<span>{it.label}</span>
{it.badge != null && (
<span className={cn('rounded-full px-1.5 text-[11px] tabular-nums',
active ? 'bg-primary/12 text-primary' : 'bg-muted text-muted-foreground')}>
{it.badge}
</span>
)}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,110 @@
// DebugTaskContext — an app-level registry of in-flight debug-console tasks
// (file uploads, streaming invocations) so they survive tab/page switches
// WITHIN the app (their state lives above the page, not in the unmounting tab).
// A full page unload (refresh / close) can't be survived, so a beforeunload
// guard warns while any task runs. Finished tasks linger briefly for history.
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
export type DebugTaskStatus = 'running' | 'done' | 'failed' | 'canceled';
export type DebugTaskKind = 'upload' | 'stream' | 'invoke';
export interface DebugTask {
id: string;
kind: DebugTaskKind;
label: string;
status: DebugTaskStatus;
/** 0..1 when determinate; undefined = indeterminate. */
progress?: number;
detail?: string;
startedAt: number;
endedAt?: number;
/** Cancel the underlying work (abort the fetch / xhr). */
cancel?: () => void;
}
interface DebugTaskContextValue {
tasks: DebugTask[];
/** Register a task; returns its id. */
start: (task: Omit<DebugTask, 'id' | 'status' | 'startedAt'> & { id?: string }) => string;
update: (id: string, patch: Partial<Omit<DebugTask, 'id'>>) => void;
/** Mark terminal (done/failed/canceled) and stamp endedAt. */
finish: (id: string, status: Exclude<DebugTaskStatus, 'running'>, detail?: string) => void;
remove: (id: string) => void;
clearFinished: () => void;
}
const Ctx = createContext<DebugTaskContextValue | null>(null);
let seq = 0;
const nextId = () => `dt-${Date.now().toString(36)}-${(seq++).toString(36)}`;
export function DebugTaskProvider({ children }: { children: ReactNode }) {
const [tasks, setTasks] = useState<DebugTask[]>([]);
const start = useCallback<DebugTaskContextValue['start']>((t) => {
const id = t.id ?? nextId();
setTasks((prev) => {
const next = [{ ...t, id, status: 'running' as const, startedAt: Date.now() }, ...prev];
if (next.length <= 50) return next;
// Over cap: evict the OLDEST finished tasks only — never drop a running
// task (that would orphan its finish()/cancel handle while it keeps going).
const running = next.filter((x) => x.status === 'running').length;
const finished = next.filter((x) => x.status !== 'running');
const drop = new Set(finished.slice(Math.max(0, 50 - running)).map((x) => x.id));
return next.filter((x) => !drop.has(x.id));
});
return id;
}, []);
const update = useCallback<DebugTaskContextValue['update']>((id, patch) => {
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
}, []);
const finish = useCallback<DebugTaskContextValue['finish']>((id, status, detail) => {
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, status, detail: detail ?? t.detail, endedAt: Date.now(), cancel: undefined } : t)));
}, []);
const remove = useCallback<DebugTaskContextValue['remove']>((id) => {
setTasks((prev) => prev.filter((t) => t.id !== id));
}, []);
const clearFinished = useCallback(() => {
setTasks((prev) => prev.filter((t) => t.status === 'running'));
}, []);
// beforeunload guard: a real page unload kills in-flight tasks, so warn while
// any task is still running (within-app navigation is safe — state is here).
useEffect(() => {
const anyRunning = tasks.some((t) => t.status === 'running');
if (!anyRunning) return;
const handler = (e: BeforeUnloadEvent) => { e.preventDefault(); e.returnValue = ''; };
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [tasks]);
const value = useMemo<DebugTaskContextValue>(
() => ({ tasks, start, update, finish, remove, clearFinished }),
[tasks, start, update, finish, remove, clearFinished],
);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}
export function useDebugTasks(): DebugTaskContextValue {
const v = useContext(Ctx);
if (!v) throw new Error('useDebugTasks must be used within DebugTaskProvider');
return v;
}
/** Convenience: count + aggregate progress of running tasks, for the badge. */
export function useRunningTaskSummary(): { count: number; progress: number | null } {
const { tasks } = useDebugTasks();
return useMemo(() => {
const running = tasks.filter((t) => t.status === 'running');
if (running.length === 0) return { count: 0, progress: null };
const determinate = running.filter((t) => typeof t.progress === 'number');
const progress = determinate.length
? determinate.reduce((s, t) => s + (t.progress ?? 0), 0) / determinate.length
: null;
return { count: running.length, progress };
}, [tasks]);
}
@@ -0,0 +1,174 @@
// Debug contacts data layer — lazy-loads friend / group / member lists for the
// debug console's pickers via the read-only OneBot actions, with a shared
// module-level cache persisted to localStorage (version-stamped) and a short
// TTL. Every loader degrades gracefully: on error the hook returns the error so
// the Picker can fall back to raw input. One cache is shared across every
// picker instance (tester form, message builder, etc.).
import { useCallback, useEffect, useRef, useState } from 'react';
import { useApi } from '@/lib/api';
import type { PickerOption } from '@/components/ui/picker';
const CACHE_VERSION = 1; // bump to invalidate all persisted entries
const TTL_MS = 5 * 60_000;
const LS_KEY = `snowluma.debug.contacts.v${CACHE_VERSION}`;
export function userAvatar(uin: string | number): string {
return `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=100`;
}
export function groupAvatar(gid: string | number): string {
return `https://p.qlogo.cn/gh/${gid}/${gid}/100`;
}
interface Entry { at: number; items: PickerOption[] }
// Avatars are derivable from the id + the list kind (encoded in the cache-key
// prefix), so they're stripped before persisting (a big member list × long
// avatar URLs would otherwise blow the ~5MB localStorage quota and silently
// kill persistence for ALL entries) and regenerated on hydrate.
function avatarFor(key: string, value: string): string | undefined {
if (key.startsWith('groups:')) return groupAvatar(value);
if (key.startsWith('friends:') || key.startsWith('members:')) return userAvatar(value);
return undefined;
}
// ── shared cache (module-level, hydrated from localStorage once) ──
const mem = new Map<string, Entry>();
let hydrated = false;
function hydrate(): void {
if (hydrated) return;
hydrated = true;
try {
const raw = localStorage.getItem(LS_KEY);
if (raw) {
const obj = JSON.parse(raw) as Record<string, Entry>;
for (const [k, v] of Object.entries(obj)) {
if (v && Array.isArray(v.items)) {
mem.set(k, { at: v.at, items: v.items.map((it) => ({ ...it, avatar: it.avatar ?? avatarFor(k, it.value) })) });
}
}
}
} catch { /* corrupt / unavailable — start empty */ }
}
function persist(): void {
try {
const obj: Record<string, Entry> = {};
// Strip the derivable avatar to keep the serialized blob small.
for (const [k, v] of mem) obj[k] = { at: v.at, items: v.items.map((it) => ({ value: it.value, label: it.label, sub: it.sub })) };
localStorage.setItem(LS_KEY, JSON.stringify(obj));
} catch { /* quota / unavailable — memory cache still works */ }
}
/** Drop every cached contact list (the data layer's "清缓存" button). */
export function clearDebugContactsCache(): void {
mem.clear();
try { localStorage.removeItem(LS_KEY); } catch { /* ignore */ }
}
type ParseRow = (row: Record<string, unknown>) => PickerOption | null;
interface ListState {
items: PickerOption[];
loading: boolean;
error: string | null;
refresh: () => void;
}
function useContactList(cacheKey: string | null, action: string, uin: string, params: Record<string, unknown>, parse: ParseRow): ListState {
const api = useApi();
hydrate();
const [items, setItems] = useState<PickerOption[]>(() => (cacheKey && mem.get(cacheKey)?.items) || []);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const reqId = useRef(0);
const load = useCallback(async (force: boolean) => {
if (!cacheKey || !uin) return;
const cached = mem.get(cacheKey);
if (!force && cached && Date.now() - cached.at < TTL_MS) {
setItems(cached.items);
return;
}
const myId = ++reqId.current;
setLoading(true);
setError(null);
try {
const res = await api.debug.invoke(uin, action, params);
if (myId !== reqId.current) return; // superseded
if (res.status !== 'ok') throw new Error(res.message || res.wording || '加载失败');
const arr = Array.isArray(res.data) ? (res.data as Record<string, unknown>[]) : [];
const mapped = arr.map(parse).filter((x): x is PickerOption => x !== null);
mem.set(cacheKey, { at: Date.now(), items: mapped });
persist();
setItems(mapped);
} catch (e) {
if (myId !== reqId.current) return;
setError(e instanceof Error ? e.message : '加载失败');
// keep any stale items visible as a fallback
} finally {
if (myId === reqId.current) setLoading(false);
}
// params + parse are stable per call-site (their identity is captured by
// cacheKey, which already varies on uin/group), so excluding them is
// deliberate — including the fresh object/closure would reload every render.
}, [api, cacheKey, uin, action]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!cacheKey || !uin) { setItems([]); return; }
const cached = mem.get(cacheKey);
// Clear stale items when switching to an uncached key — otherwise the picker
// would show the previous account/group's contacts as valid until the fetch
// returns (a member-selection hazard).
setItems(cached ? cached.items : []);
void load(false);
}, [cacheKey, uin, load]);
return { items, loading, error, refresh: () => void load(true) };
}
export function useFriends(uin: string): ListState {
return useContactList(
uin ? `friends:${uin}` : null,
'get_friend_list',
uin,
{},
(r) => {
const id = r.user_id;
if (id == null) return null;
const v = String(id);
const nick = (r.remark as string) || (r.nickname as string) || v;
return { value: v, label: nick, sub: v, avatar: userAvatar(v) };
},
);
}
export function useGroups(uin: string): ListState {
return useContactList(
uin ? `groups:${uin}` : null,
'get_group_list',
uin,
{},
(r) => {
const id = r.group_id;
if (id == null) return null;
const v = String(id);
return { value: v, label: (r.group_name as string) || v, sub: v, avatar: groupAvatar(v) };
},
);
}
export function useGroupMembers(uin: string, groupId: string): ListState {
const gid = groupId.trim();
return useContactList(
uin && gid ? `members:${uin}:${gid}` : null,
'get_group_member_list',
uin,
{ group_id: gid },
(r) => {
const id = r.user_id;
if (id == null) return null;
const v = String(id);
const name = (r.card as string) || (r.nickname as string) || v;
return { value: v, label: name, sub: v, avatar: userAvatar(v) };
},
);
}
+85
View File
@@ -128,6 +128,9 @@ class HttpApiClient implements ApiClient {
actions: () => this.getJson<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>('/api/debug/actions'),
invoke: (uin: string, action: string, params: Record<string, unknown>) =>
this.postJson<DebugInvokeResult>('/api/debug/invoke', { uin, action, params }),
invokeStream: (uin, action, params, onFrame, signal) =>
this.openDebugInvokeStream(uin, action, params, onFrame, signal),
upload: (file, opts) => this.uploadDebugFile(file, opts),
stream: (onMessage, onStatus) => this.openDebugStream(onMessage, onStatus),
};
@@ -405,6 +408,88 @@ class HttpApiClient implements ApiClient {
};
}
// Invoke a (stream) action and relay each `data: <json>\n\n` SSE frame. Uses
// fetch + a body reader (not EventSource) so the bearer token rides in the
// header and the request can be a POST. Resolves when the stream ends.
private async openDebugInvokeStream(
uin: string,
action: string,
params: Record<string, unknown>,
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
signal?: AbortSignal,
): Promise<void> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
const res = await fetch('/api/debug/invoke-stream', {
method: 'POST',
headers,
body: JSON.stringify({ uin, action, params }),
signal,
});
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
throw new ApiError(401, '未授权');
}
if (!res.ok || !res.body) {
const payload = await readJson<ErrorPayload>(res).catch(() => ({}) as ErrorPayload);
throw new ApiError(res.status, extractErrorMessage(payload, '流式调用失败'), payload.code);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let sep: number;
while ((sep = buf.indexOf('\n\n')) >= 0) {
const block = buf.slice(0, sep);
buf = buf.slice(sep + 2);
const line = block.startsWith('data: ') ? block.slice(6) : block;
if (!line.trim()) continue;
try { onFrame(JSON.parse(line) as import('@/types').DebugStreamFrame); } catch { /* skip malformed */ }
}
}
}
// Upload a browser file to a server temp path. Uses XHR (not fetch) so the
// upload progress callback can fire — fetch can't observe request-body
// progress. Returns the parsed { path, size }.
private uploadDebugFile(
file: File,
opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
): Promise<import('@/types').DebugUploadResult> {
return new Promise((resolve, reject) => {
const name = opts?.filename ?? file.name;
const xhr = new XMLHttpRequest();
xhr.open('POST', `/api/debug/upload?filename=${encodeURIComponent(name)}`);
if (this.currentToken) xhr.setRequestHeader('Authorization', `Bearer ${this.currentToken}`);
xhr.responseType = 'json';
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) opts?.onProgress?.(e.loaded / e.total);
};
xhr.onload = () => {
if (xhr.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
reject(new ApiError(401, '未授权'));
return;
}
const body = (xhr.response ?? {}) as import('@/types').DebugUploadResult;
if (xhr.status >= 200 && xhr.status < 300 && body.path) resolve(body);
else reject(new ApiError(xhr.status, body.message || '上传失败'));
};
xhr.onerror = () => reject(new ApiError(0, '上传网络错误'));
xhr.onabort = () => reject(new ApiError(0, '上传已取消'));
if (opts?.signal) {
if (opts.signal.aborted) { xhr.abort(); return; }
opts.signal.addEventListener('abort', () => xhr.abort(), { once: true });
}
xhr.send(file);
});
}
private openDebugStream(
onMessage: (m: DebugStreamMessage) => void,
onStatus?: (s: import('./types').StreamStatus) => void,
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more