feat(webui): debug-console shared primitives, data layer, task manager

Phase 3 of the debug-console expansion — the Apple-HIG foundation the
new tabs build on (reusing the existing ui kit; new controls match its
idiom, no browser-native widgets).

API client + types:
- debug.invokeStream() reads /api/debug/invoke-stream via fetch + a body
  reader, parsing data:<json> SSE frames (header auth, cancellable).
- debug.upload() streams a file via XHR for real upload progress.
- DebugActionParam.role, DebugActionDoc.stream/invariants, FieldRole,
  DebugStreamFrame, DebugUploadResult.

Primitives:
- Tabs (sliding indicator + roving tabindex), Picker (searchable,
  windowed combobox with a raw-value escape hatch), JsonTree (collapsible
  response viewer, image-url preview, copy w/ http fallback, node cap),
  FileSource (URL / server-path / browser-upload tri-state), FaceGrid.

Infra:
- DebugTaskProvider + TaskBadge: app-level registry of in-flight upload/
  stream tasks so they survive in-app tab switches, with a global
  progress chip and a beforeunload guard; eviction never drops a running
  task. Wired into App.
- use-debug-contacts: lazy friend/group/member data layer, shared module
  cache + localStorage (version-stamped, avatars stripped to dodge quota)
  + TTL + request-id race guard, degrading to raw input on error.

Adversarially reviewed (no automated component tests): virtualization
math and SSE framing verified correct; fixed the stale-contacts-on-switch
member-selection hazard, the quota-kills-persistence issue, and several
low UX edges (active-row clamp, filter scroll reset, copy fallback).
This commit is contained in:
DrSmoothl committed 2026-06-30 16:53:43 +08:00
1 parent a7667f1cd5
commit c5611ed622
12 files changed
+1188 -2

No files matched your search

+85
View File
@@ -128,6 +128,9 @@ class HttpApiClient implements ApiClient {
actions: () => this.getJson<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>('/api/debug/actions'),
invoke: (uin: string, action: string, params: Record<string, unknown>) =>
this.postJson<DebugInvokeResult>('/api/debug/invoke', { uin, action, params }),
invokeStream: (uin, action, params, onFrame, signal) =>
this.openDebugInvokeStream(uin, action, params, onFrame, signal),
upload: (file, opts) => this.uploadDebugFile(file, opts),
stream: (onMessage, onStatus) => this.openDebugStream(onMessage, onStatus),
};
@@ -405,6 +408,88 @@ class HttpApiClient implements ApiClient {
};
}
// Invoke a (stream) action and relay each `data: <json>\n\n` SSE frame. Uses
// fetch + a body reader (not EventSource) so the bearer token rides in the
// header and the request can be a POST. Resolves when the stream ends.
private async openDebugInvokeStream(
uin: string,
action: string,
params: Record<string, unknown>,
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
signal?: AbortSignal,
): Promise<void> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
const res = await fetch('/api/debug/invoke-stream', {
method: 'POST',
headers,
body: JSON.stringify({ uin, action, params }),
signal,
});
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
throw new ApiError(401, '未授权');
}
if (!res.ok || !res.body) {
const payload = await readJson<ErrorPayload>(res).catch(() => ({}) as ErrorPayload);
throw new ApiError(res.status, extractErrorMessage(payload, '流式调用失败'), payload.code);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let sep: number;
while ((sep = buf.indexOf('\n\n')) >= 0) {
const block = buf.slice(0, sep);
buf = buf.slice(sep + 2);
const line = block.startsWith('data: ') ? block.slice(6) : block;
if (!line.trim()) continue;
try { onFrame(JSON.parse(line) as import('@/types').DebugStreamFrame); } catch { /* skip malformed */ }
}
}
}
// Upload a browser file to a server temp path. Uses XHR (not fetch) so the
// upload progress callback can fire — fetch can't observe request-body
// progress. Returns the parsed { path, size }.
private uploadDebugFile(
file: File,
opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
): Promise<import('@/types').DebugUploadResult> {
return new Promise((resolve, reject) => {
const name = opts?.filename ?? file.name;
const xhr = new XMLHttpRequest();
xhr.open('POST', `/api/debug/upload?filename=${encodeURIComponent(name)}`);
if (this.currentToken) xhr.setRequestHeader('Authorization', `Bearer ${this.currentToken}`);
xhr.responseType = 'json';
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) opts?.onProgress?.(e.loaded / e.total);
};
xhr.onload = () => {
if (xhr.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
reject(new ApiError(401, '未授权'));
return;
}
const body = (xhr.response ?? {}) as import('@/types').DebugUploadResult;
if (xhr.status >= 200 && xhr.status < 300 && body.path) resolve(body);
else reject(new ApiError(xhr.status, body.message || '上传失败'));
};
xhr.onerror = () => reject(new ApiError(0, '上传网络错误'));
xhr.onabort = () => reject(new ApiError(0, '上传已取消'));
if (opts?.signal) {
if (opts.signal.aborted) { xhr.abort(); return; }
opts.signal.addEventListener('abort', () => xhr.abort(), { once: true });
}
xhr.send(file);
});
}
private openDebugStream(
onMessage: (m: DebugStreamMessage) => void,
onStatus?: (s: import('./types').StreamStatus) => void,
+17
View File
@@ -4,7 +4,9 @@ import type {
BackupImportResult,
DebugActionDoc,
DebugInvokeResult,
DebugStreamFrame,
DebugStreamMessage,
DebugUploadResult,
GlobalSettings,
HookProcessInfo,
LogEntry,
@@ -152,6 +154,21 @@ export interface ApiClient {
debug: {
actions(): Promise<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>;
invoke(uin: string, action: string, params: Record<string, unknown>): Promise<DebugInvokeResult>;
/** Invoke a Stream API action (or any action) and receive every frame.
* Resolves when the stream ends; pass a signal to cancel. */
invokeStream(
uin: string,
action: string,
params: Record<string, unknown>,
onFrame: (frame: DebugStreamFrame) => void,
signal?: AbortSignal,
): Promise<void>;
/** Stream a browser file to a temp path on the server; returns the path to
* feed a send action. `onProgress` reports 0..1 of bytes uploaded. */
upload(
file: File,
opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
): Promise<DebugUploadResult>;
/** Live merged SSE; returns an unsubscribe. */
stream(onMessage: (m: DebugStreamMessage) => void, onStatus?: (s: StreamStatus) => void): () => void;
};