Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

My Dashboard Synced Itself Only While You Watched. Background Tabs Broke That.

VoiceDash is the client portal I build for voice AI agencies: each agency's clients log in and see their own agent's calls, transcripts and analytics. For a long time those calls arrived two ways. Retell pushed them by w

VoiceDash is the client portal I build for voice AI agencies: each agency's clients log in and see their own agent's calls, transcripts and analytics. For a long time those calls arrived two ways. Retell pushed them by webhook, and there was a "Sync Calls" button for everything the webhook missed.

The button was the problem. Nobody presses a sync button on a dashboard they opened to read numbers. So I wrote a small React hook that syncs on its own, shipped it, and less than an hour later shipped a fix for a case I had not thought about: a tab you have not looked at yet.

This is that hook, the one-line bug, and the parts I still have not fixed.

What the hook does

Two client pages show calls: the conversation list and the analytics dashboard. Both now call the same hook with the agent's ID and a callback that reloads the page's data.

const SYNC_EVERY_MS = 60_000;
/** Returning to the tab syncs again unless the last sync was this recent. */
const MIN_GAP_ON_RETURN_MS = 15_000;

export function useCallSync(agentId: string | undefined, onSynced: () => void) {
  const onSyncedRef = useRef(onSynced);
  onSyncedRef.current = onSynced;

  useEffect(() => {
    if (!agentId) return;
    let stopped = false;
    let running = false;
    let lastRun = 0;
    // sync(), onVisibilityChange(), the timer and the cleanup go here
  }, [agentId]);
}

Three triggers: when the page opens, when the tab comes back into view (unless it synced in the last 15 seconds), and every minute while the tab is visible. The callback lives in a ref so the effect does not tear down and restart its timer every time the parent re-renders with a new arrow function. The effect depends only on agentId.

The running flag stops a slow sync from overlapping with the next tick. stopped stops a sync that finishes after the user navigated away from calling back into an unmounted page.

Why "only while visible"

The server route behind the hook calls Retell's list-calls API with the agent's key. A dashboard left open in a forgotten tab for a weekend should not call a vendor API 2,880 times for nobody. So the first version guarded every sync the same way:

const sync = async () => {
  if (running || document.visibilityState !== "visible") return;
  // ...
};

sync();
const timer = setInterval(sync, SYNC_EVERY_MS);

That reads fine. It is also wrong for one case that showed up almost immediately.

The background tab

Open a dashboard with a middle click. Or restore a browser session with five portal tabs. The page loads, renders the calls already in the database, and its visibilityState is "hidden". The opening sync returns early.

Nothing is broken yet. The moment you switch to that tab, visibilitychange fires and the hook syncs. But between load and switch, the page shows stale data while looking finished, and the dashboard's whole promise was "you never press Sync".

The fix was to treat the opening sync differently from the repeat:

const sync = async ({ evenIfHidden = false } = {}) => {
  if (running || (!evenIfHidden && document.visibilityState !== "visible")) return;
  running = true;
  lastRun = Date.now();
  try {
    await fetch("/api/retell/sync-calls", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ agentId }),
    });
  } catch {
    // Calls that arrived by webhook still show; the next sync retries.
  } finally {
    running = false;
  }
  if (!stopped) onSyncedRef.current();
};

sync({ evenIfHidden: true });
const timer = setInterval(() => sync(), SYNC_EVERY_MS);

Note the () => sync() in setInterval. Passing sync directly would still work here because setInterval calls it with no arguments, but the wrapper makes it obvious that the repeat never gets evenIfHidden.

The rule I took from it: a page someone opened is a request, even if they are not looking at it yet. A timer someone forgot about is not. Those deserve different guards, and I had written one guard for both.

Refreshing without flicker

Syncing is half of it. After a sync the page has to show the result without becoming a loading skeleton every minute.

On analytics, the fetch takes a quiet flag that skips the loading placeholders, plus a request counter so an old response cannot overwrite a newer date range the user picked meanwhile:

const fetchData = async (quiet = false) => {
  const request = ++latestRequest.current;
  if (!quiet) setLoading(true);
  // ... fetch /api/analytics
  if (res.ok && request === latestRequest.current) setData(await res.json());
};

useCallSync(agentId, () => fetchData(true));

The conversation list was harder because the user might have scrolled through three pages and opened a transcript. Replacing the list would throw that away. So the refresh fetches the newest page and merges: unseen calls go on top, calls already shown get their fields updated (a call stored mid-call gets its final duration and transcript later), and the list is re-sorted by start time. If the search box changed while the request was in flight, the result belongs to a different list and is dropped.

What makes it safe to call this often

The client side is the easy part. The reason a once-a-minute sync is cheap lives on the server, and I covered most of it in A Webhook Tells You Something Happened, Not That You Have Everything. The short version:

  • Each agent stores callsSyncedUntil, how far its Retell history is known to be complete. A routine sync reads oldest first from two hours before that point, so it is usually a single request.
  • The watermark only moves forward. The update is conditional (callsSyncedUntil: null or lt: until), so two syncs of the same agent racing each other cannot move it backward.
  • Inserts use createMany with skipDuplicates against a unique key on (agentId, platformCallId). Two tabs syncing the same agent at the same second store each call once.
  • The route spends at most 25 seconds answering, then hands whatever is left of a long history to Next.js after() with a bigger budget and a resume cursor.

Without those four, a polling hook on the client would be a load generator. With them, the hook is mostly a trigger.

What I have not fixed

Honest list, from reading the code again for this post. None of these have shipped.

The hook ignores the response status. fetch only rejects on network failure. If the route returns 502 because Retell is down, or 400 because the key was removed, the hook treats it as a finished sync, calls onSynced, and tries again in a minute. No backoff, and nothing on screen says the numbers are no longer being refreshed. The page just quietly stops changing. I would rather show a small "last synced 14 minutes ago" line than have someone trust a frozen dashboard.

Every visible tab polls on its own. running is per hook instance. Two tabs on the same agent's analytics, both visible on two monitors, make two sync requests a minute. The server makes that safe, not free. A BroadcastChannel so one tab syncs and the others just refresh would fix it. I have not needed it badly enough yet.

The list merge only looks at the newest page. If a sync backfills calls from last month (a gap left by a broken webhook, say), they land in the database but not in a list you already scrolled, because the merge only fetches the first 50. They appear on the next full load. Rare, but it is exactly the case the backfill exists for.

A first sync can hold the request for 25 seconds. For an agent with no watermark, the opening sync reads Retell history up to the route's budget before answering. The page is usable the whole time, but the "new calls appear" moment can lag on a freshly connected agent.

What I would tell myself before writing it

Polling from the browser is a reasonable choice when the server work is idempotent and incremental. Most of my effort went there, not into the hook, and that was the right split.

The hook itself needed exactly one more distinction than I gave it: who asked for this sync? The page opening, the user coming back, or a timer. Each one deserves its own guard, and collapsing them into a single visibilityState check cost me a release.

If you build portals for voice agents, this is part of what goes into VoiceDash. And if you have solved the "one tab syncs, the rest listen" problem in production, I would like to know whether BroadcastChannel held up or whether you ended up with locks in localStorage.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.