fix: deliver missed messages on SSE reconnect, preserve scroll position #96
+325
−142
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi, so I didn’t really want this to be this big, but one thing led to another…
It started with wanting to fix reconnection and message catchup on Safari iOS. But then if you come back to the tab and messages catch up, losing your scroll position is quite annoying, so I added scroll position saving. And then the hooks started to look a bit dodgy so did a bit of a refactor.
It all seems to work on my two instances - hope it makes sense. Won’t be offended if you reject / chop it into bits / whatever.
Thanks!
—-
Server: when an SSE stream reconnects with last_sequence_id, query ListMessagesSince to backfill messages written between disconnect and reconnect. Previously these were silently lost, causing invisible gaps. On resume, omit context_window_size (only partial messages available).
Client SSE reconnection: on iOS Safari, backgrounding a tab kills TCP connections but EventSource.readyState still reads OPEN. Track when the page was hidden and force-reconnect if backgrounded for >5s. Suppress auto-scroll during catch-up so the user's scroll position is preserved.
Client scroll position: save to localStorage on scroll settle (100ms debounce) and on visibilitychange/beforeunload. Restore via useLayoutEffect after messages render. Use ResizeObserver on .messages-list to re-scroll to bottom when content expands (images loading, tool outputs rendering) during streaming.
Refactor: replace function-in-ref patterns (reconnectRef, forceReconnectRef, handleManualReconnect) with useCallback hooks with proper dependency arrays. Wrap setupMessageStream in useCallback; nest resetHeartbeatTimeout inside it.