refactor: use native async discovery and simplify shared state
This commit is contained in:
1 parent
5032cbb8c0
commit
4e2b6b1200
87 files changed
+2063
-2002
No files matched your search
@@ -1,10 +1,3 @@
|
||||
// Settings → 全局配置 tab. Deployment-wide SnowLuma knobs (config/snowluma.json):
|
||||
// rkey fallback servers + the music-card signing URL. Same UX as the other
|
||||
// settings panels — debounced auto-save, no explicit save button. Unlike the
|
||||
// channel editor these are typed inline, so the server's normalized result is
|
||||
// NOT written back onto the inputs while editing (that would erase a half-typed
|
||||
// URL); the store reconciles on the next load. Invalid entries are flagged
|
||||
// client-side and simply dropped by the server on save.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { AlertTriangle, KeyRound, Music, Plus, RefreshCw, Trash2 } from 'lucide-react';
|
||||
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
|
||||
@@ -33,20 +26,17 @@ export function GlobalConfigPanel() {
|
||||
const { runAction } = useActionFeedback();
|
||||
const [config, setConfig] = useState<GlobalSettings | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const { msg, flash } = useFlashMessage();
|
||||
const saveTimer = useRef<number | null>(null);
|
||||
const saveGen = useRef(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setLoadFailed(false);
|
||||
|
||||
try {
|
||||
setConfig(await api.globalConfig.get());
|
||||
} catch (error) {
|
||||
console.error('load global config failed', error);
|
||||
setLoadFailed(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -65,9 +55,7 @@ export function GlobalConfigPanel() {
|
||||
[],
|
||||
);
|
||||
|
||||
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
|
||||
* inputs from the server's normalized response (it would wipe a half-typed
|
||||
* URL); a generation guard just confirms the latest save. */
|
||||
// Keep partially typed URLs in the draft until the next load.
|
||||
const commit = (
|
||||
next: GlobalSettings,
|
||||
feedback: false | { title: string; successTitle: string } = {
|
||||
@@ -83,6 +71,7 @@ export function GlobalConfigPanel() {
|
||||
}
|
||||
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
saveTimer.current = null;
|
||||
const dropped =
|
||||
next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim())) ||
|
||||
(next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
|
||||
@@ -92,7 +81,6 @@ export function GlobalConfigPanel() {
|
||||
: runAction(
|
||||
{
|
||||
title: feedback.title,
|
||||
detail: '正在同步 config/snowluma.json',
|
||||
successTitle: feedback.successTitle,
|
||||
successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步',
|
||||
errorTitle: '全局配置更新失败',
|
||||
@@ -105,8 +93,6 @@ export function GlobalConfigPanel() {
|
||||
return;
|
||||
}
|
||||
|
||||
// The server drops invalid (non-http) entries; say so rather than a
|
||||
// bare "已保存" next to a still-visible rejected value.
|
||||
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -130,7 +116,7 @@ export function GlobalConfigPanel() {
|
||||
label="全局配置"
|
||||
className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''}
|
||||
>
|
||||
{!loading && (loadFailed || !config) ? (
|
||||
{!loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
|
||||
<AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} />
|
||||
<p className="text-sm">加载全局配置失败</p>
|
||||
@@ -162,13 +148,8 @@ export function GlobalConfigPanel() {
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<KeyRound className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
图片 / 文件下载链接需要服务器签发的{' '}
|
||||
<code className="font-mono">rkey</code>。SnowLuma 默认走内核获取;
|
||||
当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。
|
||||
<strong className="font-medium text-foreground/80">
|
||||
默认留空=关闭
|
||||
</strong>
|
||||
,不配置就不会联系任何第三方。 建议填你自建的端点。
|
||||
内核无法获取 <code className="font-mono">rkey</code>{' '}
|
||||
时,依次请求下列服务器。留空关闭,建议使用自建服务。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -186,7 +167,7 @@ export function GlobalConfigPanel() {
|
||||
|
||||
{servers.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
|
||||
未配置回退服务器(rkey 回退已关闭)
|
||||
回退服务器未启用
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
@@ -235,7 +216,7 @@ export function GlobalConfigPanel() {
|
||||
<code className="font-mono">
|
||||
{'{ group_rkey, private_rkey, expired_time }'}
|
||||
</code>
|
||||
(兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。
|
||||
,仅支持 HTTP(S)。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -268,9 +249,6 @@ export function GlobalConfigPanel() {
|
||||
)}
|
||||
onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
内置默认:<code className="font-mono">{MUSIC_SIGN_DEFAULT}</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
// Settings → 通知 tab. Mirrors the node-config UX: the first screen is
|
||||
// info-only cards (name / url / template + an inline enable toggle); creating
|
||||
// and editing always go through a dialog. All changes auto-save (debounced),
|
||||
// like the per-account config page — no explicit save button.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates';
|
||||
@@ -61,6 +57,7 @@ export function NotificationsPanel() {
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setMsg(null);
|
||||
|
||||
try {
|
||||
setConfig(await api.notifications.getConfig());
|
||||
@@ -102,6 +99,7 @@ export function NotificationsPanel() {
|
||||
}
|
||||
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
saveTimer.current = null;
|
||||
void runAction(
|
||||
{
|
||||
title: copy.title,
|
||||
@@ -123,6 +121,10 @@ export function NotificationsPanel() {
|
||||
flash('ok', '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
if (saveGen.current !== gen) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('save notifications config failed', error);
|
||||
flash('err', '保存失败,请检查服务器日志');
|
||||
});
|
||||
|
||||
@@ -1,35 +1,11 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
||||
import type { UpdateInfo } from '@/types';
|
||||
import type { AppResourceData, AppResources } from '@/lib/app-resources';
|
||||
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
|
||||
|
||||
export interface ResourceLoadState {
|
||||
ready: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface AppResourceState {
|
||||
qqList: ResourceLoadState;
|
||||
processList: ResourceLoadState;
|
||||
systemInfo: ResourceLoadState;
|
||||
connections: ResourceLoadState;
|
||||
updateInfo: ResourceLoadState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live mutable state owned by AppLayout and shared with the child route
|
||||
* components rendered inside its `<Outlet />`. Pages used to receive these
|
||||
* via prop drilling — now they pull from context so adding a new page does
|
||||
* not touch AppLayout.
|
||||
*/
|
||||
export interface AppStateValue {
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
/** Advisory update-availability info; null until the first check resolves. */
|
||||
updateInfo: UpdateInfo | null;
|
||||
export interface AppStateValue extends AppResourceData {
|
||||
/** Distinguishes an empty result from an unresolved or failed initial read. */
|
||||
resources: AppResourceState;
|
||||
resources: AppResources;
|
||||
selectedUin: string | null;
|
||||
setSelectedUin: (uin: string | null) => void;
|
||||
processOps: HookProcessOps;
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
|
||||
/**
|
||||
* Auth-level state surfaced into the router subtree. `AuthBoundary` mints
|
||||
* this and `AppLayout` consumes it — used to drive the status badge and to
|
||||
* complete logout after page-local state has been cleared.
|
||||
*/
|
||||
/** Session state shared by the authentication boundary and routed pages. */
|
||||
export interface SessionValue {
|
||||
status: string;
|
||||
/** Invoked by AppLayout's logout handler after it has scrubbed its own state. */
|
||||
/** Ends the session and unmounts its page state. */
|
||||
onLogoutComplete: () => void;
|
||||
/** Replays the first-run wizard without changing persisted account state. */
|
||||
restartOnboarding: () => void;
|
||||
|
||||
@@ -228,7 +228,6 @@ export const DEFAULT_APPEARANCE: UiAppearance = {
|
||||
export const FONT_CUSTOM_ID = 'custom';
|
||||
|
||||
const LS_CACHE = 'snowluma_ui_appearance';
|
||||
const LS_MIGRATED = 'snowluma_ui_migrated';
|
||||
const TOKEN_KEY = 'snowluma_token';
|
||||
|
||||
// ─── Colour helpers (custom hex accent → readable foreground) ──────────────
|
||||
@@ -1012,61 +1011,6 @@ async function persistAppearance(appearance: UiAppearance): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Migration of the pre-server-config localStorage theme ─────────────────
|
||||
|
||||
function readLegacyOverlay(): Partial<UiAppearance> | null {
|
||||
try {
|
||||
const out: Partial<UiAppearance> = {};
|
||||
const mode = localStorage.getItem('snowluma_theme');
|
||||
|
||||
if (mode === 'light' || mode === 'dark' || mode === 'system') {
|
||||
out.mode = mode;
|
||||
}
|
||||
|
||||
const accent = localStorage.getItem('snowluma_accent');
|
||||
|
||||
if (accent && ACCENTS.some((a) => a.id === accent)) {
|
||||
out.accentMode = 'preset';
|
||||
out.accentPreset = accent;
|
||||
}
|
||||
|
||||
const radius = Number(localStorage.getItem('snowluma_radius'));
|
||||
|
||||
if (Number.isFinite(radius) && radius > 0 && radius <= 2) {
|
||||
out.radius = radius;
|
||||
}
|
||||
|
||||
const density = localStorage.getItem('snowluma_density');
|
||||
|
||||
if (density === 'cozy' || density === 'compact') {
|
||||
out.density = density;
|
||||
}
|
||||
|
||||
const poll = Number(localStorage.getItem('snowluma_poll_interval'));
|
||||
|
||||
if (Number.isFinite(poll) && poll >= 0 && poll <= 60_000) {
|
||||
out.pollInterval = poll;
|
||||
}
|
||||
|
||||
return Object.keys(out).length > 0 ? out : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isPristine(a: UiAppearance): boolean {
|
||||
const d = DEFAULT_APPEARANCE;
|
||||
return (
|
||||
a.mode === d.mode &&
|
||||
a.accentMode === d.accentMode &&
|
||||
a.accentPreset === d.accentPreset &&
|
||||
a.radius === d.radius &&
|
||||
a.density === d.density &&
|
||||
a.pollInterval === d.pollInterval &&
|
||||
a.background.type === 'none'
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Light/dark reveal (View Transitions API) ──────────────────────────────
|
||||
// Where the user last clicked, so the theme reveal emanates from there.
|
||||
let lastPointer: { x: number; y: number } | null = null;
|
||||
@@ -1149,7 +1093,7 @@ interface ThemeContextValue {
|
||||
/** Re-fetch appearance from the server (e.g. after login, so the authed
|
||||
* `customCss` loads). */
|
||||
reloadAppearance: () => Promise<void>;
|
||||
// ── back-compat conveniences ──
|
||||
// Common appearance controls.
|
||||
mode: ThemeMode;
|
||||
setMode: (m: ThemeMode) => void;
|
||||
pollInterval: number;
|
||||
@@ -1190,7 +1134,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
return () => mq.removeEventListener('change', handler);
|
||||
}, []);
|
||||
|
||||
// Initial server load (+ one-time legacy migration). Runs once.
|
||||
// Load the server appearance, retaining the cache if it is unavailable.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
@@ -1201,34 +1145,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
return;
|
||||
}
|
||||
|
||||
let next = server ?? readCache();
|
||||
|
||||
let migrated = true;
|
||||
|
||||
try {
|
||||
migrated = Boolean(localStorage.getItem(LS_MIGRATED));
|
||||
} catch {
|
||||
/* storage unavailable: skip migration */
|
||||
}
|
||||
|
||||
if (!migrated) {
|
||||
try {
|
||||
localStorage.setItem(LS_MIGRATED, '1');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
const legacy = readLegacyOverlay();
|
||||
|
||||
// Only migrate when the server has never been customized, so we don't
|
||||
// clobber a look already set from another device.
|
||||
if (legacy && server && isPristine(server)) {
|
||||
next = { ...server, ...legacy, background: server.background };
|
||||
void persistAppearance(next).catch((error) => {
|
||||
console.error('appearance migration save failed', error);
|
||||
});
|
||||
}
|
||||
}
|
||||
const next = server ?? readCache();
|
||||
|
||||
setAppearanceState(next);
|
||||
writeCache(next);
|
||||
@@ -1256,8 +1173,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
applyBackgroundLayer(appearance);
|
||||
}, [appearance]);
|
||||
|
||||
// Flush a pending debounced save on unmount (defensive — the provider lives
|
||||
// at the app root and normally never unmounts).
|
||||
// Cancel a pending save when the provider unmounts.
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { createAppResources } from '@/lib/app-resources';
|
||||
import { startPolling } from '@/lib/polling';
|
||||
|
||||
export function useAppResources(pollInterval: number) {
|
||||
const api = useApi();
|
||||
const store = useMemo(() => createAppResources(api), [api]);
|
||||
const resources = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
||||
|
||||
useEffect(() => {
|
||||
const dispose = api.stateStream({ onEvent: store.onEvent });
|
||||
|
||||
return () => {
|
||||
dispose();
|
||||
store.invalidate();
|
||||
};
|
||||
}, [api, store]);
|
||||
|
||||
// Reconcile SSE resources periodically; system metrics keep the faster cadence.
|
||||
useEffect(
|
||||
() =>
|
||||
startPolling(
|
||||
store.reconcile,
|
||||
pollInterval > 0 ? Math.max(pollInterval * 10, 10_000) : 0,
|
||||
),
|
||||
[pollInterval, store],
|
||||
);
|
||||
useEffect(() => startPolling(store.refreshSystem, pollInterval), [pollInterval, store]);
|
||||
useEffect(() => startPolling(store.refreshUpdate, 6 * 60 * 60 * 1000, false), [store]);
|
||||
|
||||
return {
|
||||
qqList: resources.qqList.data,
|
||||
processList: resources.processList.data,
|
||||
systemInfo: resources.systemInfo.data,
|
||||
connections: resources.connections.data,
|
||||
updateInfo: resources.updateInfo.data,
|
||||
resources,
|
||||
refreshQqList: store.refreshQqList,
|
||||
refreshProcesses: store.refreshProcesses,
|
||||
refreshSystem: store.refreshSystem,
|
||||
refreshConnections: store.refreshConnections,
|
||||
refreshUpdate: store.refreshUpdate,
|
||||
};
|
||||
}
|
||||
@@ -1,237 +1,33 @@
|
||||
// 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 { useEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
import { useApi } from '@/lib/api';
|
||||
import type { PickerOption } from '@/components/ui/picker';
|
||||
import { createContactList, type ContactKind } from '@/lib/debug-contacts';
|
||||
|
||||
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 { userAvatar, groupAvatar } from '@/lib/debug-contacts';
|
||||
|
||||
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 */
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
function useContactList(kind: ContactKind, uin: string, groupId = '') {
|
||||
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.
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[api, cacheKey, uin, action],
|
||||
const store = useMemo(
|
||||
() => createContactList(api.debug.invoke, kind, uin, groupId),
|
||||
[api, kind, uin, groupId],
|
||||
);
|
||||
const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
||||
|
||||
useEffect(() => {
|
||||
if (!cacheKey || !uin) {
|
||||
setItems([]);
|
||||
return;
|
||||
}
|
||||
void store.refresh(false);
|
||||
return store.invalidate;
|
||||
}, [store]);
|
||||
|
||||
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) };
|
||||
return { ...state, refresh: () => void store.refresh() };
|
||||
}
|
||||
|
||||
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 useFriends(uin: string) {
|
||||
return useContactList('friends', uin);
|
||||
}
|
||||
|
||||
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 useGroups(uin: string) {
|
||||
return useContactList('groups', uin);
|
||||
}
|
||||
|
||||
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) };
|
||||
},
|
||||
);
|
||||
export function useGroupMembers(uin: string, groupId: string) {
|
||||
return useContactList('members', uin, groupId.trim());
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
export type FlashKind = 'ok' | 'err';
|
||||
export interface FlashMessage {
|
||||
@@ -6,45 +6,38 @@ export interface FlashMessage {
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transient status-banner state for a settings panel.
|
||||
*
|
||||
* - `flash(kind, text)` shows a message that auto-clears after `durationMs`,
|
||||
* cancelling any prior auto-clear timer first.
|
||||
* - `setMsg` sets/clears the message directly (a persistent one that stays
|
||||
* until the next action — e.g. a load-failure banner).
|
||||
* - The pending timer is cleared on unmount.
|
||||
*
|
||||
* Replaces the per-panel hand-rolled `msg` state + `msgTimer` ref + `flash` +
|
||||
* unmount cleanup, which had drifted (one panel omitted the ref, the
|
||||
* prior-timer cancel, and the unmount cleanup entirely — leaking a timer that
|
||||
* could fire a stale `setMsg` after unmount).
|
||||
*/
|
||||
/** `flash` expires automatically; `setMsg` replaces it with a persistent message. */
|
||||
export function useFlashMessage(durationMs = 2400): {
|
||||
msg: FlashMessage | null;
|
||||
flash: (kind: FlashKind, text: string) => void;
|
||||
setMsg: (msg: FlashMessage | null) => void;
|
||||
} {
|
||||
const [msg, setMsg] = useState<FlashMessage | null>(null);
|
||||
const [msg, setMessage] = useState<FlashMessage | null>(null);
|
||||
const timer = useRef<number | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) {
|
||||
clearTimeout(timer.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const flash = (kind: FlashKind, text: string) => {
|
||||
setMsg({ kind, text });
|
||||
|
||||
if (timer.current) {
|
||||
const cancelTimer = useCallback(() => {
|
||||
if (timer.current !== null) {
|
||||
clearTimeout(timer.current);
|
||||
}
|
||||
|
||||
timer.current = window.setTimeout(() => setMsg(null), durationMs);
|
||||
};
|
||||
|
||||
timer.current = null;
|
||||
}, []);
|
||||
useEffect(() => cancelTimer, [cancelTimer]);
|
||||
const setMsg = useCallback(
|
||||
(next: FlashMessage | null) => {
|
||||
cancelTimer();
|
||||
setMessage(next);
|
||||
},
|
||||
[cancelTimer],
|
||||
);
|
||||
const flash = useCallback(
|
||||
(kind: FlashKind, text: string) => {
|
||||
setMsg({ kind, text });
|
||||
timer.current = window.setTimeout(() => {
|
||||
timer.current = null;
|
||||
setMessage(null);
|
||||
}, durationMs);
|
||||
},
|
||||
[durationMs, setMsg],
|
||||
);
|
||||
return { msg, flash, setMsg };
|
||||
}
|
||||
@@ -3,12 +3,7 @@ import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
|
||||
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.
|
||||
*/
|
||||
/** Account-scoped editing, persistence, and unsaved-change confirmation. */
|
||||
export interface UseOneBotInstanceConfig {
|
||||
selectedUin: string | null;
|
||||
/** Loaded config for the current UIN. Null while loading or before a selection. */
|
||||
@@ -19,11 +14,7 @@ export interface UseOneBotInstanceConfig {
|
||||
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.
|
||||
*/
|
||||
/** Dirty edits require confirmation before switching accounts. */
|
||||
requestSwitchUin: (uin: string) => void;
|
||||
/** Non-null while a switch is parked waiting for confirmation. */
|
||||
pendingSwitchUin: string | null;
|
||||
@@ -40,6 +31,14 @@ export interface UseOneBotInstanceConfig {
|
||||
saveStatusTone: 'idle' | 'saving' | 'success' | 'warning' | 'error';
|
||||
}
|
||||
|
||||
type ConfigState =
|
||||
| { status: 'idle'; uin: null }
|
||||
| { status: 'loading'; uin: string }
|
||||
| { status: 'error'; uin: string; error: string }
|
||||
| { status: 'ready'; uin: string; config: OneBotConfig; savedSnapshot: string };
|
||||
|
||||
type SaveFeedback = { text: string; tone: UseOneBotInstanceConfig['saveStatusTone'] };
|
||||
const IDLE_FEEDBACK: SaveFeedback = { text: '', tone: 'idle' };
|
||||
const CLEAR_SAVE_STATUS_MS = 3000;
|
||||
|
||||
export interface UseOneBotInstanceConfigOptions {
|
||||
@@ -56,19 +55,11 @@ export function useOneBotInstanceConfig(
|
||||
const api = useApi();
|
||||
const { runAction } = useActionFeedback();
|
||||
const { onSelectedUinChange } = options;
|
||||
// Start the first config request in the same render that receives the account
|
||||
// list; publishing the selection upward remains an effect, but no longer adds
|
||||
// an otherwise unnecessary render before the network request can begin.
|
||||
// Load the first account without waiting for selection to propagate upward.
|
||||
const selectedUin = options.selectedUin ?? accounts[0]?.uin ?? null;
|
||||
const [config, setConfigState] = useState<OneBotConfig | null>(null);
|
||||
const [loadedUin, setLoadedUin] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [state, setState] = useState<ConfigState>({ status: 'idle', uin: null });
|
||||
const [reloadGeneration, setReloadGeneration] = useState(0);
|
||||
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
|
||||
const [saveStatus, setSaveStatus] = useState('');
|
||||
const [saveStatusTone, setSaveStatusTone] =
|
||||
useState<UseOneBotInstanceConfig['saveStatusTone']>('idle');
|
||||
const [saveFeedback, setSaveFeedback] = useState<SaveFeedback>(IDLE_FEEDBACK);
|
||||
const [pendingSwitchUin, setPendingSwitchUin] = useState<string | null>(null);
|
||||
const clearTimerRef = useRef<number | null>(null);
|
||||
const editRevisionRef = useRef(0);
|
||||
@@ -93,23 +84,15 @@ export function useOneBotInstanceConfig(
|
||||
clearTimerRef.current = null;
|
||||
}
|
||||
|
||||
setSaveStatus('');
|
||||
setSaveStatusTone('idle');
|
||||
setSaveFeedback(IDLE_FEEDBACK);
|
||||
setPendingSwitchUin(null);
|
||||
|
||||
if (!selectedUin) {
|
||||
setLoading(false);
|
||||
setLoadError(null);
|
||||
setConfigState(null);
|
||||
setLoadedUin(null);
|
||||
setSavedSnapshot(null);
|
||||
setState({ status: 'idle', uin: null });
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setLoadError(null);
|
||||
setConfigState(null);
|
||||
setLoadedUin(null);
|
||||
setSavedSnapshot(null);
|
||||
setState({ status: 'loading', uin: selectedUin });
|
||||
let cancelled = false;
|
||||
|
||||
(async () => {
|
||||
@@ -121,24 +104,28 @@ export function useOneBotInstanceConfig(
|
||||
}
|
||||
|
||||
editRevisionRef.current += 1;
|
||||
setConfigState(loaded);
|
||||
setLoadedUin(selectedUin);
|
||||
setSavedSnapshot(JSON.stringify(loaded));
|
||||
setState({
|
||||
status: 'ready',
|
||||
uin: selectedUin,
|
||||
config: loaded,
|
||||
savedSnapshot: JSON.stringify(loaded),
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('load-config', e);
|
||||
|
||||
if (!cancelled) {
|
||||
setLoadError(e instanceof Error ? e.message : '加载账号配置失败');
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setLoading(false);
|
||||
setState({
|
||||
status: 'error',
|
||||
uin: selectedUin,
|
||||
error: e instanceof Error ? e.message : '加载账号配置失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
saveGenerationRef.current += 1;
|
||||
};
|
||||
}, [selectedUin, api, reloadGeneration]);
|
||||
|
||||
@@ -151,9 +138,11 @@ export function useOneBotInstanceConfig(
|
||||
[],
|
||||
);
|
||||
|
||||
const currentConfig = loadedUin === selectedUin ? config : null;
|
||||
const currentLoading =
|
||||
selectedUin !== null && (loading || (loadError === null && currentConfig === null));
|
||||
const current = state.uin === selectedUin ? state : null;
|
||||
const currentConfig = current?.status === 'ready' ? current.config : null;
|
||||
const savedSnapshot = current?.status === 'ready' ? current.savedSnapshot : null;
|
||||
const loading = selectedUin !== null && (!current || current.status === 'loading');
|
||||
const loadError = current?.status === 'error' ? current.error : null;
|
||||
|
||||
const dirty = useMemo(() => {
|
||||
if (currentConfig == null || savedSnapshot == null) {
|
||||
@@ -163,10 +152,17 @@ export function useOneBotInstanceConfig(
|
||||
return JSON.stringify(currentConfig) !== savedSnapshot;
|
||||
}, [currentConfig, savedSnapshot]);
|
||||
|
||||
const setConfig = useCallback((next: OneBotConfig) => {
|
||||
editRevisionRef.current += 1;
|
||||
setConfigState(next);
|
||||
}, []);
|
||||
const setConfig = useCallback(
|
||||
(next: OneBotConfig) => {
|
||||
editRevisionRef.current += 1;
|
||||
setState((previous) =>
|
||||
previous.status === 'ready' && previous.uin === selectedUin
|
||||
? { ...previous, config: next }
|
||||
: previous,
|
||||
);
|
||||
},
|
||||
[selectedUin],
|
||||
);
|
||||
const reload = useCallback(() => setReloadGeneration((generation) => generation + 1), []);
|
||||
|
||||
const requestSwitchUin = useCallback(
|
||||
@@ -207,8 +203,7 @@ export function useOneBotInstanceConfig(
|
||||
return;
|
||||
}
|
||||
|
||||
setSaveStatus('');
|
||||
setSaveStatusTone('idle');
|
||||
setSaveFeedback(IDLE_FEEDBACK);
|
||||
}, CLEAR_SAVE_STATUS_MS);
|
||||
}, []);
|
||||
|
||||
@@ -223,8 +218,7 @@ export function useOneBotInstanceConfig(
|
||||
const uin = selectedUin;
|
||||
const editRevision = editRevisionRef.current;
|
||||
const generation = ++saveGenerationRef.current;
|
||||
setSaveStatus('保存中...');
|
||||
setSaveStatusTone('saving');
|
||||
setSaveFeedback({ text: '保存中…', tone: 'saving' });
|
||||
|
||||
try {
|
||||
const result = await runAction(
|
||||
@@ -259,39 +253,49 @@ export function useOneBotInstanceConfig(
|
||||
}
|
||||
|
||||
if (!result.saved) {
|
||||
setSaveStatus(`保存失败:${result.message || '服务器未确认配置已保存'}`);
|
||||
setSaveStatusTone('error');
|
||||
setSaveFeedback({
|
||||
text: `保存失败:${result.message || '服务器未确认配置已保存'}`,
|
||||
tone: 'error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setSavedSnapshot(JSON.stringify(result.config));
|
||||
const unchanged = editRevisionRef.current === editRevision;
|
||||
setState((previous) =>
|
||||
previous.status === 'ready' && previous.uin === uin
|
||||
? {
|
||||
...previous,
|
||||
config: unchanged ? result.config : previous.config,
|
||||
savedSnapshot: JSON.stringify(result.config),
|
||||
}
|
||||
: previous,
|
||||
);
|
||||
|
||||
if (editRevisionRef.current === editRevision) {
|
||||
setConfigState(result.config);
|
||||
} else {
|
||||
setSaveStatus('上一版本已保存,当前修改仍待保存');
|
||||
setSaveStatusTone('warning');
|
||||
if (!unchanged) {
|
||||
setSaveFeedback({ text: '上一版本已保存,当前修改待保存', tone: 'warning' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!result.online) {
|
||||
setSaveStatus('保存成功;当前离线,将在下次连接时应用');
|
||||
setSaveStatusTone('warning');
|
||||
setSaveFeedback({ text: '已保存,下次连接时应用', tone: 'warning' });
|
||||
} else if (result.applied) {
|
||||
setSaveStatus('保存成功,热重载完成');
|
||||
setSaveStatusTone('success');
|
||||
setSaveFeedback({ text: '已保存并应用', tone: 'success' });
|
||||
} else {
|
||||
const first = result.errors[0]?.message;
|
||||
setSaveStatus(`保存成功,但热重载失败${first ? `:${first}` : ''}`);
|
||||
setSaveStatusTone('warning');
|
||||
setSaveFeedback({
|
||||
text: `已保存,但热重载失败${first ? `:${first}` : ''}`,
|
||||
tone: 'warning',
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`);
|
||||
setSaveStatusTone('error');
|
||||
setSaveFeedback({
|
||||
text: `保存失败:${e instanceof Error ? e.message : '未知错误'}`,
|
||||
tone: 'error',
|
||||
});
|
||||
} finally {
|
||||
if (selectedUinRef.current === uin && saveGenerationRef.current === generation) {
|
||||
scheduleStatusClear(uin, generation);
|
||||
@@ -304,7 +308,7 @@ export function useOneBotInstanceConfig(
|
||||
return {
|
||||
selectedUin,
|
||||
config: currentConfig,
|
||||
loading: currentLoading,
|
||||
loading,
|
||||
loadError,
|
||||
reload,
|
||||
setConfig,
|
||||
@@ -314,7 +318,7 @@ export function useOneBotInstanceConfig(
|
||||
confirmSwitch,
|
||||
cancelSwitch,
|
||||
save,
|
||||
saveStatus,
|
||||
saveStatusTone,
|
||||
saveStatus: saveFeedback.text,
|
||||
saveStatusTone: saveFeedback.tone,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import type { ApiClient, StateStreamEvent } from '@/lib/api/types';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
||||
|
||||
export interface AppResourceData {
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
updateInfo: UpdateInfo | null;
|
||||
}
|
||||
|
||||
export type AppResources = {
|
||||
[K in keyof AppResourceData]: {
|
||||
data: AppResourceData[K];
|
||||
ready: boolean;
|
||||
error: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
type ResourceKey = keyof AppResourceData;
|
||||
|
||||
const LOAD_ERRORS: Record<ResourceKey, string> = {
|
||||
qqList: '加载账号列表失败',
|
||||
processList: '加载进程列表失败',
|
||||
systemInfo: '加载系统信息失败',
|
||||
connections: '加载连接状态失败',
|
||||
updateInfo: '检查更新失败',
|
||||
};
|
||||
|
||||
export function createAppResources(api: ApiClient) {
|
||||
let snapshot: AppResources = {
|
||||
qqList: { data: [], ready: false, error: null },
|
||||
processList: { data: [], ready: false, error: null },
|
||||
systemInfo: { data: null, ready: false, error: null },
|
||||
connections: { data: [], ready: false, error: null },
|
||||
updateInfo: { data: null, ready: false, error: null },
|
||||
};
|
||||
const revisions: Record<ResourceKey, number> = {
|
||||
qqList: 0,
|
||||
processList: 0,
|
||||
systemInfo: 0,
|
||||
connections: 0,
|
||||
updateInfo: 0,
|
||||
};
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function settle<K extends ResourceKey>(
|
||||
key: K,
|
||||
data: AppResourceData[K],
|
||||
error: string | null = null,
|
||||
) {
|
||||
snapshot = { ...snapshot, [key]: { data, ready: true, error } };
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
async function refresh<K extends ResourceKey>(
|
||||
key: K,
|
||||
load: () => Promise<AppResourceData[K]>,
|
||||
throwOnError = false,
|
||||
): Promise<AppResourceData[K] | null> {
|
||||
const revision = ++revisions[key];
|
||||
|
||||
try {
|
||||
const data = await load();
|
||||
|
||||
if (revisions[key] !== revision) {
|
||||
return null;
|
||||
}
|
||||
|
||||
settle(key, data);
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (revisions[key] !== revision) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const message =
|
||||
error instanceof Error && error.message ? error.message : LOAD_ERRORS[key];
|
||||
settle(key, snapshot[key].data, message);
|
||||
|
||||
if (throwOnError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function publish<K extends ResourceKey>(key: K, data: AppResourceData[K]) {
|
||||
// A pushed snapshot supersedes any pending REST response for this resource.
|
||||
revisions[key] += 1;
|
||||
settle(key, data);
|
||||
}
|
||||
|
||||
const refreshQqList = async () => {
|
||||
await refresh('qqList', () => api.qqList());
|
||||
};
|
||||
|
||||
const refreshProcesses = async () => {
|
||||
await refresh('processList', () => api.processes.list());
|
||||
};
|
||||
|
||||
const refreshSystem = async () => {
|
||||
await refresh('systemInfo', () => api.system());
|
||||
};
|
||||
|
||||
const refreshConnections = async () => {
|
||||
await refresh('connections', () => api.connections());
|
||||
};
|
||||
|
||||
const refreshUpdate = (force = false) =>
|
||||
refresh('updateInfo', () => api.update.check(force), force);
|
||||
|
||||
const reconcile = async () => {
|
||||
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
|
||||
};
|
||||
|
||||
return {
|
||||
getSnapshot: () => snapshot,
|
||||
subscribe: (listener: () => void) => {
|
||||
listeners.add(listener);
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
invalidate: () => {
|
||||
for (const key of Object.keys(revisions) as ResourceKey[]) {
|
||||
revisions[key] += 1;
|
||||
}
|
||||
},
|
||||
onEvent: (event: StateStreamEvent) => {
|
||||
if ('resource' in event) {
|
||||
switch (event.resource) {
|
||||
case 'qq-list':
|
||||
publish('qqList', event.data);
|
||||
break;
|
||||
case 'processes':
|
||||
publish('processList', event.data);
|
||||
break;
|
||||
case 'connections':
|
||||
publish('connections', event.data);
|
||||
break;
|
||||
}
|
||||
} else if (event.kind === 'dropped') {
|
||||
void reconcile();
|
||||
}
|
||||
},
|
||||
reconcile,
|
||||
refreshQqList,
|
||||
refreshProcesses,
|
||||
refreshSystem,
|
||||
refreshConnections,
|
||||
refreshUpdate,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import type { ApiClient } from '@/lib/api/types';
|
||||
import type { PickerOption } from '@/components/ui/picker';
|
||||
|
||||
const TTL_MS = 5 * 60_000;
|
||||
const LS_KEY = 'snowluma.debug.contacts.v1';
|
||||
|
||||
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[];
|
||||
}
|
||||
|
||||
// Rebuild avatar URLs rather than storing them for every member.
|
||||
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;
|
||||
}
|
||||
|
||||
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: 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 */
|
||||
}
|
||||
}
|
||||
|
||||
export type ContactKind = 'friends' | 'groups' | 'members';
|
||||
|
||||
export interface ContactListState {
|
||||
items: PickerOption[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const ACTIONS: Record<ContactKind, string> = {
|
||||
friends: 'get_friend_list',
|
||||
groups: 'get_group_list',
|
||||
members: 'get_group_member_list',
|
||||
};
|
||||
|
||||
function parseContact(kind: ContactKind, row: unknown): PickerOption | null {
|
||||
if (!row || typeof row !== 'object' || Array.isArray(row)) {
|
||||
throw new Error('联系人列表格式无效');
|
||||
}
|
||||
|
||||
const fields = row as Record<string, unknown>;
|
||||
const id = kind === 'groups' ? fields.group_id : fields.user_id;
|
||||
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof id !== 'string' && typeof id !== 'number') {
|
||||
throw new Error('联系人 ID 格式无效');
|
||||
}
|
||||
|
||||
const value = String(id);
|
||||
const names =
|
||||
kind === 'groups'
|
||||
? [fields.group_name]
|
||||
: kind === 'friends'
|
||||
? [fields.remark, fields.nickname]
|
||||
: [fields.card, fields.nickname];
|
||||
const label =
|
||||
names.find((name): name is string => typeof name === 'string' && name !== '') ?? value;
|
||||
return {
|
||||
value,
|
||||
label,
|
||||
sub: value,
|
||||
avatar: kind === 'groups' ? groupAvatar(value) : userAvatar(value),
|
||||
};
|
||||
}
|
||||
|
||||
export function createContactList(
|
||||
invoke: ApiClient['debug']['invoke'],
|
||||
kind: ContactKind,
|
||||
uin: string,
|
||||
groupId = '',
|
||||
) {
|
||||
hydrate();
|
||||
const key =
|
||||
uin && (kind !== 'members' || groupId)
|
||||
? `${kind}:${uin}${kind === 'members' ? `:${groupId}` : ''}`
|
||||
: null;
|
||||
const cached = key ? mem.get(key) : undefined;
|
||||
let state: ContactListState = { items: cached?.items ?? [], loading: false, error: null };
|
||||
let revision = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function publish(next: ContactListState) {
|
||||
state = next;
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
async function refresh(force = true): Promise<void> {
|
||||
const request = ++revision;
|
||||
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hit = mem.get(key);
|
||||
|
||||
if (!force && hit && Date.now() - hit.at < TTL_MS) {
|
||||
publish({ items: hit.items, loading: false, error: null });
|
||||
return;
|
||||
}
|
||||
|
||||
publish({ ...state, loading: true, error: null });
|
||||
|
||||
try {
|
||||
const result = await invoke(
|
||||
uin,
|
||||
ACTIONS[kind],
|
||||
kind === 'members' ? { group_id: groupId } : {},
|
||||
);
|
||||
|
||||
if (request !== revision) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status !== 'ok') {
|
||||
throw new Error(result.message || result.wording || '加载失败');
|
||||
}
|
||||
|
||||
if (!Array.isArray(result.data)) {
|
||||
throw new Error('联系人列表格式无效');
|
||||
}
|
||||
|
||||
const items = result.data
|
||||
.map((row) => parseContact(kind, row))
|
||||
.filter((item) => item !== null);
|
||||
mem.set(key, { at: Date.now(), items });
|
||||
persist();
|
||||
publish({ items, loading: false, error: null });
|
||||
} catch (error) {
|
||||
if (request === revision) {
|
||||
publish({
|
||||
...state,
|
||||
loading: false,
|
||||
error: error instanceof Error ? error.message : '加载失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getSnapshot: () => state,
|
||||
subscribe: (listener: () => void) => {
|
||||
listeners.add(listener);
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
refresh,
|
||||
invalidate: () => {
|
||||
revision += 1;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Run immediately, then at the requested cadence without overlapping requests. */
|
||||
export function startPolling(
|
||||
refresh: () => Promise<unknown>,
|
||||
intervalMs: number,
|
||||
pauseWhenHidden = true,
|
||||
): () => void {
|
||||
let running = false;
|
||||
|
||||
const tick = async () => {
|
||||
if (running || (pauseWhenHidden && document.hidden)) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await refresh();
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
void tick();
|
||||
const interval = intervalMs > 0 ? setInterval(tick, intervalMs) : null;
|
||||
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
void tick();
|
||||
}
|
||||
};
|
||||
|
||||
if (pauseWhenHidden) {
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (interval !== null) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
if (pauseWhenHidden) {
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -8,43 +8,12 @@ import { NAV_ITEMS } from '@/components/layout/sidebar';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { LowIntegrityWarning } from '@/components/low-integrity-warning';
|
||||
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
|
||||
import { AppStateProvider, type AppResourceState } from '@/contexts/AppStateContext';
|
||||
import { AppStateProvider } from '@/contexts/AppStateContext';
|
||||
import { useAppResources } from '@/hooks/use-app-resources';
|
||||
import { KioskProvider } from '@/contexts/KioskContext';
|
||||
import { LayoutProvider, useLayout } from '@/contexts/LayoutContext';
|
||||
import { useSession } from '@/contexts/SessionContext';
|
||||
import type { AppPath } from '@/router';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
||||
|
||||
function createInitialResources(): AppResourceState {
|
||||
return {
|
||||
qqList: { ready: false, error: null },
|
||||
processList: { ready: false, error: null },
|
||||
systemInfo: { ready: false, error: null },
|
||||
connections: { ready: false, error: null },
|
||||
updateInfo: { ready: false, error: null },
|
||||
};
|
||||
}
|
||||
|
||||
type AppResourceKey = keyof AppResourceState;
|
||||
|
||||
function createResourceCounters(): Record<AppResourceKey, number> {
|
||||
return {
|
||||
qqList: 0,
|
||||
processList: 0,
|
||||
systemInfo: 0,
|
||||
connections: 0,
|
||||
updateInfo: 0,
|
||||
};
|
||||
}
|
||||
|
||||
interface ResourceRequestTicket {
|
||||
generation: number;
|
||||
streamRevision: number;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof Error && error.message ? error.message : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects to the operator's configured landing page once (after the layout
|
||||
@@ -79,12 +48,6 @@ function DefaultRouteRedirect() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The layout route. Owns the live state shared across the four pages
|
||||
* (polling lists, processOps, selectedUin) and renders `<Outlet />` inside
|
||||
* the chrome. The unload-failed alert sits here so it survives navigation
|
||||
* away from the overview page.
|
||||
*/
|
||||
export function AppLayout() {
|
||||
const api = useApi();
|
||||
const { pollInterval, reloadAppearance } = useTheme();
|
||||
@@ -96,171 +59,9 @@ export function AppLayout() {
|
||||
void reloadAppearance();
|
||||
}, [reloadAppearance]);
|
||||
|
||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
|
||||
const [connections, setConnections] = useState<AccountConnections[]>([]);
|
||||
const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null);
|
||||
const [resources, setResources] = useState<AppResourceState>(createInitialResources);
|
||||
const data = useAppResources(pollInterval);
|
||||
const { connections, refreshProcesses, systemInfo } = data;
|
||||
const [selectedUin, setSelectedUin] = useState<string | null>(null);
|
||||
const requestGenerationRef = useRef(createResourceCounters());
|
||||
const streamRevisionRef = useRef(createResourceCounters());
|
||||
|
||||
const settleResource = useCallback((resource: AppResourceKey, error: string | null) => {
|
||||
setResources((current) => ({
|
||||
...current,
|
||||
[resource]: { ready: true, error },
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const beginResourceRequest = useCallback(
|
||||
(resource: AppResourceKey): ResourceRequestTicket => ({
|
||||
generation: ++requestGenerationRef.current[resource],
|
||||
streamRevision: streamRevisionRef.current[resource],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const isCurrentResourceRequest = useCallback(
|
||||
(resource: AppResourceKey, ticket: ResourceRequestTicket): boolean =>
|
||||
requestGenerationRef.current[resource] === ticket.generation &&
|
||||
streamRevisionRef.current[resource] === ticket.streamRevision,
|
||||
[],
|
||||
);
|
||||
|
||||
const settleStreamResource = useCallback(
|
||||
(resource: AppResourceKey) => {
|
||||
streamRevisionRef.current[resource] += 1;
|
||||
settleResource(resource, null);
|
||||
},
|
||||
[settleResource],
|
||||
);
|
||||
|
||||
const refreshQqList = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('qqList');
|
||||
|
||||
try {
|
||||
const next = await api.qqList();
|
||||
|
||||
if (!isCurrentResourceRequest('qqList', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setQqList(next);
|
||||
settleResource('qqList', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('qqList', ticket)) {
|
||||
console.warn('ignored stale qq-list request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('qq-list', e);
|
||||
settleResource('qqList', errorMessage(e, '加载账号列表失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshProcesses = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('processList');
|
||||
|
||||
try {
|
||||
const next = await api.processes.list();
|
||||
|
||||
if (!isCurrentResourceRequest('processList', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setProcessList(next);
|
||||
settleResource('processList', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('processList', ticket)) {
|
||||
console.warn('ignored stale process-list request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('processes', e);
|
||||
settleResource('processList', errorMessage(e, '加载进程列表失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshSystem = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('systemInfo');
|
||||
|
||||
try {
|
||||
const next = await api.system();
|
||||
|
||||
if (!isCurrentResourceRequest('systemInfo', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSystemInfo(next);
|
||||
settleResource('systemInfo', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('systemInfo', ticket)) {
|
||||
console.warn('ignored stale system-info request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('system', e);
|
||||
settleResource('systemInfo', errorMessage(e, '加载系统信息失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshConnections = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('connections');
|
||||
|
||||
try {
|
||||
const next = await api.connections();
|
||||
|
||||
if (!isCurrentResourceRequest('connections', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setConnections(next);
|
||||
settleResource('connections', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('connections', ticket)) {
|
||||
console.warn('ignored stale connections request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('connections', e);
|
||||
settleResource('connections', errorMessage(e, '加载连接状态失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshUpdate = useCallback(
|
||||
async (force = false) => {
|
||||
const ticket = beginResourceRequest('updateInfo');
|
||||
|
||||
try {
|
||||
const next = await api.update.check(force);
|
||||
|
||||
if (!isCurrentResourceRequest('updateInfo', ticket)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
setUpdateInfo(next);
|
||||
settleResource('updateInfo', null);
|
||||
return next;
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('updateInfo', ticket)) {
|
||||
console.warn('ignored stale update-check request failure', e);
|
||||
return null;
|
||||
}
|
||||
|
||||
console.error('update-check', e);
|
||||
settleResource('updateInfo', errorMessage(e, '检查更新失败'));
|
||||
|
||||
if (force) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[api, beginResourceRequest, isCurrentResourceRequest, settleResource],
|
||||
);
|
||||
|
||||
const {
|
||||
ops: processOps,
|
||||
unloadFailedAlert,
|
||||
@@ -269,182 +70,8 @@ export function AppLayout() {
|
||||
onAfterOp: refreshProcesses,
|
||||
});
|
||||
|
||||
// Primary live-state path: subscribe to /api/state/stream and apply
|
||||
// pushed snapshots directly. Initial frames on connect prime
|
||||
// processes/qqList/connections without a polling tick.
|
||||
//
|
||||
// On `{kind:'dropped'}` (backpressure made the server skip some frames),
|
||||
// a per-resource SSE auto-recovery is NOT guaranteed: the next delivered
|
||||
// frame is whatever resource next changes, not necessarily the one whose
|
||||
// update we lost. So on dropped, kick a one-shot REST reconcile to
|
||||
// recover immediately instead of waiting up to 30s for the fallback.
|
||||
useEffect(() => {
|
||||
const dispose = api.stateStream({
|
||||
onEvent: (event) => {
|
||||
if ('resource' in event) {
|
||||
if (event.resource === 'processes') {
|
||||
setProcessList(event.data);
|
||||
settleStreamResource('processList');
|
||||
} else if (event.resource === 'qq-list') {
|
||||
setQqList(event.data);
|
||||
settleStreamResource('qqList');
|
||||
} else if (event.resource === 'connections') {
|
||||
setConnections(event.data);
|
||||
settleStreamResource('connections');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ('kind' in event && event.kind === 'dropped') {
|
||||
// Fire-and-forget; each refresh has its own try/catch.
|
||||
void refreshQqList();
|
||||
void refreshProcesses();
|
||||
void refreshConnections();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return () => {
|
||||
dispose();
|
||||
};
|
||||
}, [api, refreshQqList, refreshProcesses, refreshConnections, settleStreamResource]);
|
||||
|
||||
// Slow reconcile fallback for the SSE-covered resources. SSE drops can
|
||||
// be silent (proxy rewrites text/event-stream, tab thrashing). One REST
|
||||
// tick per (pollInterval × 10, min 10s) recovers from those without
|
||||
// hammering the server.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let running = false;
|
||||
const reconcileMs = Math.max(pollInterval * 10, 10_000);
|
||||
|
||||
const tick = async () => {
|
||||
// Skip while the tab is hidden — SSE already carries live updates, and a
|
||||
// backgrounded tab has no UI to refresh. Re-tick on becoming visible.
|
||||
// `running` drops a tick while the previous refresh is still in flight,
|
||||
// so a slow backend can't stack overlapping requests.
|
||||
if (cancelled || document.hidden || running) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Initial tick primes the lists before the SSE handshake completes
|
||||
// (avoids a flash of empty state in the chrome).
|
||||
tick();
|
||||
const interval = pollInterval > 0 ? setInterval(tick, reconcileMs) : null;
|
||||
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
void tick();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
|
||||
if (interval !== null) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [pollInterval, refreshQqList, refreshProcesses, refreshConnections]);
|
||||
|
||||
// systemInfo has its OWN fast cadence — it carries live values (uptime,
|
||||
// cpu loadAvg, memory.usagePercent, runtime.heapUsed) that the overview
|
||||
// widget visibly animates. It isn't on the SSE feed, so a 30s reconcile
|
||||
// would visibly lag the dashboard. Keep the user's configured
|
||||
// pollInterval (default 3s) here.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let running = false;
|
||||
|
||||
const tick = async () => {
|
||||
if (cancelled || document.hidden || running) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await refreshSystem();
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
const interval = pollInterval > 0 ? setInterval(tick, pollInterval) : null;
|
||||
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
void tick();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
|
||||
if (interval !== null) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [pollInterval, refreshSystem]);
|
||||
|
||||
// Update check runs on its own slow cadence (6h), independent of the fast
|
||||
// list-polling above — GitHub's API is rate-limited, the result rarely
|
||||
// changes, and the server caches it anyway, so this is cheap.
|
||||
useEffect(() => {
|
||||
let running = false;
|
||||
|
||||
const tick = async () => {
|
||||
if (running) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await refreshUpdate();
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
const id = setInterval(tick, 6 * 60 * 60 * 1000);
|
||||
return () => clearInterval(id);
|
||||
}, [refreshUpdate]);
|
||||
|
||||
const handleLogout = useCallback(async () => {
|
||||
for (const resource of Object.keys(requestGenerationRef.current) as AppResourceKey[]) {
|
||||
requestGenerationRef.current[resource] += 1;
|
||||
streamRevisionRef.current[resource] += 1;
|
||||
}
|
||||
|
||||
await api.logout();
|
||||
setQqList([]);
|
||||
setProcessList([]);
|
||||
setSystemInfo(null);
|
||||
setConnections([]);
|
||||
setUpdateInfo(null);
|
||||
setResources(createInitialResources());
|
||||
setSelectedUin(null);
|
||||
session.onLogoutComplete();
|
||||
}, [api, session]);
|
||||
|
||||
@@ -486,7 +113,7 @@ export function AppLayout() {
|
||||
className="border-b border-warning/25 bg-warning/10 px-4 py-2.5 text-sm text-warning-foreground sm:px-6 lg:px-8"
|
||||
>
|
||||
<span className="font-medium">账号数据库状态:</span>
|
||||
{parts.join(';')}。请查看概览详情。
|
||||
{parts.join(';')}
|
||||
</div>
|
||||
);
|
||||
}, [connections]);
|
||||
@@ -494,20 +121,10 @@ export function AppLayout() {
|
||||
return (
|
||||
<AppStateProvider
|
||||
value={{
|
||||
qqList,
|
||||
processList,
|
||||
systemInfo,
|
||||
connections,
|
||||
updateInfo,
|
||||
resources,
|
||||
...data,
|
||||
selectedUin,
|
||||
setSelectedUin,
|
||||
processOps,
|
||||
refreshQqList,
|
||||
refreshProcesses,
|
||||
refreshSystem,
|
||||
refreshConnections,
|
||||
refreshUpdate,
|
||||
onLogout: handleLogout,
|
||||
}}
|
||||
>
|
||||
@@ -541,7 +158,7 @@ export function AppLayout() {
|
||||
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
|
||||
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
|
||||
如需彻底卸载,请重启 QQ。
|
||||
</p>
|
||||
</>
|
||||
) : null
|
||||
|
||||
Reference in new issue
Block a user