| void;
- onConfigChange: (config: OneBotConfig) => void;
}
function qqAvatarUrl(uin: string) {
@@ -98,18 +93,25 @@ function Section({ title, description, onAdd, children, count }: SectionProps) {
);
}
-export function ConfigPage({
- qqList,
- selectedUin,
- config,
- saveStatus,
- onSelectAccount,
- onSave,
- onConfigChange,
-}: ConfigPageProps) {
+export function ConfigPage({ qqList }: ConfigPageProps) {
+ const {
+ selectedUin,
+ config,
+ setConfig,
+ dirty,
+ requestSwitchUin,
+ pendingSwitchUin,
+ confirmSwitch,
+ cancelSwitch,
+ save,
+ saveStatus,
+ } = useOneBotInstanceConfig(qqList);
const [confirmSave, setConfirmSave] = useState(false);
- const update = (next: OneBotConfig) => onConfigChange(next);
+ const update = (next: OneBotConfig) => setConfig(next);
+ const pendingSwitchAccount = pendingSwitchUin
+ ? qqList.find((q) => q.uin === pendingSwitchUin) ?? null
+ : null;
return (
@@ -132,7 +134,7 @@ export function ConfigPage({
type="button"
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
- onClick={() => onSelectAccount(q.uin)}
+ onClick={() => requestSwitchUin(q.uin)}
className={cn(
'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer',
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40'
@@ -193,7 +195,12 @@ export function ConfigPage({
{saveStatus}
)}
-
@@ -421,7 +428,27 @@ export function ConfigPage({
title="保存配置变更?"
description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`}
confirmText="保存"
- onConfirm={onSave}
+ onConfirm={save}
+ />
+
+ !open && cancelSwitch()}
+ title="放弃未保存的修改?"
+ description={
+ <>
+
+ 当前会话 {selectedUin} 还有未保存的修改。
+
+
+ 切换到 {pendingSwitchAccount?.uin ?? pendingSwitchUin}
+ {pendingSwitchAccount?.nickname ? `(${pendingSwitchAccount.nickname})` : ''} 会丢弃这些修改。
+
+ >
+ }
+ confirmText="放弃并切换"
+ destructive
+ onConfirm={confirmSwitch}
/>
);
diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx
index bc0f07f3..36fd5669 100644
--- a/packages/webui/src/components/pages/logs-page.tsx
+++ b/packages/webui/src/components/pages/logs-page.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { motion } from 'motion/react';
import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -9,10 +9,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry } from '@/types';
-
-interface LogsPageProps {
- fetchApi: (url: string, options?: RequestInit) => Promise;
-}
+import { useApi } from '@/lib/api';
const levelClass: Record = {
debug: 'text-muted-foreground',
@@ -24,7 +21,8 @@ const levelClass: Record = {
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
-export function LogsPage({ fetchApi }: LogsPageProps) {
+export function LogsPage() {
+ const api = useApi();
const [logs, setLogs] = useState([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const [paused, setPaused] = useState(false);
@@ -34,36 +32,30 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
const endRef = useRef(null);
const viewportRef = useRef(null);
- const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
-
- async function loadLogs() {
- const res = await fetchApi('/api/logs?limit=500');
- if (!res.ok) return;
- const data = await res.json();
- setLogs(data.list || []);
- }
+ const loadLogs = useCallback(async () => {
+ try {
+ setLogs(await api.logs.list(500));
+ } catch (e) {
+ console.error('logs', e);
+ }
+ }, [api]);
useEffect(() => {
- loadLogs().catch(console.error);
- }, []);
+ void loadLogs();
+ }, [loadLogs]);
useEffect(() => {
- if (!token) return;
- const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
- const source = new EventSource(url);
- source.onopen = () => setStreamStatus('实时');
- source.onerror = () => setStreamStatus('重连中');
- source.onmessage = (event) => {
- try {
- const entry = JSON.parse(event.data) as LogEntry | { type: string };
- if ('type' in entry) return;
+ return api.logs.stream({
+ onLine: (entry) => {
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000));
- } catch {
- // ignore
- }
- };
- return () => source.close();
- }, [token]);
+ },
+ onStatus: (s) => {
+ if (s === 'open') setStreamStatus('实时');
+ else if (s === 'reconnecting') setStreamStatus('重连中');
+ else setStreamStatus('已断开');
+ },
+ });
+ }, [api]);
useEffect(() => {
if (paused) return;
@@ -115,7 +107,7 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
{paused ? : }
{paused ? '继续' : '暂停'}
- loadLogs().catch(console.error)}>
+ void loadLogs()}>
刷新
Promise;
/** Called after successful logout (e.g. all-sessions invalidated). */
onLogout: () => void;
}
@@ -37,7 +34,8 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
];
-export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
+export function SettingsPage({ onLogout }: SettingsPageProps) {
+ const api = useApi();
const {
mode, setMode,
accent, setAccent,
@@ -49,30 +47,12 @@ export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
const [showChangePwd, setShowChangePwd] = useState(false);
const [pwdSavedAt, setPwdSavedAt] = useState(null);
- const checkStrength = async (password: string) => {
- const res = await fetchApi('/api/auth/check-strength', {
- method: 'POST',
- body: JSON.stringify({ password }),
- });
- const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
- return { rules: data.rules ?? [], valid: !!data.valid };
- };
-
- const submitPwd = async (oldPassword: string, newPassword: string) => {
- const res = await fetchApi('/api/auth/change-password', {
- method: 'POST',
- body: JSON.stringify({ oldPassword, newPassword }),
- });
- const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
- return { success: !!data.success, message: data.message };
- };
-
if (showChangePwd) {
return (
api.checkPasswordStrength(p)}
+ submit={(o, n) => api.changePassword(o, n)}
onSuccess={() => {
setShowChangePwd(false);
setPwdSavedAt(Date.now());
diff --git a/packages/webui/src/hooks/use-onebot-instance-config.ts b/packages/webui/src/hooks/use-onebot-instance-config.ts
new file mode 100644
index 00000000..99b44668
--- /dev/null
+++ b/packages/webui/src/hooks/use-onebot-instance-config.ts
@@ -0,0 +1,137 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import type { OneBotConfig, QQInfo } from '@/types';
+import { useApi } from '@/lib/api';
+
+/**
+ * Per-UIN OneBotInstance configuration editor. Owns the full lifecycle:
+ * selection, load, in-memory edit (with dirty tracking), save (with refetch),
+ * and a "switch UIN while dirty" guard that surfaces a pending switch the
+ * view can confirm or cancel.
+ */
+export interface UseOneBotInstanceConfig {
+ selectedUin: string | null;
+ /** Loaded config for the current UIN. Null while loading or before a selection. */
+ config: OneBotConfig | null;
+ setConfig: (next: OneBotConfig) => void;
+ /** True if the in-memory config diverges from the last server-confirmed snapshot. */
+ dirty: boolean;
+ /**
+ * Request a UIN switch. If currently dirty, the switch is parked as
+ * `pendingSwitchUin` and must be confirmed or cancelled. Otherwise it
+ * applies immediately.
+ */
+ requestSwitchUin: (uin: string) => void;
+ /** Non-null while a switch is parked waiting for confirmation. */
+ pendingSwitchUin: string | null;
+ confirmSwitch: () => void;
+ cancelSwitch: () => void;
+ save: () => Promise;
+ saveStatus: string;
+}
+
+const CLEAR_SAVE_STATUS_MS = 3000;
+
+export function useOneBotInstanceConfig(accounts: QQInfo[]): UseOneBotInstanceConfig {
+ const api = useApi();
+ const [selectedUin, setSelectedUin] = useState(null);
+ const [config, setConfigState] = useState(null);
+ const [savedSnapshot, setSavedSnapshot] = useState(null);
+ const [saveStatus, setSaveStatus] = useState('');
+ const [pendingSwitchUin, setPendingSwitchUin] = useState(null);
+ const clearTimerRef = useRef(null);
+
+ // Auto-select first account when none is selected yet.
+ useEffect(() => {
+ if (!selectedUin && accounts.length > 0) setSelectedUin(accounts[0].uin);
+ }, [accounts, selectedUin]);
+
+ // Load on UIN change. The api client already runs normalizeOneBotConfig.
+ useEffect(() => {
+ if (!selectedUin) {
+ setConfigState(null);
+ setSavedSnapshot(null);
+ return;
+ }
+ let cancelled = false;
+ (async () => {
+ try {
+ const loaded = await api.config.get(selectedUin);
+ if (cancelled) return;
+ setConfigState(loaded);
+ setSavedSnapshot(JSON.stringify(loaded));
+ } catch (e) {
+ console.error('load-config', e);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [selectedUin, api]);
+
+ useEffect(
+ () => () => {
+ if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current);
+ },
+ [],
+ );
+
+ const dirty = useMemo(() => {
+ if (config == null || savedSnapshot == null) return false;
+ return JSON.stringify(config) !== savedSnapshot;
+ }, [config, savedSnapshot]);
+
+ const setConfig = useCallback((next: OneBotConfig) => setConfigState(next), []);
+
+ const requestSwitchUin = useCallback(
+ (uin: string) => {
+ if (uin === selectedUin) return;
+ if (dirty) setPendingSwitchUin(uin);
+ else setSelectedUin(uin);
+ },
+ [dirty, selectedUin],
+ );
+
+ const confirmSwitch = useCallback(() => {
+ if (pendingSwitchUin == null) return;
+ setSelectedUin(pendingSwitchUin);
+ setPendingSwitchUin(null);
+ }, [pendingSwitchUin]);
+
+ const cancelSwitch = useCallback(() => setPendingSwitchUin(null), []);
+
+ const scheduleStatusClear = useCallback(() => {
+ if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current);
+ clearTimerRef.current = window.setTimeout(() => {
+ setSaveStatus('');
+ clearTimerRef.current = null;
+ }, CLEAR_SAVE_STATUS_MS);
+ }, []);
+
+ const save = useCallback(async () => {
+ if (!selectedUin || !config) return;
+ setSaveStatus('保存中...');
+ try {
+ const serverView = await api.config.save(selectedUin, config);
+ setConfigState(serverView);
+ setSavedSnapshot(JSON.stringify(serverView));
+ setSaveStatus('保存成功');
+ } catch (e) {
+ setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`);
+ } finally {
+ scheduleStatusClear();
+ }
+ }, [api, selectedUin, config, scheduleStatusClear]);
+
+ return {
+ selectedUin,
+ config,
+ setConfig,
+ dirty,
+ requestSwitchUin,
+ pendingSwitchUin,
+ confirmSwitch,
+ cancelSwitch,
+ save,
+ saveStatus,
+ };
+}
diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts
new file mode 100644
index 00000000..156197d2
--- /dev/null
+++ b/packages/webui/src/lib/api/client.ts
@@ -0,0 +1,251 @@
+import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
+import type { PasswordRule } from '@/components/pages/change-password-page';
+import { normalizeOneBotConfig } from '@/lib/onebot-config';
+import {
+ ApiError,
+ type ApiClient,
+ type ChangePasswordResult,
+ type CreateApiClientOptions,
+ type LoginResult,
+ type LogsStreamOptions,
+ type ProcessActionResult,
+ type TokenStore,
+} from './types';
+import { localStorageTokenStore } from './token-store';
+
+const DEFAULT_TOKEN_KEY = 'snowluma_token';
+
+interface ErrorPayload {
+ message?: string;
+ error?: string;
+ code?: string;
+}
+
+async function readJson(res: Response): Promise {
+ try {
+ return (await res.json()) as T;
+ } catch {
+ return {} as T;
+ }
+}
+
+function extractErrorMessage(payload: ErrorPayload, fallback: string): string {
+ return payload.message || payload.error || fallback;
+}
+
+class HttpApiClient implements ApiClient {
+ private tokenStore: TokenStore;
+ private currentToken: string | null;
+ private onUnauthorized?: () => void;
+
+ // namespaced surfaces are bound up-front so callers can destructure
+ readonly processes: ApiClient['processes'];
+ readonly config: ApiClient['config'];
+ readonly logs: ApiClient['logs'];
+
+ constructor(opts: CreateApiClientOptions = {}) {
+ this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
+ this.currentToken = this.tokenStore.load();
+ this.onUnauthorized = opts.onUnauthorized;
+
+ this.processes = {
+ list: () => this.getJson<{ list: HookProcessInfo[] }>('/api/processes').then((d) => d.list ?? []),
+ load: (pid) => this.postJson(`/api/processes/${pid}/load`),
+ unload: (pid) => this.postJson(`/api/processes/${pid}/unload`),
+ refresh: (pid) => this.postJson(`/api/processes/${pid}/refresh`),
+ };
+
+ this.config = {
+ get: async (uin) => {
+ const url = `/api/config/${encodeURIComponent(uin)}`;
+ const data = await this.getJson<{ config?: unknown } | unknown>(url);
+ const raw =
+ typeof data === 'object' && data != null && 'config' in (data as Record)
+ ? (data as { config: unknown }).config
+ : data;
+ return normalizeOneBotConfig(raw);
+ },
+ save: async (uin, config) => {
+ const url = `/api/config/${encodeURIComponent(uin)}`;
+ const data = await this.fetchJson<{ config?: unknown } | unknown>(url, {
+ method: 'POST',
+ body: JSON.stringify(config),
+ });
+ const raw =
+ typeof data === 'object' && data != null && 'config' in (data as Record)
+ ? (data as { config: unknown }).config
+ : data;
+ return normalizeOneBotConfig(raw);
+ },
+ };
+
+ this.logs = {
+ list: async (limit = 500) => {
+ const data = await this.getJson<{ list: LogEntry[] }>(`/api/logs?limit=${limit}`);
+ return data.list ?? [];
+ },
+ stream: (options) => this.openLogStream(options),
+ };
+ }
+
+ // ---------- HTTP helpers ----------
+
+ async request(url: string, init: RequestInit = {}): Promise {
+ const headers: Record = {
+ ...((init.headers as Record | undefined) ?? {}),
+ };
+ if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
+ if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
+ const res = await fetch(url, { ...init, headers });
+ if (res.status === 401) {
+ this.setToken(null);
+ this.onUnauthorized?.();
+ }
+ return res;
+ }
+
+ /** Like request(), but throws ApiError on non-2xx and parses JSON. */
+ private async fetchJson(url: string, init: RequestInit = {}): Promise {
+ const res = await this.request(url, init);
+ if (!res.ok) {
+ const payload = await readJson(res);
+ throw new ApiError(res.status, extractErrorMessage(payload, res.statusText || '请求失败'), payload.code);
+ }
+ return readJson(res);
+ }
+
+ private getJson(url: string): Promise {
+ return this.fetchJson(url);
+ }
+
+ private postJson(url: string, body?: unknown): Promise {
+ return this.fetchJson(url, {
+ method: 'POST',
+ body: body == null ? undefined : JSON.stringify(body),
+ });
+ }
+
+ // ---------- token management ----------
+
+ private setToken(token: string | null): void {
+ this.currentToken = token;
+ this.tokenStore.save(token);
+ }
+
+ // ---------- auth ----------
+
+ async login(password: string): Promise {
+ // Login deliberately bypasses fetchJson/onUnauthorized so a bad password
+ // doesn't trigger a global sign-out side effect.
+ try {
+ const res = await fetch('/api/login', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ password }),
+ });
+ if (!res.ok) {
+ const payload = await readJson(res);
+ return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
+ }
+ const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res);
+ this.setToken(payload.token);
+ return { ok: true, mustChangePassword: !!payload.mustChangePassword };
+ } catch (e) {
+ return { ok: false, message: e instanceof Error ? e.message : '网络错误' };
+ }
+ }
+
+ async logout(): Promise {
+ try {
+ await this.request('/api/logout', { method: 'POST' });
+ } catch {
+ /* ignore */
+ }
+ this.setToken(null);
+ }
+
+ async status(): Promise {
+ if (!this.currentToken) return false;
+ try {
+ const res = await this.request('/api/status');
+ return res.ok;
+ } catch {
+ return false;
+ }
+ }
+
+ async mustChangePassword(): Promise {
+ try {
+ const data = await this.getJson<{ mustChangePassword?: boolean }>('/api/auth/state');
+ return !!data.mustChangePassword;
+ } catch {
+ return false;
+ }
+ }
+
+ async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
+ try {
+ const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
+ '/api/auth/check-strength',
+ { password },
+ );
+ return { rules: data.rules ?? [], valid: !!data.valid };
+ } catch {
+ return { rules: [], valid: false };
+ }
+ }
+
+ async changePassword(oldPassword: string, newPassword: string): Promise {
+ try {
+ const data = await this.postJson<{ success?: boolean; message?: string }>(
+ '/api/auth/change-password',
+ { oldPassword, newPassword },
+ );
+ return { success: !!data.success, message: data.message };
+ } catch (e) {
+ if (e instanceof ApiError) return { success: false, message: e.message };
+ return { success: false, message: e instanceof Error ? e.message : '网络错误' };
+ }
+ }
+
+ // ---------- top-level resources ----------
+
+ async qqList(): Promise {
+ const data = await this.getJson<{ list: QQInfo[] }>('/api/qq-list');
+ return data.list ?? [];
+ }
+
+ system(): Promise {
+ return this.getJson('/api/system');
+ }
+
+ // ---------- SSE ----------
+
+ private openLogStream(options: LogsStreamOptions): () => void {
+ if (!this.currentToken) {
+ options.onStatus?.('closed');
+ return () => {};
+ }
+ const url = `/api/logs/stream?token=${encodeURIComponent(this.currentToken)}`;
+ const source = new EventSource(url);
+ source.onopen = () => options.onStatus?.('open');
+ source.onerror = () => options.onStatus?.('reconnecting');
+ source.onmessage = (event) => {
+ try {
+ const parsed = JSON.parse(event.data) as LogEntry | { type: string };
+ if ('type' in parsed) return; // control frame, not a log line
+ options.onLine(parsed);
+ } catch {
+ /* malformed frame, skip */
+ }
+ };
+ return () => {
+ source.close();
+ options.onStatus?.('closed');
+ };
+ }
+}
+
+export function createApiClient(options: CreateApiClientOptions = {}): ApiClient {
+ return new HttpApiClient(options);
+}
diff --git a/packages/webui/src/lib/api/context.tsx b/packages/webui/src/lib/api/context.tsx
new file mode 100644
index 00000000..fdeb57ef
--- /dev/null
+++ b/packages/webui/src/lib/api/context.tsx
@@ -0,0 +1,14 @@
+import { createContext, useContext, type ReactNode } from 'react';
+import type { ApiClient } from './types';
+
+const ApiContext = createContext(null);
+
+export function ApiProvider({ client, children }: { client: ApiClient; children: ReactNode }) {
+ return {children};
+}
+
+export function useApi(): ApiClient {
+ const client = useContext(ApiContext);
+ if (!client) throw new Error('useApi must be used inside ');
+ return client;
+}
diff --git a/packages/webui/src/lib/api/index.ts b/packages/webui/src/lib/api/index.ts
new file mode 100644
index 00000000..c9439a85
--- /dev/null
+++ b/packages/webui/src/lib/api/index.ts
@@ -0,0 +1,13 @@
+export { createApiClient } from './client';
+export { ApiProvider, useApi } from './context';
+export { ApiError } from './types';
+export type {
+ ApiClient,
+ ChangePasswordResult,
+ CreateApiClientOptions,
+ LoginResult,
+ LogsStreamOptions,
+ ProcessActionResult,
+ StreamStatus,
+ TokenStore,
+} from './types';
diff --git a/packages/webui/src/lib/api/token-store.ts b/packages/webui/src/lib/api/token-store.ts
new file mode 100644
index 00000000..c0233c0d
--- /dev/null
+++ b/packages/webui/src/lib/api/token-store.ts
@@ -0,0 +1,11 @@
+import type { TokenStore } from './types';
+
+export function localStorageTokenStore(key: string): TokenStore {
+ return {
+ load: () => localStorage.getItem(key),
+ save: (token) => {
+ if (token == null) localStorage.removeItem(key);
+ else localStorage.setItem(key, token);
+ },
+ };
+}
diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts
new file mode 100644
index 00000000..25b46934
--- /dev/null
+++ b/packages/webui/src/lib/api/types.ts
@@ -0,0 +1,88 @@
+import type {
+ HookProcessInfo,
+ LogEntry,
+ OneBotConfig,
+ QQInfo,
+ SystemInfo,
+} from '@/types';
+import type { PasswordRule } from '@/components/pages/change-password-page';
+
+export class ApiError extends Error {
+ status: number;
+ code: string | undefined;
+ constructor(status: number, message: string, code?: string) {
+ super(message);
+ this.name = 'ApiError';
+ this.status = status;
+ this.code = code;
+ }
+}
+
+export type LoginResult =
+ | { ok: true; mustChangePassword: boolean }
+ | { ok: false; message: string };
+
+export type ChangePasswordResult = { success: boolean; message?: string };
+
+export type ProcessActionResult = {
+ process?: HookProcessInfo & { error?: string };
+};
+
+export type StreamStatus = 'open' | 'reconnecting' | 'closed';
+
+export interface LogsStreamOptions {
+ onLine: (line: LogEntry) => void;
+ onStatus?: (status: StreamStatus) => void;
+}
+
+export interface ApiClient {
+ // ---- auth ----
+ login(password: string): Promise;
+ logout(): Promise;
+ /** True if the current token is still valid. */
+ status(): Promise;
+ /** Whether the current session must rotate its password before doing anything else. */
+ mustChangePassword(): Promise;
+ checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
+ changePassword(oldPassword: string, newPassword: string): Promise;
+
+ // ---- system ----
+ qqList(): Promise;
+ system(): Promise;
+
+ // ---- hook processes ----
+ processes: {
+ list(): Promise;
+ load(pid: number): Promise;
+ unload(pid: number): Promise;
+ refresh(pid: number): Promise;
+ };
+
+ // ---- OneBotInstance per-UIN config ----
+ config: {
+ get(uin: string): Promise;
+ save(uin: string, config: OneBotConfig): Promise;
+ };
+
+ // ---- logs ----
+ logs: {
+ list(limit?: number): Promise;
+ /** Subscribe to the SSE log stream. Returns a disposer. */
+ stream(options: LogsStreamOptions): () => void;
+ };
+
+ /** Escape hatch for endpoints not yet wrapped above. */
+ request(url: string, init?: RequestInit): Promise;
+}
+
+export interface TokenStore {
+ load(): string | null;
+ save(token: string | null): void;
+}
+
+export interface CreateApiClientOptions {
+ /** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
+ tokenStore?: TokenStore;
+ /** Fires whenever a request returns 401, after the token has been cleared. */
+ onUnauthorized?: () => void;
+}
diff --git a/packages/webui/src/lib/onebot-config.ts b/packages/webui/src/lib/onebot-config.ts
new file mode 100644
index 00000000..91db11fb
--- /dev/null
+++ b/packages/webui/src/lib/onebot-config.ts
@@ -0,0 +1,34 @@
+import type { MessageFormat, OneBotConfig } from '@/types';
+
+/**
+ * Anti-corruption layer for the per-UIN config payload. Older backends emit
+ * `messageFormat` / `reportSelfMessage` at the top level instead of per
+ * adapter, and may omit them on adapters entirely. This collapses both shapes
+ * into the canonical {@link OneBotConfig} the editor expects.
+ */
+export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
+ const cfg = (raw ?? {}) as Record;
+ const nets = (cfg.networks as Record | undefined) ?? {};
+ const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array';
+ const legacyReport = !!cfg.reportSelfMessage;
+
+ const normalize = (item: Record): Record => ({
+ ...item,
+ messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
+ reportSelfMessage:
+ typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
+ });
+
+ const list = (x: unknown): Record[] =>
+ Array.isArray(x) ? x.map((it) => normalize(it as Record)) : [];
+
+ return {
+ networks: {
+ httpServers: list(nets.httpServers) as unknown as OneBotConfig['networks']['httpServers'],
+ httpClients: list(nets.httpClients) as unknown as OneBotConfig['networks']['httpClients'],
+ wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'],
+ wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
+ },
+ musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined,
+ };
+}