fix: harden resume and SSE replay
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { BASE } from "../api/client";
|
||||
import { joinBackendPath } from "../api/runtime-config";
|
||||
import { useSessionStore } from "../store/sessionStore";
|
||||
@@ -7,15 +7,24 @@ import type { StreamEvent } from "../api/types";
|
||||
export function useSessionStream(sessionId: string | null, generation = 0) {
|
||||
const [connected, setConnected] = useState(false);
|
||||
const applyEvent = useSessionStore((s) => s.applyEvent);
|
||||
const cursor = useRef({ sessionId: null as string | null, lastEventId: "" });
|
||||
|
||||
if (cursor.current.sessionId !== sessionId) {
|
||||
cursor.current = { sessionId, lastEventId: "" };
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
|
||||
const es = new EventSource(joinBackendPath(BASE, `/sessions/${sessionId}/events`));
|
||||
const query = cursor.current.lastEventId
|
||||
? `?lastEventId=${encodeURIComponent(cursor.current.lastEventId)}`
|
||||
: "";
|
||||
const es = new EventSource(joinBackendPath(BASE, `/sessions/${sessionId}/events${query}`));
|
||||
es.onopen = () => setConnected(true);
|
||||
es.onerror = () => setConnected(false);
|
||||
|
||||
const handle = (ev: MessageEvent) => {
|
||||
if (ev.lastEventId) cursor.current.lastEventId = ev.lastEventId;
|
||||
try {
|
||||
applyEvent(JSON.parse(ev.data) as StreamEvent);
|
||||
} catch {
|
||||
|
||||
Reference in New Issue
Block a user