Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(calls): stop stale call state from auto-initiating a call on wake (#6018)

Peter Chinman7d160911de68
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index 198cb6c6b3..56e173cdb5 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -384,13 +384,16 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
callCtx.syncCallPageTab(channelId, false);
});
- // Once the call actually mounts for this channel, replace the URL so a
- // reload doesn't re-trigger auto-join after the user has left. Waiting for
- // the call to mount (instead of running on adapter mount) preserves the
- // deep link if the join fails so the user can retry by refreshing.
+ // Once the auto-join attempt settles — joined, failed, or calls disabled —
+ // replace the URL so the deep link cannot fire a second time. This used to
+ // wait for the call to mount, which left `join_call=true` in the URL forever
+ // when the join failed; any later reload (the browser discarding this tab
+ // overnight and restoring it on wake, say) then re-ran the join — and since
+ // the join API is a get-or-create, that starts a brand-new call in the
+ // channel. Retrying a failed join is the Call tab's "Try again", not a
+ // refresh.
createComputed(() => {
- if (!callCtx) return;
- if (!callCtx.isInCall() || callCtx.activeChannelId() !== channelId) return;
+ if (pendingJoinCall()) return;
if (searchParams[CHANNEL_URL_PARAMS.joinCall] === undefined) return;
setSearchParams(
{ [CHANNEL_URL_PARAMS.joinCall]: undefined },
diff --git a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx b/apps/web/src/features/channel/Call/CallStartedNotifier.tsx
index 3de6f70044..0475ac7317 100644
--- a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx
+++ b/apps/web/src/features/channel/Call/CallStartedNotifier.tsx
@@ -226,8 +226,8 @@ function startRingingLoop(
*
* Also resolves the ring remotely: `call_answered` (sent to just this user
* when they join the call on any device, e.g. answering on iPhone) and
- * `call_ended` both stop the ring; `call_answered` additionally closes the
- * incoming-call notification since the user is already in the call.
+ * `call_ended` both stop the ring and close the incoming-call notification —
+ * the user is already in the call, or there is no longer a call to answer.
*
* This component is the sole bridge from those one-shot websocket events to
* published call resolutions (`call-resolution.ts`) — resolution consumers
@@ -268,6 +268,11 @@ export function CallStartedNotifier() {
}
stopCallRinger(resolution.callId);
+ // Close the toast too, not just the ring. It is `requireInteraction`, so
+ // an ended call's notification otherwise sits on screen until clicked —
+ // and clicking it deep-links into a join, which for a call that is over
+ // means get-or-create starts a brand-new one in the channel.
+ closeCallNotification(resolution.callId);
setActiveCallEndedCache({
channelId: resolution.channelId,
callId: resolution.callId,
@@ -340,6 +345,13 @@ async function emitCallStartedNotification(args: {
if (notif === 'not-supported') return;
const pending = { cancelled: false };
+ // Cancel any earlier attempt for this call before taking its slot. The map
+ // holds one entry per call id, so an attempt that was replaced would never
+ // see a later `closeCallNotification` and could still register its toast
+ // once it resolved — leaving a requireInteraction notification up for a call
+ // that has already ended.
+ const superseded = pendingCallNotifications.get(callId);
+ if (superseded) superseded.cancelled = true;
pendingCallNotifications.set(callId, pending);
try {
const callerName =
diff --git a/apps/web/src/features/channel/Call/auto-rejoin.ts b/apps/web/src/features/channel/Call/auto-rejoin.ts
new file mode 100644
index 0000000000..73e4d355e0
--- /dev/null
+++ b/apps/web/src/features/channel/Call/auto-rejoin.ts
@@ -0,0 +1,107 @@
+/**
+ * Guards for the automatic rejoin that runs after LiveKit gives up on a
+ * dropped call session.
+ *
+ * The rejoin is a *recovery* path: it exists so a brief network hiccup does
+ * not dump the user out of a call they are still in. It must never be able to
+ * *start* a call, because the join API (`GET /call/{channel_id}`) is a
+ * get-or-create — rejoining a call that has since ended creates a brand-new
+ * one and rings the whole channel.
+ *
+ * That is exactly what a sleeping laptop produces. Closing the lid mid-call
+ * freezes the page: LiveKit's socket dies, the server reaps the participant
+ * and archives the call, and the pending rejoin timer sits frozen. On wake —
+ * possibly the next day — the timer fires immediately (or LiveKit reports the
+ * disconnect it could not report while suspended) and the "reconnect" starts a
+ * fresh call in the channel with no user action at all.
+ *
+ * Two checks close that hole: a wall-clock check that the rejoin is running
+ * when it was meant to, and a server check that the call being rejoined is
+ * still the live call in that channel.
+ */
+
+/** Delay between the disconnect and the rejoin attempt. */
+export const AUTO_REJOIN_DELAY_MS = 750;
+
+/**
+ * Wall-clock budget for the scheduled rejoin to actually run. A busy main
+ * thread overshoots the timer by a little; a suspended device overshoots it by
+ * minutes or hours, which is the signal that the session is long gone.
+ */
+export const AUTO_REJOIN_MAX_SCHEDULING_LAG_MS = 10_000;
+
+/** Why an auto-rejoin was refused. */
+export type AutoRejoinRefusal =
+ /** The timer fired far later than scheduled — the device was suspended. */
+ | 'device_suspended'
+ /** The hook now tracks a different channel than the one that dropped. */
+ | 'channel_changed'
+ /** No call is running in the channel any more. */
+ | 'call_ended'
+ /** A different call is running now; this session's call is over. */
+ | 'call_replaced'
+ /** The dropped call could not be identified, so no rejoin can be proven safe. */
+ | 'call_unknown'
+ /** The active-call lookup failed, so we cannot prove a call still exists. */
+ | 'lookup_failed';
+
+/** A scheduled rejoin, captured at the moment the session dropped. */
+export type AutoRejoinAttempt = {
+ channelId: string;
+ /**
+ * The call the session was in when it dropped, or null when it could not be
+ * determined. A null id refuses the rejoin: without it there is no way to
+ * tell the dropped call apart from one someone else has since started, and
+ * joining that would be as unprompted as creating one.
+ */
+ callId: string | null;
+ /**
+ * `Date.now()` when the rejoin was scheduled. Deliberately wall-clock, not
+ * `performance.now()`: the performance timeline freezes while the device
+ * sleeps, so a monotonic delta cannot reveal the suspension this exists to
+ * detect.
+ */
+ scheduledAt: number;
+};
+
+/** The channel's live call, `null` when there is none, `'unavailable'` when the lookup failed. */
+export type ActiveCallLookup = { callId: string } | null | 'unavailable';
+
+/**
+ * Checks that the rejoin is running when it was scheduled to, and still for
+ * the channel that dropped. Runs before the active-call lookup so a rejoin
+ * woken from suspension never reaches the network.
+ */
+export function checkAutoRejoinTiming(params: {
+ attempt: AutoRejoinAttempt;
+ now: number;
+ currentChannelId: string;
+}): AutoRejoinRefusal | null {
+ const elapsed = params.now - params.attempt.scheduledAt;
+ // A backwards clock jump is as untrustworthy as an overshoot.
+ if (elapsed < 0 || elapsed > AUTO_REJOIN_MAX_SCHEDULING_LAG_MS) {
+ return 'device_suspended';
+ }
+ if (params.currentChannelId !== params.attempt.channelId) {
+ return 'channel_changed';
+ }
+ return null;
+}
+
+/**
+ * Checks the dropped session's call against what the server reports is live in
+ * the channel. Anything short of "the same call is still running" refuses, so
+ * the rejoin can only ever re-enter an existing call.
+ */
+export function checkAutoRejoinTarget(params: {
+ attempt: AutoRejoinAttempt;
+ activeCall: ActiveCallLookup;
+}): AutoRejoinRefusal | null {
+ if (params.activeCall === 'unavailable') return 'lookup_failed';
+ if (params.activeCall === null) return 'call_ended';
+ if (params.attempt.callId === null) return 'call_unknown';
+ if (params.activeCall.callId !== params.attempt.callId) {
+ return 'call_replaced';
+ }
+ return null;
+}
diff --git a/apps/web/src/features/channel/Call/tests/auto-rejoin.test.ts b/apps/web/src/features/channel/Call/tests/auto-rejoin.test.ts
new file mode 100644
index 0000000000..f4e532d7dd
--- /dev/null
+++ b/apps/web/src/features/channel/Call/tests/auto-rejoin.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+import {
+ AUTO_REJOIN_MAX_SCHEDULING_LAG_MS,
+ type AutoRejoinAttempt,
+ checkAutoRejoinTarget,
+ checkAutoRejoinTiming,
+} from '../auto-rejoin';
+
+const CHANNEL_ID = 'channel-1';
+const CALL_ID = 'call-1';
+const SCHEDULED_AT = 1_700_000_000_000;
+
+function attempt(overrides?: Partial<AutoRejoinAttempt>): AutoRejoinAttempt {
+ return {
+ channelId: CHANNEL_ID,
+ callId: CALL_ID,
+ scheduledAt: SCHEDULED_AT,
+ ...overrides,
+ };
+}
+
+describe('auto-rejoin timing', () => {
+ it('allows a rejoin that runs when it was scheduled to', () => {
+ expect(
+ checkAutoRejoinTiming({
+ attempt: attempt(),
+ now: SCHEDULED_AT + 750,
+ currentChannelId: CHANNEL_ID,
+ })
+ ).toBeNull();
+ });
+
+ it('refuses a rejoin whose timer was frozen by a sleeping device', () => {
+ // The lid closes mid-call; the timer thaws the next morning.
+ expect(
+ checkAutoRejoinTiming({
+ attempt: attempt(),
+ now: SCHEDULED_AT + 14 * 60 * 60 * 1000,
+ currentChannelId: CHANNEL_ID,
+ })
+ ).toBe('device_suspended');
+ });
+
+ it('refuses a rejoin just past the scheduling budget', () => {
+ expect(
+ checkAutoRejoinTiming({
+ attempt: attempt(),
+ now: SCHEDULED_AT + AUTO_REJOIN_MAX_SCHEDULING_LAG_MS + 1,
+ currentChannelId: CHANNEL_ID,
+ })
+ ).toBe('device_suspended');
+ });
+
+ it('refuses a rejoin when the clock jumped backwards', () => {
+ expect(
+ checkAutoRejoinTiming({
+ attempt: attempt(),
+ now: SCHEDULED_AT - 1,
+ currentChannelId: CHANNEL_ID,
+ })
+ ).toBe('device_suspended');
+ });
+
+ it('refuses a rejoin once the hook tracks another channel', () => {
+ expect(
+ checkAutoRejoinTiming({
+ attempt: attempt(),
+ now: SCHEDULED_AT + 750,
+ currentChannelId: 'channel-2',
+ })
+ ).toBe('channel_changed');
+ });
+});
+
+describe('auto-rejoin target', () => {
+ it('allows a rejoin into the same still-running call', () => {
+ expect(
+ checkAutoRejoinTarget({
+ attempt: attempt(),
+ activeCall: { callId: CALL_ID },
+ })
+ ).toBeNull();
+ });
+
+ it('refuses to re-create a call that has already ended', () => {
+ expect(
+ checkAutoRejoinTarget({ attempt: attempt(), activeCall: null })
+ ).toBe('call_ended');
+ });
+
+ it('refuses to join a different call that started in the meantime', () => {
+ expect(
+ checkAutoRejoinTarget({
+ attempt: attempt(),
+ activeCall: { callId: 'call-2' },
+ })
+ ).toBe('call_replaced');
+ });
+
+ it('refuses when the active-call lookup failed', () => {
+ expect(
+ checkAutoRejoinTarget({ attempt: attempt(), activeCall: 'unavailable' })
+ ).toBe('lookup_failed');
+ });
+
+ it('refuses when the dropped call id is unknown, even with a live call', () => {
+ expect(
+ checkAutoRejoinTarget({
+ attempt: attempt({ callId: null }),
+ activeCall: { callId: 'call-2' },
+ })
+ ).toBe('call_unknown');
+ });
+
+ it('refuses with an unknown call id when nothing is live', () => {
+ expect(
+ checkAutoRejoinTarget({
+ attempt: attempt({ callId: null }),
+ activeCall: null,
+ })
+ ).toBe('call_ended');
+ });
+});
diff --git a/apps/web/src/features/channel/Call/use-call.ts b/apps/web/src/features/channel/Call/use-call.ts
index 11eadd9117..2d265b6720 100644
--- a/apps/web/src/features/channel/Call/use-call.ts
+++ b/apps/web/src/features/channel/Call/use-call.ts
@@ -10,6 +10,14 @@ import { callServiceClient } from '@service-call/client';
import { useMutation } from '@tanstack/solid-query';
import type { DisconnectReason } from 'livekit-client';
import { createEffect, createSignal, onCleanup } from 'solid-js';
+import {
+ type ActiveCallLookup,
+ AUTO_REJOIN_DELAY_MS,
+ type AutoRejoinAttempt,
+ type AutoRejoinRefusal,
+ checkAutoRejoinTarget,
+ checkAutoRejoinTiming,
+} from './auto-rejoin';
import { useCallContext } from './CallContext';
import { publishCallResolution } from './call-resolution';
import { LK_DISCONNECT_REASON, LK_ROOM_EVENT } from './livekit-loader';
@@ -27,7 +35,6 @@ type JoinCallContext = {
};
const JOIN_TIMEOUT_MS = 15_000;
-const AUTO_REJOIN_DELAY_MS = 750;
const MAX_AUTO_REJOIN_ATTEMPTS = 1;
type ActiveJoinAttempt = {
@@ -90,6 +97,10 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
let cleanupDisconnectListener: (() => void) | null = null;
let autoRejoinAttempts = 0;
let autoRejoinTimer: ReturnType<typeof globalThis.setTimeout> | null = null;
+ // Captured when the listener is attached, because LiveKit's own Disconnected
+ // handler resets the store before ours runs. An auto-rejoin needs it to tell
+ // "the call I dropped out of" from "whatever call is in this channel now".
+ let listeningCallId: string | null = null;
function clearAutoRejoinTimer() {
if (!autoRejoinTimer) return;
@@ -97,6 +108,74 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
autoRejoinTimer = null;
}
+ /** The channel's live call; `'unavailable'` when the lookup itself failed. */
+ async function lookupActiveCall(id: string): Promise<ActiveCallLookup> {
+ try {
+ const active = await throwOnErr(() =>
+ callServiceClient.checkActiveCall(id)
+ );
+ return active ? { callId: active.callId } : null;
+ } catch (e) {
+ console.error('auto-rejoin active-call lookup failed', e);
+ return 'unavailable';
+ }
+ }
+
+ /**
+ * Give up on reconnecting: drop the "Reconnecting…" banner and let the UI
+ * fall back to the pre-call surface, the same way it does when a call ends
+ * on its own. No server-side leave is issued — the session dropped because
+ * the transport died, so the RTC provider has already reaped this
+ * participant and the `participant_left` webhook cleaned up after it.
+ */
+ function abandonAutoRejoin(
+ attempt: AutoRejoinAttempt,
+ refusal: AutoRejoinRefusal
+ ) {
+ console.info('[call] skipping auto-rejoin', {
+ refusal,
+ channelId: attempt.channelId,
+ callId: attempt.callId,
+ });
+ callCtx.setJoinError(null);
+ options?.onLeave?.();
+ }
+
+ async function runAutoRejoin(attempt: AutoRejoinAttempt) {
+ if (isLeaveInFlight()) return;
+
+ const timingRefusal = checkAutoRejoinTiming({
+ attempt,
+ now: Date.now(),
+ currentChannelId: channelId(),
+ });
+ if (timingRefusal) {
+ abandonAutoRejoin(attempt, timingRefusal);
+ return;
+ }
+
+ // The join API is a get-or-create, so rejoining a call that has ended
+ // silently starts a new one and rings the channel. Confirm the call is
+ // still live first: recovery may re-enter a call, never open one.
+ const activeCall = await lookupActiveCall(attempt.channelId);
+
+ // `joinCall` reads the channel accessor, which can have moved on while the
+ // lookup was in flight (the split navigated). Joining now would drop the
+ // user into whichever channel they went to instead.
+ if (channelId() !== attempt.channelId) {
+ abandonAutoRejoin(attempt, 'channel_changed');
+ return;
+ }
+
+ const targetRefusal = checkAutoRejoinTarget({ attempt, activeCall });
+ if (targetRefusal) {
+ abandonAutoRejoin(attempt, targetRefusal);
+ return;
+ }
+
+ await joinCall().catch((e) => console.error('auto-rejoin call failed', e));
+ }
+
function scheduleAutoRejoin(reason?: DisconnectReason) {
if (isLeaveInFlight()) return;
@@ -112,9 +191,14 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
autoRejoinAttempts += 1;
callCtx.setJoinError('Call disconnected. Reconnecting…');
+ const attempt: AutoRejoinAttempt = {
+ channelId: channelId(),
+ callId: listeningCallId,
+ scheduledAt: Date.now(),
+ };
autoRejoinTimer = globalThis.setTimeout(() => {
autoRejoinTimer = null;
- joinCall().catch((e) => console.error('auto-rejoin call failed', e));
+ void runAutoRejoin(attempt);
}, AUTO_REJOIN_DELAY_MS);
}
@@ -125,6 +209,8 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
const room = callCtx.room();
if (!room) return;
+ listeningCallId = callCtx.activeCallId();
+
const handleDisconnect = (reason?: DisconnectReason) => {
// This listener is detached before explicit leave, so reaching this path
// means LiveKit gave up on recovery. Try one hard rejoin with a fresh