修复:查询局部刷新与智能分析会话交互,完善分析收尾和配置切换

This commit is contained in:
2026-10-23 15:30:06 +08:00
parent 5fbeb52b93
commit 6394e057bf
40 changed files with 2107 additions and 239 deletions
+22 -38
View File
@@ -1,3 +1,4 @@
import { consumeEventStream, type StreamEvent } from './eventStream';
import { publicErrorMessage } from './publicDataDisplay';
import type {
AuthUser,
@@ -18,7 +19,7 @@ export class ApiError extends Error {
details: unknown;
constructor(status: number, message: string, details?: unknown) {
super(publicErrorMessage(message));
super(publicErrorMessage(message, status));
this.name = 'ApiError';
this.status = status;
this.details = details;
@@ -27,6 +28,14 @@ export class ApiError extends Error {
let csrfToken: string | undefined;
async function fetchApi(path: string, init: RequestInit): Promise<Response> {
try { return await fetch(path, init); }
catch (error) {
if (init.signal?.aborted || (error instanceof DOMException && error.name === 'AbortError')) throw error;
throw new ApiError(0, '无法连接质量数据服务,请检查网络后重试;当前无法确认数据覆盖。');
}
}
async function readResponse<T>(response: Response): Promise<T> {
const raw = await response.text();
let payload: unknown;
@@ -51,13 +60,14 @@ async function readResponse<T>(response: Response): Promise<T> {
: `请求失败(${response.status})`;
throw new ApiError(response.status, message, payload);
}
if (typeof payload === 'string') throw new ApiError(response.status, '服务返回格式异常,请稍后重试。');
return payload as T;
}
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
const response = await fetch(path, {
const response = await fetchApi(path, {
...init,
headers,
credentials: 'same-origin',
@@ -67,7 +77,7 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
}
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal });
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal });
if (!response.ok) {
const raw = await response.text();
let payload: unknown = raw;
@@ -84,16 +94,12 @@ async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob:
return { blob: await response.blob(), filename };
}
export interface StreamEvent {
id?: string;
event: string;
data: unknown;
}
export type { StreamEvent } from './eventStream';
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
const headers = new Headers({ Accept: 'text/event-stream' });
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
const response = await fetch(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
if (!response.ok) {
const raw = await response.text();
let payload: unknown = raw;
@@ -102,35 +108,7 @@ async function readEventStream(path: string, options: { signal?: AbortSignal; la
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
}
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const dispatch = (frame: string) => {
if (!frame || frame.startsWith(':')) return;
let id: string | undefined;
let event = 'message';
const data: string[] = [];
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith('id:')) id = line.slice(3).trim();
else if (line.startsWith('event:')) event = line.slice(6).trim() || 'message';
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
}
if (data.length) {
const raw = data.join('\n');
let value: unknown = raw;
try { value = JSON.parse(raw) as unknown; } catch { /* allow plain text event data */ }
options.onEvent({ ...(id ? { id } : {}), event, data: value });
}
};
while (true) {
const { done, value } = await reader.read();
buffer += decoder.decode(value, { stream: !done });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || '';
for (const frame of frames) dispatch(frame);
if (done) break;
}
if (buffer.trim()) dispatch(buffer);
await consumeEventStream(response.body, options.onEvent);
}
export async function refreshCsrf(): Promise<string> {
@@ -175,6 +153,9 @@ export const api = {
logout() {
return mutate<void>('/api/auth/logout');
},
changePassword(currentPassword: string, newPassword: string) {
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
},
options() {
return request<OptionsResponse>('/api/options');
},
@@ -402,6 +383,9 @@ export const api = {
deleteAnalysisSession(id: string) {
return mutate<{ deleted: boolean; sessionId: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, undefined, 'DELETE');
},
renameAnalysisSession(id: string, title: string) {
return mutate<{ sessionId: string; title: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, { title }, 'PATCH');
},
analysisSessionTurns(id: string) {
return request<{ items: Record<string, unknown>[] }>(`/api/analysis/sessions/${encodeURIComponent(id)}/turns`);
},