Client-side reconnect
Mobile networks drop. Wi-Fi switches. A long answer mid-stream becomes a stuck UI if the client does not handle the disconnect. The fix is short: detect the close, resume with the last-event-id header, and let the server skip events the client already saw.
Reconnect handshake
The client tracks the most recent event id, retries on close, and the server resumes from the next event in the run.
web/sse-client.js
javascript
let lastEventId = null;
async function connect(threadId) {
while (true) {
try {
const res = await fetch(`/stream?thread=${threadId}`, {
headers: lastEventId ? { 'Last-Event-ID': lastEventId } : {},
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const events = buffer.split('\n\n');
buffer = events.pop() || '';
for (const raw of events) {
const idLine = raw.split('\n').find(l => l.startsWith('id: '));
if (idLine) lastEventId = idLine.slice(4);
handle(raw);
}
}
} catch (err) {
await new Promise(r => setTimeout(r, 1000));
}
}
}Track the last event id, send it on retry, and the server resumes mid-run. The user sees a brief pause instead of a broken answer.
Quiz: Quiz
Loading practice…