Refactor OneBot networks and event dispatch

Unify per-adapter network configuration into a single `networks` structure and add migration/normalization for legacy on-disk formats. Introduce per-adapter options (messageFormat, reportSelfMessage, enabled, name) and stronger typing in types.ts. Add event-filter utilities to prebuild two serialized payload variants and pick the right one per adapter to avoid repeated JSON.stringify calls. Update HTTP/WS transports to use adapter names/signatures for hot-reload, respect per-adapter options, and improve logging; WS transport also improves client/server lifecycle/reconnect handling. Mark self-sent messages as `message_sent` in the event converter and wire instance dispatch to use the new DispatchPayload. Misc: README edits and accompanying tests added/updated for the refactor.
This commit is contained in:
手瓜一十雪 committed 2026-05-07 16:01:28 +08:00
1 parent 19a564991c
commit 2a4ca46a99
14 files changed
+1732 -758

No files matched your search

@@ -12,12 +12,12 @@ import { Skeleton } from '@/components/ui/skeleton';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type {
HttpPostEndpoint,
HttpServerEndpoint,
MessageFormat,
NetworkKind,
OneBotConfig,
OneBotNetworks,
QQInfo,
WsClientEndpoint,
WsServerEndpoint,
WsRole,
} from '@/types';
interface ConfigPageProps {
@@ -34,6 +34,12 @@ function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
}
function generateAccessToken(): string {
const bytes = new Uint8Array(32);
globalThis.crypto.getRandomValues(bytes);
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
}
function Field({
label,
value,
@@ -92,30 +98,6 @@ function Section({ title, description, onAdd, children, count }: SectionProps) {
);
}
function EndpointRow({ children, onRemove }: { children: React.ReactNode; onRemove?: () => void }) {
return (
<motion.div
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18 }}
className="flex flex-col gap-3 rounded-lg border bg-card/40 p-3 sm:flex-row sm:items-end"
>
<div className="flex flex-1 flex-col gap-3 sm:flex-row sm:items-end">{children}</div>
{onRemove && (
<Button
variant="ghost"
size="icon-sm"
onClick={onRemove}
aria-label="删除"
className="self-end text-muted-foreground hover:text-destructive"
>
<Trash2 className="size-4" />
</Button>
)}
</motion.div>
);
}
export function ConfigPage({
qqList,
selectedUin,
@@ -217,200 +199,218 @@ export function ConfigPage({
</div>
</div>
{/* HTTP Servers */}
<Section
title="HTTP 服务监听"
description="开放 HTTP API,OneBot 客户端可主动发起请求"
count={config.httpServers.length}
onAdd={() => update({ ...config, httpServers: [...config.httpServers, { port: 3000, host: '0.0.0.0', path: '/' }] })}
title="通用设置"
description="OneBot 共享功能配置"
>
{config.httpServers.length === 0 ? (
<EmptyHint label="暂无 HTTP 服务" />
) : (
config.httpServers.map((s, idx) => (
<EndpointRow
key={idx}
onRemove={() => update({ ...config, httpServers: config.httpServers.filter((_, i) => i !== idx) })}
>
<Field
label="端口"
type="number"
value={s.port}
onChange={(v) =>
update({
...config,
httpServers: config.httpServers.map((it, i) => (i === idx ? { ...it, port: Number(v) || undefined } : it)) as HttpServerEndpoint[],
})
}
className="sm:w-32"
/>
<Field
label="授权 Token"
placeholder="不填则无密码"
value={s.accessToken}
onChange={(v) =>
update({
...config,
httpServers: config.httpServers.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="flex-1"
/>
</EndpointRow>
))
)}
</Section>
{/* HTTP Post */}
<Section
title="HTTP Post 推送"
description="向远端 URL 主动推送事件"
count={config.httpPostEndpoints.length}
onAdd={() => update({ ...config, httpPostEndpoints: [...config.httpPostEndpoints, { url: 'http://127.0.0.1:5700' }] })}
>
{config.httpPostEndpoints.length === 0 ? (
<EmptyHint label="暂无 HTTP 推送目标" />
) : (
config.httpPostEndpoints.map((s, idx) => (
<EndpointRow
key={idx}
onRemove={() =>
update({ ...config, httpPostEndpoints: config.httpPostEndpoints.filter((_, i) => i !== idx) })
}
>
<Field
label="目标 URL"
type="url"
placeholder="http://..."
value={s.url}
onChange={(v) =>
update({
...config,
httpPostEndpoints: config.httpPostEndpoints.map((it, i) => (i === idx ? { ...it, url: v } : it)) as HttpPostEndpoint[],
})
}
className="flex-1"
/>
<Field
label="授权 Token"
placeholder="可选"
value={s.accessToken}
onChange={(v) =>
update({
...config,
httpPostEndpoints: config.httpPostEndpoints.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="sm:w-64"
/>
</EndpointRow>
))
)}
</Section>
{/* WS Servers */}
<Section
title="WebSocket 服务监听"
description="开放 WS 服务,客户端可建立持久连接"
count={config.wsServers.length}
onAdd={() => update({ ...config, wsServers: [...config.wsServers, { port: 3001, host: '0.0.0.0', path: '/' }] })}
>
{config.wsServers.length === 0 ? (
<EmptyHint label="暂无 WS 服务" />
) : (
config.wsServers.map((s, idx) => (
<EndpointRow
key={idx}
onRemove={() => update({ ...config, wsServers: config.wsServers.filter((_, i) => i !== idx) })}
>
<Field
label="端口"
type="number"
value={s.port}
onChange={(v) =>
update({
...config,
wsServers: config.wsServers.map((it, i) => (i === idx ? { ...it, port: Number(v) || undefined } : it)) as WsServerEndpoint[],
})
}
className="sm:w-32"
/>
<Field
label="授权 Token"
placeholder="不填则无密码"
value={s.accessToken}
onChange={(v) =>
update({
...config,
wsServers: config.wsServers.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="flex-1"
/>
</EndpointRow>
))
)}
</Section>
{/* WS Clients */}
<Section
title="WebSocket 反向连出"
description="主动连接到外部 WS 服务器(reverse-ws)"
count={config.wsClients.length}
onAdd={() =>
update({
...config,
wsClients: [...config.wsClients, { url: 'ws://127.0.0.1:8080/ws', reconnectIntervalMs: 5000 }],
})
}
>
{config.wsClients.length === 0 ? (
<EmptyHint label="暂无反向 WS 客户端" />
) : (
config.wsClients.map((c, idx) => (
<EndpointRow
key={idx}
onRemove={() => update({ ...config, wsClients: config.wsClients.filter((_, i) => i !== idx) })}
>
<Field
label="目标 URL"
type="url"
placeholder="ws://..."
value={c.url}
onChange={(v) =>
update({
...config,
wsClients: config.wsClients.map((it, i) => (i === idx ? { ...it, url: v } : it)) as WsClientEndpoint[],
})
}
className="flex-1"
/>
<Field
label="授权 Token"
placeholder="可选"
value={c.accessToken}
onChange={(v) =>
update({
...config,
wsClients: config.wsClients.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="sm:w-64"
/>
</EndpointRow>
))
)}
</Section>
<Section title="音乐签名 URL" description="用于生成音乐卡片签名(可选)">
<Field
label="签名服务地址"
label="音乐签名服务 URL"
type="url"
placeholder="留空则不启用"
value={config.musicSignUrl}
onChange={(v) => update({ ...config, musicSignUrl: v || undefined })}
/>
</Section>
{/* HTTP Servers */}
<NetworkSection
title="HTTP API 服务"
description="本地监听 HTTP 端口,OneBot 客户端发起请求"
kind="httpServers"
networks={config.networks.httpServers}
onChange={(arr) => updateNetworks(config, update, 'httpServers', arr)}
renderFields={(item, patch) => (
<>
<Field
label="主机"
placeholder="0.0.0.0"
value={item.host}
onChange={(v) => patch({ host: v || undefined })}
className="sm:w-40"
/>
<Field
label="端口"
type="number"
value={item.port}
onChange={(v) => patch({ port: Number(v) || 0 })}
className="sm:w-28"
/>
<Field
label="路径"
placeholder="/"
value={item.path}
onChange={(v) => patch({ path: v || undefined })}
className="sm:w-32"
/>
<Field
label="授权 Token"
placeholder="不填则无密码"
value={item.accessToken}
onChange={(v) => patch({ accessToken: v || undefined })}
className="flex-1"
/>
</>
)}
defaultEntry={(suffix) => ({
name: `http-${suffix}`,
host: '0.0.0.0',
port: 3000,
path: '/',
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
})}
/>
{/* HTTP Clients (POST push) */}
<NetworkSection
title="HTTP 推送客户端"
description="主动向远端 URL POST 推送事件"
kind="httpClients"
networks={config.networks.httpClients}
onChange={(arr) => updateNetworks(config, update, 'httpClients', arr)}
renderFields={(item, patch) => (
<>
<Field
label="目标 URL"
type="url"
placeholder="http://..."
value={item.url}
onChange={(v) => patch({ url: v })}
className="flex-1"
/>
<Field
label="授权 Token"
placeholder="可选"
value={item.accessToken}
onChange={(v) => patch({ accessToken: v || undefined })}
className="sm:w-56"
/>
<Field
label="超时 (ms)"
type="number"
placeholder="5000"
value={item.timeoutMs}
onChange={(v) => patch({ timeoutMs: Number(v) || undefined })}
className="sm:w-32"
/>
</>
)}
defaultEntry={(suffix) => ({
name: `httppost-${suffix}`,
url: 'http://127.0.0.1:5700',
messageFormat: 'array',
reportSelfMessage: false,
})}
/>
{/* WebSocket Servers */}
<NetworkSection
title="WebSocket 服务"
description="本地监听 WebSocket 端口,客户端建立持久连接"
kind="wsServers"
networks={config.networks.wsServers}
onChange={(arr) => updateNetworks(config, update, 'wsServers', arr)}
renderFields={(item, patch) => (
<>
<Field
label="主机"
placeholder="0.0.0.0"
value={item.host}
onChange={(v) => patch({ host: v || undefined })}
className="sm:w-40"
/>
<Field
label="端口"
type="number"
value={item.port}
onChange={(v) => patch({ port: Number(v) || 0 })}
className="sm:w-28"
/>
<Field
label="路径"
placeholder="/"
value={item.path}
onChange={(v) => patch({ path: v || undefined })}
className="sm:w-32"
/>
<SelectField
label="角色"
value={item.role ?? 'universal'}
options={WS_ROLE_OPTIONS}
onChange={(v) => patch({ role: v })}
className="sm:w-32"
/>
<Field
label="授权 Token"
placeholder="不填则无密码"
value={item.accessToken}
onChange={(v) => patch({ accessToken: v || undefined })}
className="flex-1"
/>
</>
)}
defaultEntry={(suffix) => ({
name: `ws-${suffix}`,
host: '0.0.0.0',
port: 3001,
path: '/',
role: 'universal' as WsRole,
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
})}
/>
{/* WebSocket Clients (reverse) */}
<NetworkSection
title="WebSocket 反向客户端"
description="主动连接到外部 WebSocket 服务器(reverse-ws)"
kind="wsClients"
networks={config.networks.wsClients}
onChange={(arr) => updateNetworks(config, update, 'wsClients', arr)}
renderFields={(item, patch) => (
<>
<Field
label="目标 URL"
type="url"
placeholder="ws://..."
value={item.url}
onChange={(v) => patch({ url: v })}
className="flex-1"
/>
<SelectField
label="角色"
value={item.role ?? 'universal'}
options={WS_ROLE_OPTIONS}
onChange={(v) => patch({ role: v })}
className="sm:w-32"
/>
<Field
label="重连间隔 (ms)"
type="number"
value={item.reconnectIntervalMs}
onChange={(v) => patch({ reconnectIntervalMs: Number(v) || undefined })}
className="sm:w-36"
/>
<Field
label="授权 Token"
placeholder="可选"
value={item.accessToken}
onChange={(v) => patch({ accessToken: v || undefined })}
className="sm:w-56"
/>
</>
)}
defaultEntry={(suffix) => ({
name: `wsclient-${suffix}`,
url: 'ws://127.0.0.1:8080/ws',
role: 'universal' as WsRole,
reconnectIntervalMs: 5000,
messageFormat: 'array',
reportSelfMessage: false,
})}
/>
</div>
)}
</div>
@@ -432,3 +432,296 @@ function EmptyHint({ label }: { label: string }) {
<div className="rounded-md border border-dashed py-6 text-center text-xs text-muted-foreground">{label}</div>
);
}
interface ToggleFieldProps {
label: string;
description?: string;
value: boolean;
onChange: (v: boolean) => void;
}
function ToggleField({ label, description, value, onChange }: ToggleFieldProps) {
return (
<div className="flex items-start justify-between gap-3 rounded-lg border bg-card/40 p-3">
<div className="min-w-0 flex-1">
<Label className="text-sm">{label}</Label>
{description && (
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">{description}</p>
)}
</div>
<button
type="button"
role="switch"
aria-checked={value}
aria-label={label}
onClick={() => onChange(!value)}
className={cn(
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
value
? 'border-primary bg-primary'
: 'border-input bg-muted',
)}
>
<motion.span
className="inline-block size-4 rounded-full bg-background shadow-sm"
animate={{ x: value ? 22 : 4 }}
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
/>
</button>
</div>
);
}
interface SegmentedOption<T extends string> {
value: T;
label: string;
}
function SegmentedField<T extends string>({
label,
value,
options,
onChange,
className,
}: {
label: string;
value: T;
options: ReadonlyArray<SegmentedOption<T>>;
onChange: (v: T) => void;
className?: string;
}) {
return (
<div className={cn('flex flex-col gap-1.5', className)}>
<Label>{label}</Label>
<div className="flex flex-wrap gap-1 rounded-md border bg-muted/30 p-1">
{options.map((opt) => {
const active = value === opt.value;
return (
<button
key={opt.value}
type="button"
onClick={() => onChange(opt.value)}
className={cn(
'flex-1 rounded px-2.5 py-1 text-xs transition-colors cursor-pointer',
active
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:bg-accent/50',
)}
>
{opt.label}
</button>
);
})}
</div>
</div>
);
}
function SelectField<T extends string>({
label,
value,
options,
onChange,
className,
}: {
label: string;
value: T;
options: ReadonlyArray<SegmentedOption<T>>;
onChange: (v: T) => void;
className?: string;
}) {
return (
<div className={cn('flex flex-col gap-1.5', className)}>
<Label>{label}</Label>
<select
value={value}
onChange={(e) => onChange(e.target.value as T)}
className="h-9 rounded-md border bg-background px-2 text-sm shadow-xs"
>
{options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
);
}
const ADAPTER_FORMAT_OPTIONS: ReadonlyArray<SegmentedOption<MessageFormat>> = [
{ value: 'array', label: '数组' },
{ value: 'string', label: 'CQ 码' },
];
const ADAPTER_REPORT_OPTIONS: ReadonlyArray<SegmentedOption<'on' | 'off'>> = [
{ value: 'on', label: '开启' },
{ value: 'off', label: '关闭' },
];
const WS_ROLE_OPTIONS: ReadonlyArray<SegmentedOption<WsRole>> = [
{ value: 'universal', label: 'universal' },
{ value: 'event', label: 'event' },
{ value: 'api', label: 'api' },
];
interface BaseAdapter {
name: string;
enabled?: boolean;
accessToken?: string;
messageFormat: MessageFormat;
reportSelfMessage: boolean;
}
interface NetworkSectionProps<T extends BaseAdapter> {
title: string;
description?: string;
kind: NetworkKind;
networks: T[];
onChange: (next: T[]) => void;
renderFields: (item: T, patch: (changes: Partial<T>) => void) => React.ReactNode;
defaultEntry: (suffix: number) => T;
}
function NetworkSection<T extends BaseAdapter>({
title,
description,
networks,
onChange,
renderFields,
defaultEntry,
}: NetworkSectionProps<T>) {
const handleAdd = () => {
const used = new Set(networks.map((n) => n.name));
let suffix = networks.length + 1;
let entry = defaultEntry(suffix);
while (used.has(entry.name)) {
suffix += 1;
entry = defaultEntry(suffix);
}
onChange([...networks, entry]);
};
const patchAt = (idx: number, changes: Partial<T>) => {
onChange(networks.map((it, i) => (i === idx ? { ...it, ...changes } : it)));
};
const removeAt = (idx: number) => {
onChange(networks.filter((_, i) => i !== idx));
};
return (
<Section title={title} description={description} count={networks.length} onAdd={handleAdd}>
{networks.length === 0 ? (
<EmptyHint label="暂无适配器,点击右上角『添加』新建" />
) : (
networks.map((item, idx) => (
<AdapterRow
key={`${item.name}-${idx}`}
item={item}
otherNames={networks.filter((_, i) => i !== idx).map((n) => n.name)}
onPatch={(changes) => patchAt(idx, changes)}
onRemove={() => removeAt(idx)}
renderFields={renderFields}
/>
))
)}
</Section>
);
}
interface AdapterRowProps<T extends BaseAdapter> {
item: T;
otherNames: string[];
onPatch: (changes: Partial<T>) => void;
onRemove: () => void;
renderFields: (item: T, patch: (changes: Partial<T>) => void) => React.ReactNode;
}
function AdapterRow<T extends BaseAdapter>({
item,
otherNames,
onPatch,
onRemove,
renderFields,
}: AdapterRowProps<T>) {
const enabled = item.enabled !== false;
const duplicateName = !!item.name && otherNames.includes(item.name);
const blankName = !item.name?.trim();
const formatValue: MessageFormat = item.messageFormat ?? 'array';
const reportValue: 'on' | 'off' = item.reportSelfMessage ? 'on' : 'off';
return (
<motion.div
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18 }}
className={cn(
'flex flex-col gap-3 rounded-lg border bg-card/40 p-3',
!enabled && 'opacity-60',
)}
>
<div className="flex flex-wrap items-end gap-3">
<Field
label="名称"
placeholder="自定义"
value={item.name}
onChange={(v) => onPatch({ name: v } as Partial<T>)}
className="sm:w-44"
/>
<ToggleField
label="启用"
value={enabled}
onChange={(v) => onPatch({ enabled: v ? undefined : false } as Partial<T>)}
/>
<Button
variant="ghost"
size="icon-sm"
onClick={onRemove}
aria-label="删除"
className="ml-auto self-center text-muted-foreground hover:text-destructive"
>
<Trash2 className="size-4" />
</Button>
</div>
{(blankName || duplicateName) && (
<p className="text-[11px] text-destructive">
{blankName ? '请填写名称' : '名称与其它适配器重复'}
</p>
)}
<div className="flex flex-wrap items-end gap-3">{renderFields(item, onPatch)}</div>
<div className="grid gap-3 border-t pt-3 sm:grid-cols-2">
<SegmentedField
label="消息格式"
value={formatValue}
options={ADAPTER_FORMAT_OPTIONS}
onChange={(v) => onPatch({ messageFormat: v } as Partial<T>)}
/>
<SegmentedField
label="上报自身消息"
value={reportValue}
options={ADAPTER_REPORT_OPTIONS}
onChange={(v) =>
onPatch({
reportSelfMessage: v === 'on',
} as Partial<T>)
}
/>
</div>
</motion.div>
);
}
function updateNetworks<K extends NetworkKind>(
config: OneBotConfig,
update: (next: OneBotConfig) => void,
kind: K,
next: OneBotNetworks[K],
): void {
update({
...config,
networks: { ...config.networks, [kind]: next },
});
}