fix(webui): keep live streams alive after Safari page hide
Safari freezes fetch SSE when the tab is backgrounded. Close the stream on hide, reopen on show, and accept both line endings.
This commit is contained in:
1 file changed
+89
-15
@@ -414,7 +414,9 @@ class HttpApiClient implements ApiClient {
|
|||||||
...((init.headers as Record<string, string> | undefined) ?? {}),
|
...((init.headers as Record<string, string> | undefined) ?? {}),
|
||||||
};
|
};
|
||||||
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 && !(init.body instanceof FormData) && !headers['Content-Type']) {
|
||||||
|
headers['Content-Type'] = 'application/json';
|
||||||
|
}
|
||||||
|
|
||||||
const res = await this.fetchWithDeadline(url, { ...init, headers });
|
const res = await this.fetchWithDeadline(url, { ...init, headers });
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
@@ -626,9 +628,11 @@ class HttpApiClient implements ApiClient {
|
|||||||
active = controller;
|
active = controller;
|
||||||
try {
|
try {
|
||||||
const response = await fetch(path, {
|
const response = await fetch(path, {
|
||||||
|
cache: 'no-store',
|
||||||
headers: {
|
headers: {
|
||||||
Accept: 'text/event-stream',
|
Accept: 'text/event-stream',
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Cache-Control': 'no-cache',
|
||||||
},
|
},
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
@@ -650,7 +654,10 @@ class HttpApiClient implements ApiClient {
|
|||||||
try {
|
try {
|
||||||
while (!disposed) {
|
while (!disposed) {
|
||||||
const { done, value } = await reader.read();
|
const { done, value } = await reader.read();
|
||||||
if (done) break;
|
if (done) {
|
||||||
|
buffer += decoder.decode();
|
||||||
|
break;
|
||||||
|
}
|
||||||
buffer += decoder.decode(value, { stream: true });
|
buffer += decoder.decode(value, { stream: true });
|
||||||
if (buffer.length > 1024 * 1024) throw new Error('SSE frame buffer exceeded 1 MiB');
|
if (buffer.length > 1024 * 1024) throw new Error('SSE frame buffer exceeded 1 MiB');
|
||||||
for (;;) {
|
for (;;) {
|
||||||
@@ -678,7 +685,8 @@ class HttpApiClient implements ApiClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
reader.releaseLock();
|
try { await reader.cancel(); } catch { /* already closed */ }
|
||||||
|
try { reader.releaseLock(); } catch { /* already released */ }
|
||||||
}
|
}
|
||||||
if (!disposed) scheduleReconnect();
|
if (!disposed) scheduleReconnect();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -688,10 +696,43 @@ class HttpApiClient implements ApiClient {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const onPageHide = () => { active?.abort(); };
|
||||||
|
const onPageShow = (event: PageTransitionEvent) => {
|
||||||
|
if (event.persisted && !disposed) {
|
||||||
|
if (reconnectTimer !== null) {
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
void connect();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onVisible = () => {
|
||||||
|
if (document.visibilityState === 'visible' && !disposed && !active) {
|
||||||
|
if (reconnectTimer !== null) {
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
void connect();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const page = typeof window !== 'undefined' && typeof document !== 'undefined';
|
||||||
|
if (page) {
|
||||||
|
window.addEventListener('pagehide', onPageHide);
|
||||||
|
window.addEventListener('pageshow', onPageShow);
|
||||||
|
document.addEventListener('visibilitychange', onVisible);
|
||||||
|
document.addEventListener('freeze', onPageHide);
|
||||||
|
}
|
||||||
|
|
||||||
void connect();
|
void connect();
|
||||||
return () => {
|
return () => {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
disposed = true;
|
disposed = true;
|
||||||
|
if (page) {
|
||||||
|
window.removeEventListener('pagehide', onPageHide);
|
||||||
|
window.removeEventListener('pageshow', onPageShow);
|
||||||
|
document.removeEventListener('visibilitychange', onVisible);
|
||||||
|
document.removeEventListener('freeze', onPageHide);
|
||||||
|
}
|
||||||
if (reconnectTimer !== null) clearTimeout(reconnectTimer);
|
if (reconnectTimer !== null) clearTimeout(reconnectTimer);
|
||||||
reconnectTimer = null;
|
reconnectTimer = null;
|
||||||
active?.abort();
|
active?.abort();
|
||||||
@@ -770,10 +811,15 @@ class HttpApiClient implements ApiClient {
|
|||||||
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
|
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
const headers: Record<string, string> = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Accept: 'text/event-stream',
|
||||||
|
'Cache-Control': 'no-cache',
|
||||||
|
};
|
||||||
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
|
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
|
||||||
const res = await fetch('/api/debug/invoke-stream', {
|
const res = await fetch('/api/debug/invoke-stream', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
cache: 'no-store',
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify({ uin, action, params }),
|
body: JSON.stringify({ uin, action, params }),
|
||||||
signal,
|
signal,
|
||||||
@@ -790,18 +836,46 @@ class HttpApiClient implements ApiClient {
|
|||||||
const reader = res.body.getReader();
|
const reader = res.body.getReader();
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
let buf = '';
|
let buf = '';
|
||||||
for (;;) {
|
const takeFrames = (raw: string) => {
|
||||||
const { done, value } = await reader.read();
|
for (;;) {
|
||||||
if (done) break;
|
const lf = raw.indexOf('\n\n');
|
||||||
buf += decoder.decode(value, { stream: true });
|
const crlf = raw.indexOf('\r\n\r\n');
|
||||||
let sep: number;
|
let separator = -1;
|
||||||
while ((sep = buf.indexOf('\n\n')) >= 0) {
|
let separatorLength = 0;
|
||||||
const block = buf.slice(0, sep);
|
if (lf >= 0 && (crlf < 0 || lf < crlf)) {
|
||||||
buf = buf.slice(sep + 2);
|
separator = lf;
|
||||||
const line = block.startsWith('data: ') ? block.slice(6) : block;
|
separatorLength = 2;
|
||||||
if (!line.trim()) continue;
|
} else if (crlf >= 0) {
|
||||||
try { onFrame(JSON.parse(line) as import('@/types').DebugStreamFrame); } catch { /* skip malformed */ }
|
separator = crlf;
|
||||||
|
separatorLength = 4;
|
||||||
|
}
|
||||||
|
if (separator < 0) return raw;
|
||||||
|
const block = raw.slice(0, separator);
|
||||||
|
raw = raw.slice(separator + separatorLength);
|
||||||
|
const data = block
|
||||||
|
.split(/\r?\n/u)
|
||||||
|
.filter((line) => line.startsWith('data:'))
|
||||||
|
.map((line) => line.slice(5).replace(/^ /u, ''))
|
||||||
|
.join('\n');
|
||||||
|
if (!data) continue;
|
||||||
|
try { onFrame(JSON.parse(data) as import('@/types').DebugStreamFrame); } catch { /* skip malformed */ }
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
buf += decoder.decode();
|
||||||
|
takeFrames(buf);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buf += decoder.decode(value, { stream: true });
|
||||||
|
if (buf.length > 1024 * 1024) throw new Error('SSE frame buffer exceeded 1 MiB');
|
||||||
|
buf = takeFrames(buf);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
try { await reader.cancel(); } catch { /* already closed */ }
|
||||||
|
try { reader.releaseLock(); } catch { /* already released */ }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user