Files
claude-code/packages/remote-control-server/web/sse.js
claude-code-best 2da6514095 feat: 支持自托管的 remote-control-server (#214)
* feat: 支持自托管的 remote-control-server (#214)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-04-09 17:40:50 +08:00

54 lines
1.4 KiB
JavaScript

/**
* Remote Control — SSE Connection Manager (UUID-based auth)
*/
import { getUuid } from "./api.js";
import { refreshLoadingActivity } from "./render.js";
let currentEventSource = null;
let currentSSESessionId = null;
let onEventCallback = null;
export function connectSSE(sessionId, onEvent, fromSeqNum = 0) {
disconnectSSE();
currentSSESessionId = sessionId;
onEventCallback = onEvent;
const uuid = getUuid();
let url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
const es = new EventSource(url);
currentEventSource = es;
// Track the last sequence number we've seen to avoid duplicates
let lastSeenSeq = fromSeqNum;
es.addEventListener("message", (e) => {
try {
const data = JSON.parse(e.data);
// Skip events we've already rendered from history
if (data.seqNum !== undefined && data.seqNum <= lastSeenSeq) return;
if (data.seqNum !== undefined) lastSeenSeq = data.seqNum;
onEventCallback?.(data);
refreshLoadingActivity();
} catch {
// ignore parse errors
}
});
es.addEventListener("error", () => {
// EventSource auto-reconnects
});
}
export function disconnectSSE() {
if (currentEventSource) {
currentEventSource.close();
currentEventSource = null;
currentSSESessionId = null;
}
}
export function getCurrentSSESessionId() {
return currentSSESessionId;
}