Skip to content

fix: resolve stale closure and peer connection cleanup in P2P reconnection#16

Merged
taco-jpg merged 1 commit into
mainfrom
claude/wonderful-bell-bIyKk
May 24, 2026
Merged

fix: resolve stale closure and peer connection cleanup in P2P reconnection#16
taco-jpg merged 1 commit into
mainfrom
claude/wonderful-bell-bIyKk

Conversation

@taco-jpg
Copy link
Copy Markdown
Owner

Summary

Fixes a critical stale closure bug in the P2P reconnection logic that could cause logic errors and prevent proper fallback to relay mode.

Changes

  • Remove stale 'status' checks: The attemptP2PReconnection function was checking a stale status variable captured from the effect's initial render. Since effects don't re-run when state changes, this variable always held its initial 'connecting' value, making the checks ineffective and misleading.
  • Add peer connection cleanup: Previous peer connections from failed reconnection attempts are now explicitly closed before creating new ones, preventing resource leaks.
  • Improve fallback logic: Relay fallback now depends on actual data channel state rather than stale closure variables.

Impact

  • Fixes potential logic errors during reconnection attempts
  • Prevents peer connection resource leaks during failed reconnections
  • Simplifies reconnection logic and removes misleading conditions
  • Maintains all existing functionality while improving reliability

Testing

  • ESLint: ✓ PASS
  • Next.js build: ✓ PASS
  • No test suite present in repo (verified via package.json)

Generated by Claude Code

…ction

- Remove stale 'status' variable checks in attemptP2PReconnection that always evaluated to captured initial value
- Add explicit cleanup of previous peer connections before creating new ones
- Ensure relay fallback logic depends on data channel state, not stale closure variables
- Fixes potential logic errors during reconnection attempts and prevents peer connection leaks
Copilot AI review requested due to automatic review settings May 22, 2026 10:08
@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages Bot commented May 22, 2026

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
serotine b17aa1b Commit Preview URL

Branch Preview URL
May 22 2026, 10:09 AM

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b17aa1b874

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread hooks/use-p2p-chat.ts
Comment on lines +243 to +244
if (peerRef.current) {
peerRef.current.close();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Prevent stale onclose from scheduling concurrent reconnects

Calling peerRef.current.close() here can trigger the previous data channel’s onclose handler, which calls scheduleReconnection(). Because this happens while a new reconnection attempt is already in progress, a second reconnect timer can be queued and later tear down the fresh connection (or start overlapping attempts), causing reconnect thrash/flapping in unstable networks. This was introduced by the new pre-close step; suppress old handlers (or clear/guard reconnect scheduling) before closing the previous peer.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates the useP2PChat hook’s P2P reconnection flow to avoid stale React state in reconnection checks, explicitly close prior peer connections between attempts, and make relay fallback decisions based on actual DataChannel state.

Changes:

  • Close any existing RTCPeerConnection before starting a new reconnection attempt.
  • Remove stale status-closure gating so relay fallback always executes when reconnection doesn’t succeed.
  • Simplify reconnection timeout/catch fallback paths to consistently enter relay mode and reschedule attempts.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread hooks/use-p2p-chat.ts
Comment on lines +242 to +245
// Clean up previous peer connection if it exists
if (peerRef.current) {
peerRef.current.close();
}
Comment thread hooks/use-p2p-chat.ts
Comment on lines 343 to +351
setTimeout(async () => {
clearInterval(answerPoll);
if (mounted && dc.readyState !== 'open') {
pc.close();
if (status === 'connecting') {
setStatus('relay');
pollBackoffRef.current = 3000;
setupRelayPolling();
await pollRelayMessages();
scheduleReconnection();
}
setStatus('relay');
pollBackoffRef.current = 3000;
setupRelayPolling();
await pollRelayMessages();
scheduleReconnection();
@taco-jpg taco-jpg merged commit cc4bd10 into main May 24, 2026
2 checks passed
@taco-jpg taco-jpg deleted the claude/wonderful-bell-bIyKk branch May 24, 2026 01:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants