Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(realtime): reconnect on document visibility change

Sidwebworkse5187719d2dd
diff --git a/packages/react/src/hooks/useRealtimeChannel.ts b/packages/react/src/hooks/useRealtimeChannel.ts
index 9b76b9c1ef..6b83f9fb6e 100644
--- a/packages/react/src/hooks/useRealtimeChannel.ts
+++ b/packages/react/src/hooks/useRealtimeChannel.ts
@@ -48,6 +48,7 @@ export const useRealtimeChannel = <TDeps extends any[]>(
const lastErrorToastAtRef = useRef<number>(0);
const retryCountRef = useRef(0);
const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const isVisibilityReconnectRef = useRef(false);
// Updated each effect run so the retry timer always calls the latest subscribe closure.
const doSubscribeRef = useRef<() => Promise<void>>(() => Promise.resolve());
const { carbon, isRealtimeAuthSet } = useCarbon();
@@ -118,7 +119,11 @@ export const useRealtimeChannel = <TDeps extends any[]>(
status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR ||
status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT;
- if (isRetriableError && notifyOnSubscribeError) {
+ if (
+ isRetriableError &&
+ notifyOnSubscribeError &&
+ !isVisibilityReconnectRef.current
+ ) {
const now = Date.now();
if (now - lastErrorToastAtRef.current > 12_000) {
lastErrorToastAtRef.current = now;
@@ -160,8 +165,26 @@ export const useRealtimeChannel = <TDeps extends any[]>(
doSubscribeRef.current = doSubscribe;
void doSubscribe();
+ const handleVisibilityChange = () => {
+ if (document.visibilityState === "visible") {
+ // Cancel pending retry and reconnect immediately
+ if (retryTimerRef.current) {
+ clearTimeout(retryTimerRef.current);
+ retryTimerRef.current = null;
+ }
+ retryCountRef.current = 0;
+ isVisibilityReconnectRef.current = true;
+ void doSubscribeRef.current().finally(() => {
+ isVisibilityReconnectRef.current = false;
+ });
+ }
+ };
+
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+
// Cleanup on unmount or dependency change
return () => {
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
if (retryTimerRef.current) {
clearTimeout(retryTimerRef.current);
retryTimerRef.current = null;