fix(webui): recover stalled requests

This commit is contained in:
DrSmoothl committed 2026-07-29 02:15:30 +08:00
1 parent f97444c391
commit 04cbb8cbf3
5 files changed
+145 -12

No files matched your search

@@ -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 { Eye, Loader2, User, UserX } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
@@ -37,31 +37,48 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange, onLoa
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [info, setInfo] = useState<QqPortLoginInfo | null>(null); const [info, setInfo] = useState<QqPortLoginInfo | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const activeProbe = useRef<AbortController | null>(null);
const probe = useCallback(async () => { const probe = useCallback(async () => {
activeProbe.current?.abort();
const controller = new AbortController();
activeProbe.current = controller;
setLoading(true); setLoading(true);
setError(null); setError(null);
setInfo(null); setInfo(null);
try { 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); setInfo(result as QqPortLoginInfo | null);
if (!result) { if (!result) {
setError('未检测到登录信息(端口 9210-9219 无响应)'); setError('未检测到登录信息(端口 9210-9219 无响应)');
} }
} catch (err) { } catch (err) {
if (activeProbe.current !== controller || controller.signal.aborted) return;
setError(err instanceof Error ? err.message : '探测失败'); setError(err instanceof Error ? err.message : '探测失败');
} finally { } finally {
if (activeProbe.current === controller) {
activeProbe.current = null;
setLoading(false); setLoading(false);
} }
}
}, [api.processes, pid]); }, [api.processes, pid]);
useEffect(() => { useEffect(() => {
if (open) { if (open) {
probe(); void probe();
} else { } else {
activeProbe.current?.abort();
activeProbe.current = null;
setLoading(false);
setInfo(null); setInfo(null);
setError(null); setError(null);
} }
return () => {
activeProbe.current?.abort();
activeProbe.current = null;
};
}, [open, probe]); }, [open, probe]);
return ( return (
+32 -4
View File
@@ -18,6 +18,7 @@ import {
import { localStorageTokenStore } from './token-store'; import { localStorageTokenStore } from './token-store';
const DEFAULT_TOKEN_KEY = 'snowluma_token'; const DEFAULT_TOKEN_KEY = 'snowluma_token';
const REQUEST_TIMEOUT_MS = 30_000;
interface ErrorPayload { interface ErrorPayload {
message?: string; message?: string;
@@ -72,7 +73,10 @@ class HttpApiClient implements ApiClient {
load: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/load`), load: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/load`),
unload: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/unload`), unload: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/unload`),
refresh: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/refresh`), refresh: (pid) => this.postJson<ProcessActionResult>(`/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 = { this.config = {
@@ -211,7 +215,7 @@ class HttpApiClient implements ApiClient {
getPublic: async () => { getPublic: async () => {
// Pre-auth path: a plain fetch with no bearer. Used by the login page // Pre-auth path: a plain fetch with no bearer. Used by the login page
// to theme itself before the operator has signed in. // 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, '无法获取外观配置'); if (!res.ok) throw new ApiError(res.status, '无法获取外观配置');
const data = await readJson<{ appearance: UiAppearance }>(res); const data = await readJson<{ appearance: UiAppearance }>(res);
return data.appearance; return data.appearance;
@@ -303,7 +307,8 @@ class HttpApiClient implements ApiClient {
}; };
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`; if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json'; 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) { if (res.status === 401) {
this.setToken(null); this.setToken(null);
this.onUnauthorized?.(); this.onUnauthorized?.();
@@ -311,6 +316,29 @@ class HttpApiClient implements ApiClient {
return res; return res;
} }
private async fetchWithDeadline(
url: string,
init: RequestInit = {},
): Promise<Response> {
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. */ /** Like request(), but throws ApiError on non-2xx and parses JSON. */
private async fetchJson<T>(url: string, init: RequestInit = {}): Promise<T> { private async fetchJson<T>(url: string, init: RequestInit = {}): Promise<T> {
const res = await this.request(url, init); const res = await this.request(url, init);
@@ -349,7 +377,7 @@ class HttpApiClient implements ApiClient {
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password // Login deliberately bypasses fetchJson/onUnauthorized so a bad password
// doesn't trigger a global sign-out side effect. // doesn't trigger a global sign-out side effect.
try { try {
const res = await fetch('/api/login', { const res = await this.fetchWithDeadline('/api/login', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }), body: JSON.stringify({ password }),
+1 -1
View File
@@ -151,7 +151,7 @@ export interface ApiClient {
load(pid: number): Promise<ProcessActionResult>; load(pid: number): Promise<ProcessActionResult>;
unload(pid: number): Promise<ProcessActionResult>; unload(pid: number): Promise<ProcessActionResult>;
refresh(pid: number): Promise<ProcessActionResult>; refresh(pid: number): Promise<ProcessActionResult>;
probeLoginInfo(pid: number): Promise<unknown>; probeLoginInfo(pid: number, signal?: AbortSignal): Promise<unknown>;
}; };
// ---- OneBotInstance per-UIN config ---- // ---- OneBotInstance per-UIN config ----
@@ -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<Response>((_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<Response>((_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<Response>((_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: '请求超时,请重试',
});
});
});
+6 -4
View File
@@ -43,9 +43,10 @@ describe('storage API client', () => {
const client = createApiClient({ tokenStore }); const client = createApiClient({ tokenStore });
await expect(client.storage.get()).resolves.toEqual(payload); 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' }, headers: { Authorization: 'Bearer test-token' },
}); signal: expect.any(AbortSignal),
}));
}); });
it('posts a partial log-settings patch', async () => { it('posts a partial log-settings patch', async () => {
@@ -64,14 +65,15 @@ describe('storage API client', () => {
const client = createApiClient({ tokenStore }); const client = createApiClient({ tokenStore });
await client.storage.saveSettings({ logRetainDays: 0 }); await client.storage.saveSettings({ logRetainDays: 0 });
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', { expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', expect.objectContaining({
method: 'POST', method: 'POST',
body: JSON.stringify({ logRetainDays: 0 }), body: JSON.stringify({ logRetainDays: 0 }),
headers: { headers: {
Authorization: 'Bearer test-token', Authorization: 'Bearer test-token',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}); signal: expect.any(AbortSignal),
}));
}); });
it('returns a structured partial cleanup result from an HTTP 500 response', async () => { it('returns a structured partial cleanup result from an HTTP 500 response', async () => {