From 04cbb8cbf3110f1e10a89115b2868710842311d9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 29 Jul 2026 02:15:30 +0800 Subject: [PATCH] fix(webui): recover stalled requests --- .../src/components/process-probe-dialog.tsx | 25 +++++- packages/webui/src/lib/api/client.ts | 36 +++++++- packages/webui/src/lib/api/types.ts | 2 +- .../webui/tests/api-client-timeout.test.ts | 86 +++++++++++++++++++ packages/webui/tests/storage-api.test.ts | 10 ++- 5 files changed, 146 insertions(+), 13 deletions(-) create mode 100644 packages/webui/tests/api-client-timeout.test.ts diff --git a/packages/webui/src/components/process-probe-dialog.tsx b/packages/webui/src/components/process-probe-dialog.tsx index 31bd1e38..6c0cc839 100644 --- a/packages/webui/src/components/process-probe-dialog.tsx +++ b/packages/webui/src/components/process-probe-dialog.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { Eye, Loader2, User, UserX } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { @@ -37,31 +37,48 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange, onLoa const [loading, setLoading] = useState(false); const [info, setInfo] = useState(null); const [error, setError] = useState(null); + const activeProbe = useRef(null); const probe = useCallback(async () => { + activeProbe.current?.abort(); + const controller = new AbortController(); + activeProbe.current = controller; setLoading(true); setError(null); setInfo(null); try { - const result = await api.processes.probeLoginInfo(pid); + const result = await api.processes.probeLoginInfo(pid, controller.signal); + if (activeProbe.current !== controller) return; setInfo(result as QqPortLoginInfo | null); if (!result) { setError('未检测到登录信息(端口 9210-9219 无响应)'); } } catch (err) { + if (activeProbe.current !== controller || controller.signal.aborted) return; setError(err instanceof Error ? err.message : '探测失败'); } finally { - setLoading(false); + if (activeProbe.current === controller) { + activeProbe.current = null; + setLoading(false); + } } }, [api.processes, pid]); useEffect(() => { if (open) { - probe(); + void probe(); } else { + activeProbe.current?.abort(); + activeProbe.current = null; + setLoading(false); setInfo(null); setError(null); } + + return () => { + activeProbe.current?.abort(); + activeProbe.current = null; + }; }, [open, probe]); return ( diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 98f1aeda..b965e066 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -18,6 +18,7 @@ import { import { localStorageTokenStore } from './token-store'; const DEFAULT_TOKEN_KEY = 'snowluma_token'; +const REQUEST_TIMEOUT_MS = 30_000; interface ErrorPayload { message?: string; @@ -72,7 +73,10 @@ class HttpApiClient implements ApiClient { load: (pid) => this.postJson(`/api/processes/${pid}/load`), unload: (pid) => this.postJson(`/api/processes/${pid}/unload`), refresh: (pid) => this.postJson(`/api/processes/${pid}/refresh`), - probeLoginInfo: (pid) => this.getJson<{ info: unknown }>(`/api/processes/${pid}/probe-login`).then((d) => d.info ?? null), + probeLoginInfo: (pid, signal) => this.fetchJson<{ info: unknown }>( + `/api/processes/${pid}/probe-login`, + { signal }, + ).then((d) => d.info ?? null), }; this.config = { @@ -211,7 +215,7 @@ class HttpApiClient implements ApiClient { getPublic: async () => { // Pre-auth path: a plain fetch with no bearer. Used by the login page // to theme itself before the operator has signed in. - const res = await fetch('/api/ui/public'); + const res = await this.fetchWithDeadline('/api/ui/public'); if (!res.ok) throw new ApiError(res.status, '无法获取外观配置'); const data = await readJson<{ appearance: UiAppearance }>(res); return data.appearance; @@ -303,7 +307,8 @@ class HttpApiClient implements ApiClient { }; 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 }); + + const res = await this.fetchWithDeadline(url, { ...init, headers }); if (res.status === 401) { this.setToken(null); this.onUnauthorized?.(); @@ -311,6 +316,29 @@ class HttpApiClient implements ApiClient { return res; } + private async fetchWithDeadline( + url: string, + init: RequestInit = {}, + ): Promise { + const deadline = new AbortController(); + const onCallerAbort = () => deadline.abort(init.signal?.reason); + if (init.signal?.aborted) onCallerAbort(); + else init.signal?.addEventListener('abort', onCallerAbort, { once: true }); + const timer = setTimeout(() => deadline.abort(), REQUEST_TIMEOUT_MS); + try { + const res = await fetch(url, { ...init, signal: deadline.signal }); + return res; + } catch (error) { + if (deadline.signal.aborted && !init.signal?.aborted) { + throw new ApiError(408, '请求超时,请重试', 'REQUEST_TIMEOUT'); + } + throw error; + } finally { + clearTimeout(timer); + init.signal?.removeEventListener('abort', onCallerAbort); + } + } + /** 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); @@ -349,7 +377,7 @@ class HttpApiClient implements ApiClient { // 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', { + const res = await this.fetchWithDeadline('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password }), diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 2ee25755..87a8ddde 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -151,7 +151,7 @@ export interface ApiClient { load(pid: number): Promise; unload(pid: number): Promise; refresh(pid: number): Promise; - probeLoginInfo(pid: number): Promise; + probeLoginInfo(pid: number, signal?: AbortSignal): Promise; }; // ---- OneBotInstance per-UIN config ---- diff --git a/packages/webui/tests/api-client-timeout.test.ts b/packages/webui/tests/api-client-timeout.test.ts new file mode 100644 index 00000000..d8b3e8f3 --- /dev/null +++ b/packages/webui/tests/api-client-timeout.test.ts @@ -0,0 +1,86 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createApiClient } from '../src/lib/api/client'; + +const tokenStore = { + load: () => 'test-token', + save: () => undefined, +}; + +describe('API client request deadline', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it('aborts a pending request and reports a retryable timeout', async () => { + vi.stubGlobal('fetch', vi.fn((_url: string, init?: RequestInit) => new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')); + }, { once: true }); + }))); + const client = createApiClient({ tokenStore }); + + const request = client.request('/api/processes'); + const rejection = expect(request).rejects.toMatchObject({ + message: '请求超时,请重试', + code: 'REQUEST_TIMEOUT', + }); + await vi.advanceTimersByTimeAsync(30_000); + + await rejection; + }); + + it('cancels a login probe without preventing a later retry', async () => { + const fetchMock = vi + .fn() + .mockImplementationOnce((_url: string, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')); + }, { once: true }); + }), + ) + .mockResolvedValueOnce(new Response(JSON.stringify({ + info: { port: 0, uin: '', loggedIn: false }, + }), { + status: 200, + headers: { 'content-type': 'application/json' }, + })); + vi.stubGlobal('fetch', fetchMock); + const client = createApiClient({ tokenStore }); + const controller = new AbortController(); + + const cancelled = client.processes.probeLoginInfo(4242, controller.signal); + controller.abort(); + + await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' }); + await expect(client.processes.probeLoginInfo(4242)).resolves.toEqual({ + port: 0, + uin: '', + loggedIn: false, + }); + }); + + it('settles a pending login with a retryable timeout message', async () => { + vi.stubGlobal('fetch', vi.fn((_url: string, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')); + }, { once: true }); + }), + )); + const client = createApiClient({ tokenStore }); + + const login = client.login('password'); + await vi.advanceTimersByTimeAsync(30_000); + + await expect(login).resolves.toEqual({ + ok: false, + message: '请求超时,请重试', + }); + }); +}); diff --git a/packages/webui/tests/storage-api.test.ts b/packages/webui/tests/storage-api.test.ts index 6c7ea329..5bf853e0 100644 --- a/packages/webui/tests/storage-api.test.ts +++ b/packages/webui/tests/storage-api.test.ts @@ -43,9 +43,10 @@ describe('storage API client', () => { const client = createApiClient({ tokenStore }); await expect(client.storage.get()).resolves.toEqual(payload); - expect(fetchMock).toHaveBeenCalledWith('/api/system/storage', { + expect(fetchMock).toHaveBeenCalledWith('/api/system/storage', expect.objectContaining({ headers: { Authorization: 'Bearer test-token' }, - }); + signal: expect.any(AbortSignal), + })); }); it('posts a partial log-settings patch', async () => { @@ -64,14 +65,15 @@ describe('storage API client', () => { const client = createApiClient({ tokenStore }); await client.storage.saveSettings({ logRetainDays: 0 }); - expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', { + expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', expect.objectContaining({ method: 'POST', body: JSON.stringify({ logRetainDays: 0 }), headers: { Authorization: 'Bearer test-token', 'Content-Type': 'application/json', }, - }); + signal: expect.any(AbortSignal), + })); }); it('returns a structured partial cleanup result from an HTTP 500 response', async () => {