Skip to content

Conversation

@Th-Shivam
Copy link

@Th-Shivam Th-Shivam commented Feb 10, 2026

Implement Automatic Network IP & QR Code Update

Fixes #51

Description

This PR addresses the issue where the application's displayed IP address and QR code remained stale when the host machine switched networks (e.g., changing WiFi or connecting to a hotspot). Previously, the IP was only fetched on initial load, requiring a manual refresh to update the connection details.

Changes Made

1. Server-side (Backend)

  • Modified src/server/websocket.ts to implement a network interface polling mechanism.
  • Added a POLLING_INTERVAL (5 seconds) that checks for IP changes using os.networkInterfaces().
  • Implemented a broadcast system to notify all connected WebSocket clients immediately when a network change is detected.

2. Frontend (UI)

  • Updated src/routes/settings.tsx to maintain a persistent WebSocket connection for IP tracking.
  • The UI now listens for server-ip update messages and updates the local state in real-time.
  • Changes in the IP state automatically trigger the regeneration of the connection QR code and URL.

How to Test

  1. Run the application in development mode: npm run dev.
  2. Open the Settings page (http://localhost:3000/settings).
  3. Note the current IP and QR code.
  4. Switch your host machine's network (e.g., connect to a different WiFi or mobile hotspot).
  5. Observe that the Server IP field and QR Code update automatically within 5 seconds without a page reload.

Checklist

  • My code follows the project's style guidelines.
  • I have performed a self-review of my own code.
  • I have verified the changes with a local build (npm run build).
  • All existing functionality remains intact.

Summary by CodeRabbit

  • New Features

    • Real-time local IP tracking with automatic broadcasting to connected clients.
    • Settings page now receives continuous live IP updates without closing the connection after the first response.
  • Bug Fixes

    • Improved IP auto-detection and connection logging messages.
    • Broadened message/error handling for more reliable IP updates.
    • Safer socket shutdown on page exit and fixed input-handling fall-through to prevent unintended actions.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 10, 2026

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (6)
  • public/favicon.ico is excluded by !**/*.ico
  • public/icon.svg is excluded by !**/*.svg
  • public/logo192.png is excluded by !**/*.png
  • public/logo512.png is excluded by !**/*.png
  • public/tanstack-circle-logo.png is excluded by !**/*.png
  • public/tanstack-word-logo-white.svg is excluded by !**/*.svg

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds dynamic local IP polling and broadcasting on the server, updates client SettingsPage to maintain an open WebSocket for live IP updates, and fixes a switch-case fall-through in the input message handler.

Changes

Cohort / File(s) Summary
Server IP detection & broadcasting
src/server/websocket.ts
Introduce currentIp via getLocalIp(), poll every 5s, detect IP changes, broadcast server-ip to all WS clients, send current IP on new connections, and clean up polling on server close/SIGTERM. Replaces previous LAN_IP usage and adds logging.
Client Settings & IP handling
src/routes/settings.tsx
Update JSDoc for SettingsPage. Replace and clarify WS logs; handle messages with type: 'server-ip' or type: 'connected' and accept data.ip or data.serverIp. Keep socket open for subsequent updates and safely close on unmount with logging. Minor formatting tweaks in UI code.
Input message handling fix
src/server/InputHandler.ts
Add JSDoc for handleMessage and insert break at end of the move case to prevent fall-through; whitespace/formatting adjusted.

Sequence Diagram(s)

sequenceDiagram
    participant Net as Network Interface
    participant Server as App Server (poller)
    participant WSS as WebSocket Server
    participant Client as Browser SettingsPage

    Server->>Net: call getLocalIp() every 5s
    Net-->>Server: return current IP

    alt IP changed
        Server->>WSS: broadcast {type: "server-ip", serverIp}
        WSS->>Client: send server-ip message
        Client->>Client: update displayed IP / QR
    else IP unchanged
        Server->>Server: continue polling
    end

    Note over Client,WSS: On new client connection
    Client->>WSS: open WebSocket
    WSS->>Client: send {type: "connected", ip: currentIp}
    Client->>Client: initialize displayed IP
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nudge the socket, twitch my nose,

Polling paths where network flows.
When addresses shift and wander far,
I shout the new IP to each client star.
Hop on—connections keep their glow. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: implementing real-time IP auto-updates via server polling, which is the primary objective of the PR.
Linked Issues check ✅ Passed The PR implements all coding requirements from issue #51: server-side IP polling detection, real-time WebSocket broadcast of changes, client-side persistent connection listening, automatic IP/QR code updates, and resource cleanup.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the network IP auto-update issue: server polling/broadcast implementation, client WebSocket persistence, JSDoc improvements, and necessary socket cleanup—all align with PR objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@src/routes/settings.tsx`:
- Around line 73-76: The cleanup currently only closes the socket when
socket.readyState === WebSocket.OPEN, missing the CONNECTING state; update the
teardown in the component's cleanup (the return callback where `socket` is
referenced) to close the socket whenever it's not already closing/closed — e.g.
check `socket && socket.readyState !== WebSocket.CLOSING && socket.readyState
!== WebSocket.CLOSED` (or explicitly allow OPEN and CONNECTING) before calling
`socket.close()` so connecting sockets are properly torn down.

In `@src/server/websocket.ts`:
- Line 40: The messages use inconsistent IP property names (some send { serverIp
} while others send { ip }); standardize on a single property (use "ip") across
all message payloads: update the construction of updateMsg (currently
JSON.stringify({ type: 'server-ip', ip: currentIp })) is correct, so change the
payload for the "connected" message and any other sends/broadcasts that use
serverIp to use ip instead (look for occurrences of "serverIp" in the
send/broadcast logic and in functions building the "connected" message) so the
client can always read data.ip.
- Around line 33-47: The setInterval polling in websocket.ts is never cleared
causing a resource leak; modify createWsServer (or the scope where currentIp and
wss are created) to store the interval ID (e.g., pollingIntervalId) returned by
setInterval and add cleanup to clearInterval(pollingIntervalId) when the
WebSocket server closes or is recreated: attach a 'close' handler on wss (or
call clearInterval before creating a new server) to call clearInterval, and also
ensure any process shutdown hooks clear it so intervals don't stack if
createWsServer runs multiple times.
🧹 Nitpick comments (2)
src/routes/settings.tsx (2)

44-77: No reconnection logic if the WebSocket drops.

If the server restarts or the connection is lost, the client silently stops receiving IP updates. Consider adding an onerror/onclose handler with a retry (e.g., exponential backoff or a simple setTimeout reconnect) so the live-update feature is resilient.


59-67: Dual-property handling is a workaround for server inconsistency.

The (data.ip || data.serverIp) check on line 64 exists only because the server sends different property names for different message types. Once the server-side naming is unified (as suggested in the other file), simplify this to a single property.

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.

[Bug]:IP Address and QR Code do not update when network changes

1 participant