Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
refactor(calls): share join leave and recovery lifecycle (#6667)
teo2c15517367af
diff --git a/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsx b/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsxindex e2a6df223d..a043ccf8f5 100644--- a/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsx+++ b/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsx@@ -56,6 +56,14 @@ export function CallRecordingSplitHeader(props: {const callName = () => record().customName ?? record().channelName ?? 'Call';const call = useCall(() => record().channelId);+ async function handleJoin() {+ try {+ await call.joinCall();+ } catch (error) {+ console.error('Failed to join call from recording', error);+ }+ }+const shareTool: BlockTool = {label: 'Share',icon: IconShared,@@ -144,7 +152,7 @@ export function CallRecordingSplitHeader(props: {size="icon-xs"class="bg-surface"tooltip="Call Again"- onClick={() => call.joinCall()}+ onClick={handleJoin}><PhoneCallIcon class="size-4" /></Button>diff --git a/apps/web/src/features/channel/Call/CallContext.tsx b/apps/web/src/features/channel/Call/CallContext.tsxindex 6f3e96d008..a4235ffc9b 100644--- a/apps/web/src/features/channel/Call/CallContext.tsx+++ b/apps/web/src/features/channel/Call/CallContext.tsx@@ -1,7 +1,14 @@import { analytics } from '@app/lib/analytics';+import { useChannelsContext } from '@core/context/channels';+import { useUserId } from '@core/context/user';import type { KrispNoiseFilter } from '@livekit/krisp-noise-filter';import type { BackgroundProcessorWrapper } from '@livekit/track-processors';-import type { CallTokenResponse } from '@service-call/client';+import {+ fetchActiveCall,+ invalidateActiveCallQueries,+ requestCallToken,+ useLeaveCallMutation,+} from '@queries/call/call';import { makePersisted } from '@solid-primitives/storage';import type {AudioCaptureOptions,@@ -20,25 +27,29 @@ import {} from 'solid-js';import { createStore } from 'solid-js/store';import { CallAudioSink } from './CallAudioSink';-import {- type CallSessionConnectMetadata,- type CallSessionDisconnectOptions,- createCallSessionController,-} from './CallSessionController';+import { createCallSessionController } from './CallSessionController';+import { createCallLifecycle } from './call-lifecycle';+import { publishCallResolution } from './call-resolution';import { createLatestAsyncRequestQueue } from './latest-async-request-queue';import {getKrisp,getLivekit,isKrispSupported,LK_CONNECTION_STATE,+ LK_ROOM_EVENT,LK_TRACK_SOURCE,loadKrisp,loadLivekit,} from './livekit-loader';+import { bindNativeCallLifecycle } from './native-call-lifecycle';import {type NativeCallConnectionState,useMaybeNativeCallState,} from './native-call-state';+import {+ isNativeIosCallKitEnabled,+ registerCallKitCallEndedHandler,+} from './use-callkit';type LivekitJsCallController = ReturnType<typeof import('./LivekitJsCallController')['createLivekitJsCallController']@@ -342,6 +353,8 @@ const [persistedNoiseSuppressionMode, setPersistedNoiseSuppressionMode] =});export type CallState = {+ /** Shared join, leave, and recovery lifecycle, with a reactive snapshot. */+ callLifecycle: ReturnType<typeof createCallLifecycle>;/** The LiveKit Room instance, null when not in a call */room: () => Room | null;/** Current connection state */@@ -378,15 +391,6 @@ export type CallState = {activeAudioOutputDeviceId: () => string | null;/** Currently active video input device ID */activeVideoInputDeviceId: () => string | null;- /** Whether joining this channel needs a fresh call token */- shouldRequestSessionToken: (channelId: string) => boolean;- /** Connect the active call session using the right platform controller */- connectSession: (- tokenResponse: CallTokenResponse,- metadata?: CallSessionConnectMetadata- ) => Promise<void>;- /** Disconnect the active call session using the right platform controller */- disconnectSession: (options?: CallSessionDisconnectOptions) => Promise<void>;/** Toggle local audio */toggleAudio: () => Promise<void>;/** Toggle local video */@@ -405,16 +409,10 @@ export type CallState = {isNoiseSuppressed: () => boolean;/** Toggle mic noise suppression on/off */toggleNoiseSuppression: () => Promise<void>;- /** Begin an optimistic join to a channel */- beginOptimisticJoin: (channelId: string) => void;- /** Rollback an optimistic join to a channel */- rollbackOptimisticJoin: () => void;/** Whether we're in the optimistic join window */isConnecting: () => boolean;/** Error message from a failed join attempt */joinError: () => string | null;- /** Set the join error message */- setJoinError: (error: string | null) => void;/*** Which channel has the Call tab focused in a channel split. `null` when no* channel block reports the Call tab.@@ -457,6 +455,9 @@ export function useCallContextOptional(): CallState | undefined {* and all readonly call state. Returns reactive state + mutation actions.*/function createCallState() {+ const channels = useChannelsContext();+ const userId = useUserId();+ const leaveMutation = useLeaveCallMutation();const nativeCall = useMaybeNativeCallState();const [room, setRoom] = createSignal<Room | null>(null);const [store, setStore] = createStore<CallStoreState>({@@ -1107,9 +1108,6 @@ function createCallState() {currentConnectionState() === LK_CONNECTION_STATE.Reconnecting ||currentConnectionState() === LK_CONNECTION_STATE.SignalReconnecting;- const currentJoinError = () =>- currentNativeCallSnapshot() ? null : store.joinError;-// --- mutations ---async function finishLocalMediaSetup(targetRoom: Room, setupVersion: number) {@@ -1227,7 +1225,7 @@ function createCallState() {},jsDisconnect: async () => {// Cancel a connect that is still waiting on its dynamic import. This is- // also reached by timeout/error recovery in useCall.+ // also reached by timeout/error recovery in the call lifecycle.browserConnectGeneration += 1;if (!livekitJsPromise) return;const controller = await getLivekitJsController();@@ -1359,7 +1357,7 @@ function createCallState() {function beginOptimisticJoin(channelId: string) {// Do not clear joinError here — retries should keep the error panel visible- // with `isJoining` until LiveKit connects (see useCall join mutation).+ // with `isJoining` until LiveKit connects.setStore('optimisticJoinChannelId', channelId);}@@ -1400,6 +1398,70 @@ function createCallState() {}}+ const lifecycle = createCallLifecycle({+ shouldRequestToken: callSession.shouldRequestToken,+ requestToken: requestCallToken,+ connect: (token) =>+ callSession.connectWithToken(token, {+ channelTitle: channels.channelsById()[token.channelId]?.name ?? null,+ }),+ disconnect: callSession.disconnect,+ leave: (id) => leaveMutation.mutateAsync(id),+ lookup: fetchActiveCall,+ currentCall: () => {+ const channelId = currentActiveChannelId();+ return channelId+ ? { channelId, callId: currentActiveCallId() }+ : undefined;+ },+ beginJoin: beginOptimisticJoin,+ rollbackJoin: rollbackOptimisticJoin,+ setError: setJoinError,+ watch: (_call, disconnected, nativeEnded) => {+ // Capture the room: its own disconnect handler resets the store first.+ const currentRoom = room();+ currentRoom?.on(LK_ROOM_EVENT.Disconnected, disconnected);+ const unregister = registerCallKitCallEndedHandler(nativeEnded);+ return () => {+ currentRoom?.off(LK_ROOM_EVENT.Disconnected, disconnected);+ unregister();+ };+ },+ onJoined: (call) => {+ const answeringUserId = userId();+ if (answeringUserId && call.callId) {+ publishCallResolution({+ type: 'answered',+ callId: call.callId,+ answeredBy: answeringUserId,+ });+ }+ void invalidateActiveCallQueries();+ analytics.track('call_action', {+ action: 'joined',+ channelId: call.channelId,+ });+ },+ onLeft: (channelId) =>+ analytics.track('call_action', {+ action: 'left',+ channelId,+ leaveReason: 'user_initiated',+ }),+ reportError: (error) => console.error('call lifecycle failed', error),+ });+ const [lifecycleSnapshot, setLifecycleSnapshot] = createSignal(+ lifecycle.getState()+ );+ const unsubscribeLifecycle = lifecycle.subscribe((state) =>+ setLifecycleSnapshot(state)+ );++ const unsubscribeNative =+ isNativeIosCallKitEnabled() && nativeCall+ ? bindNativeCallLifecycle(nativeCall, lifecycle)+ : undefined;+// --- cleanup ---const handleBeforeUnload = () => {@@ -1408,6 +1470,9 @@ function createCallState() {window.addEventListener('beforeunload', handleBeforeUnload);onCleanup(() => {+ unsubscribeNative?.();+ unsubscribeLifecycle();+ lifecycle.dispose();disposed = true;browserConnectGeneration += 1;window.removeEventListener('beforeunload', handleBeforeUnload);@@ -1421,6 +1486,13 @@ function createCallState() {// --- public API ---const state: CallState = {+ callLifecycle: {+ ...lifecycle,+ getState: () => {+ lifecycleSnapshot();+ return lifecycle.getState();+ },+ },// readonly stateroom,connectionState: currentConnectionState,@@ -1451,9 +1523,6 @@ function createCallState() {isConnecting: currentIsConnecting,// mutations- shouldRequestSessionToken: callSession.shouldRequestToken,- connectSession: callSession.connectWithToken,- disconnectSession: callSession.disconnect,toggleAudio,toggleVideo,toggleScreenShare,@@ -1464,10 +1533,7 @@ function createCallState() {isNoiseSuppressed: () =>isNoiseSuppressionEnabled(store.noiseSuppressionMode),toggleNoiseSuppression,- beginOptimisticJoin,- rollbackOptimisticJoin,- joinError: currentJoinError,- setJoinError,+ joinError: () => store.joinError,callPageChannelId: () => store.callPageChannelId,syncCallPageTab,isCallPage: () => {diff --git a/apps/web/src/features/channel/Call/CallControls/CallControlsDefaultAndPanelRow.tsx b/apps/web/src/features/channel/Call/CallControls/CallControlsDefaultAndPanelRow.tsxindex 8c1eb2c51c..824bf91a80 100644--- a/apps/web/src/features/channel/Call/CallControls/CallControlsDefaultAndPanelRow.tsx+++ b/apps/web/src/features/channel/Call/CallControls/CallControlsDefaultAndPanelRow.tsx@@ -149,6 +149,14 @@ export function CallControlsDefaultAndPanelRow(const callCtx = useCallContext();const isConnecting = () => callCtx.isConnecting();+ async function handleLeave() {+ try {+ await props.onLeave();+ } catch (error) {+ console.error('Failed to leave call', error);+ }+ }+return (<div class="inline-flex items-center overflow-hidden rounded-lg border border-ink-muted/[0.08] bg-ink-muted/[0.025] divide-x divide-ink-muted/[0.08]"><Cell>@@ -269,7 +277,7 @@ export function CallControlsDefaultAndPanelRow(<Buttonsize="icon-sm"class="text-failure not-disabled:hover:text-failure not-disabled:hover:bg-failure/10"- onClick={() => void props.onLeave()}+ onClick={handleLeave}disabled={isConnecting()}aria-label="Leave call">diff --git a/apps/web/src/features/channel/Call/ChannelCallTab.tsx b/apps/web/src/features/channel/Call/ChannelCallTab.tsxindex 88e464ae04..208f64b0b7 100644--- a/apps/web/src/features/channel/Call/ChannelCallTab.tsx+++ b/apps/web/src/features/channel/Call/ChannelCallTab.tsx@@ -108,13 +108,13 @@ export function ChannelCallTab(props: {onLeave: () => setActiveTab(getCallLeaveTab()),});- const handleRetry = async () => {+ async function handleJoin() {try {await call.joinCall();- } catch {- // joinError is set inside useCall join mutation onError+ } catch (error) {+ console.error('Failed to join call', error);}- };+ }return (<Switch@@ -122,7 +122,7 @@ export function ChannelCallTab(props: {<JoinCallEmptyStatechannelId={props.channelId}isJoining={call.isJoining()}- onJoin={() => void call.joinCall()}+ onJoin={handleJoin}/>}>@@ -139,7 +139,7 @@ export function ChannelCallTab(props: {</Show><buttontype="button"- onClick={handleRetry}+ onClick={handleJoin}disabled={call.isJoining()}class="rounded-lg bg-surface-2 px-4 py-2 text-sm text-ink hover:bg-surface-3 transition-colors disabled:opacity-50 disabled:pointer-events-none">diff --git a/apps/web/src/features/channel/Call/InCallPanel/InCallPanelView.tsx b/apps/web/src/features/channel/Call/InCallPanel/InCallPanelView.tsxindex fbd81678d8..ecf4d5b191 100644--- a/apps/web/src/features/channel/Call/InCallPanel/InCallPanelView.tsx+++ b/apps/web/src/features/channel/Call/InCallPanel/InCallPanelView.tsx@@ -47,6 +47,14 @@ export const InCallPanel: Component<InCallPanelProps> = (props) => {onLeaveCall: props.onLeaveCall,onJoinCall: props.onJoinCall,});++ async function handleLeave() {+ try {+ await panel.controls.leaveCall();+ } catch (error) {+ console.error('Failed to leave call from panel', error);+ }+ }const channelsCtx = useChannelsContext();const [nowMs, setNowMs] = createSignal(Date.now());const durationTimer = globalThis.setInterval(@@ -252,7 +260,7 @@ export const InCallPanel: Component<InCallPanelProps> = (props) => {<CallControlsvariant={controlsVariant()}when={props.showCallControls}- onLeave={() => panel.controls.leaveCall()}+ onLeave={handleLeave}/></div>@@ -260,7 +268,7 @@ export const InCallPanel: Component<InCallPanelProps> = (props) => {<div class="flex items-center justify-center px-1 py-1"><buttonclass="flex items-center justify-center size-5 shrink-0 rounded-md transition-colors text-failure hover:bg-failure/10"- onClick={() => void panel.controls.leaveCall()}+ onClick={handleLeave}aria-label="Leave call"type="button">diff --git a/apps/web/src/features/channel/Call/auto-rejoin.ts b/apps/web/src/features/channel/Call/auto-rejoin.tsindex 73e4d355e0..dd3cf9a6be 100644--- a/apps/web/src/features/channel/Call/auto-rejoin.ts+++ b/apps/web/src/features/channel/Call/auto-rejoin.ts@@ -100,7 +100,11 @@ export function checkAutoRejoinTarget(params: {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) {+ // Native UUID.uuidString is uppercase; the server serializes lowercase UUIDs.+ if (+ params.activeCall.callId.toLowerCase() !==+ params.attempt.callId.toLowerCase()+ ) {return 'call_replaced';}return null;diff --git a/apps/web/src/features/channel/Call/call-lifecycle.ts b/apps/web/src/features/channel/Call/call-lifecycle.tsnew file mode 100644index 0000000000..ee7900f0cf--- /dev/null+++ b/apps/web/src/features/channel/Call/call-lifecycle.ts@@ -0,0 +1,627 @@+import { thrownResultErrorHasCode } from '@core/util/result';+import {+ type Cleanup,+ createMachine,+ type MachineDef,+} from '@macro-inc/machine';+import type { CallTokenResponse } from '@service-call/client';+import type { DisconnectReason } from 'livekit-client';+import { match } from 'ts-pattern';+import {+ type ActiveCallLookup,+ AUTO_REJOIN_DELAY_MS,+ type AutoRejoinAttempt,+ checkAutoRejoinTarget,+ checkAutoRejoinTiming,+} from './auto-rejoin';+import type { CallSessionDisconnectOptions } from './CallSessionController';+import { LK_DISCONNECT_REASON } from './livekit-loader';++export const JOIN_TIMEOUT_MS = 15_000;+export const LEAVE_TIMEOUT_MS = 10_000;+const ALREADY_IN_CALL_MESSAGE =+ "You're already in another call. Leave your current call before joining a new one.";+export type CallIdentity = { channelId: string; callId: string | null };++function sameCall(first: CallIdentity | undefined, second: CallIdentity) {+ return (+ first?.channelId === second.channelId &&+ first.callId?.toLowerCase() === second.callId?.toLowerCase()+ );+}++function deferred() {+ let resolve!: () => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<void>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+type Join = ReturnType<typeof deferred> & {+ channelId: string;+ onJoin?: () => void;+ restoredCall?: CallIdentity;+};+type Leave = ReturnType<typeof deferred> & {+ channelId: string;+ startedAt: number;+ options?: CallSessionDisconnectOptions;+ skipServerLeave?: boolean;+};+export type CallLifecycleState =+ | { t: 'idle' }+ | { t: 'joining'; request: Join }+ | { t: 'active'; call: CallIdentity }+ | { t: 'retry-wait'; attempt: AutoRejoinAttempt }+ | { t: 'checking'; attempt: AutoRejoinAttempt }+ | { t: 'leaving'; request: Leave }+ | { t: 'failed'; channelId: string; error: unknown };+type Event =+ | { t: 'join'; request: Join }+ | { t: 'leave'; request: Leave }+ | { t: 'connected' | 'adopt'; call: CallIdentity }+ | { t: 'disconnected'; retry: boolean; at: number }+ | { t: 'fail'; error: unknown }+ | { t: 'retry' | 'finish' };++const definition: MachineDef<CallLifecycleState, Event> = {+ idle: { on: (_state, event) => changeIntent(event) },+ joining: {+ on: (state, event) =>+ match(event)+ .with({ t: 'connected' }, ({ call }) => ({+ state: { t: 'active', call } as const,+ }))+ .with({ t: 'fail' }, ({ error }) => ({+ state: {+ t: 'failed',+ channelId: state.request.channelId,+ error,+ } as const,+ }))+ .with({ t: 'leave' }, ({ request }) => ({+ state: { t: 'leaving', request } as const,+ }))+ .otherwise(() => undefined),+ },+ active: {+ on: (state, event) =>+ match(event)+ .with({ t: 'disconnected' }, ({ retry, at }) => ({+ state: retry+ ? ({+ t: 'retry-wait',+ attempt: { ...state.call, scheduledAt: at },+ } as const)+ : ({ t: 'idle' } as const),+ }))+ .with({ t: 'adopt' }, ({ call }) =>+ sameCall(state.call, call)+ ? undefined+ : { state: { t: 'active', call } as const }+ )+ .otherwise(() => changeIntent(event)),+ },+ 'retry-wait': {+ on: (state, event) =>+ event.t === 'retry'+ ? { state: { t: 'checking', attempt: state.attempt } }+ : changeIntent(event),+ },+ checking: { on: (_state, event) => changeIntent(event) },+ leaving: {+ on: (state, event) =>+ match(event)+ .with({ t: 'finish' }, changeIntent)+ .with({ t: 'adopt' }, ({ call }) =>+ state.request.options?.endNativeCall === false &&+ state.request.channelId === call.channelId+ ? changeIntent(event)+ : undefined+ )+ .with({ t: 'join' }, ({ request }) =>+ state.request.options?.endNativeCall === false &&+ state.request.channelId === request.channelId+ ? changeIntent(event)+ : undefined+ )+ .otherwise(() => undefined),+ },+ failed: { on: (_state, event) => changeIntent(event) },+};++function changeIntent(event: Event) {+ return match(event)+ .with({ t: 'join' }, ({ request }) => ({+ state: { t: 'joining', request } as const,+ }))+ .with({ t: 'leave' }, ({ request }) => ({+ state: { t: 'leaving', request } as const,+ }))+ .with({ t: 'adopt' }, ({ call }) => ({+ state: { t: 'active', call } as const,+ }))+ .with({ t: 'finish' }, () => ({ state: { t: 'idle' } as const }))+ .otherwise(() => undefined);+}++function shouldRejoin(reason?: DisconnectReason) {+ return match(reason)+ .with(+ LK_DISCONNECT_REASON.CLIENT_INITIATED,+ LK_DISCONNECT_REASON.DUPLICATE_IDENTITY,+ LK_DISCONNECT_REASON.PARTICIPANT_REMOVED,+ LK_DISCONNECT_REASON.ROOM_DELETED,+ LK_DISCONNECT_REASON.ROOM_CLOSED,+ () => false+ )+ .otherwise(() => true);+}++/** One coordinator per call provider; views only submit intent and observe it. */+export function createCallLifecycle(options: {+ shouldRequestToken: (channelId: string) => boolean;+ requestToken: (channelId: string) => Promise<CallTokenResponse>;+ connect: (token: CallTokenResponse) => Promise<void>;+ disconnect: (options?: CallSessionDisconnectOptions) => Promise<void>;+ leave: (channelId: string) => Promise<unknown>;+ lookup: (channelId: string) => Promise<ActiveCallLookup>;+ currentCall: () => CallIdentity | undefined;+ beginJoin: (channelId: string) => void;+ rollbackJoin: () => void;+ setError: (error: string | null) => void;+ watch: (+ call: CallIdentity,+ disconnected: (reason?: DisconnectReason) => void,+ nativeEnded: () => void+ ) => Cleanup;+ onJoined: (call: CallIdentity) => void;+ onLeft: (channelId: string) => void;+ reportError: (error: unknown) => void;+}) {+ let disposed = false;+ const pendingServerLeaves = new Set<Promise<unknown>>();+ async function leaveServer(channelId: string) {+ const pending = options.leave(channelId);+ pendingServerLeaves.add(pending);+ try {+ await pending;+ } finally {+ pendingServerLeaves.delete(pending);+ }+ }+ const leaveListeners = new Set<(channelId: string) => void>();+ const notifyLeft = (channelId: string) => {+ for (const listener of [...leaveListeners]) {+ try {+ listener(channelId);+ } catch (error) {+ options.reportError(error);+ }+ }+ };+ const machine = createMachine<CallLifecycleState, Event>({+ initial: { t: 'idle' },+ def: definition,+ scopes: {+ idle: () => {+ options.rollbackJoin();+ options.setError(null);+ },+ joining: ({ request }, dispatch) => {+ let active = true;+ let settled = false;+ const fail = (error: unknown) => {+ if (!active) return;+ settled = true;+ request.reject(error);+ dispatch({ t: 'fail', error });+ };+ const timeout = setTimeout(+ () => fail(new Error('Connection timed out')),+ JOIN_TIMEOUT_MS+ );+ let finishDelay!: () => void;+ const delay = new Promise<void>((resolve) => {+ finishDelay = resolve;+ });+ const delayTimer = setTimeout(finishDelay, 300);+ options.beginJoin(request.channelId);+ async function connect() {+ try {+ request.onJoin?.();+ // A sent leave cannot be cancelled. Register the retry only after+ // it settles, so the old request cannot remove the new membership.+ const renewMembership = pendingServerLeaves.size > 0;+ if (renewMembership) {+ await Promise.allSettled(pendingServerLeaves);+ if (!active) return;+ }+ if (request.restoredCall) {+ let activeCall: ActiveCallLookup;+ try {+ activeCall = await options.lookup(request.channelId);+ } catch (error) {+ if (!active) return;+ options.reportError(error);+ activeCall = 'unavailable';+ }+ if (!active) return;+ if (+ checkAutoRejoinTarget({+ attempt: { ...request.restoredCall, scheduledAt: Date.now() },+ activeCall,+ })+ ) {+ await releaseStaleNativeSession(request.restoredCall, true);+ return;+ }+ }+ let call = options.currentCall();+ const needsConnection = options.shouldRequestToken(+ request.channelId+ );+ if (needsConnection || renewMembership) {+ const [token] = await Promise.all([+ options.requestToken(request.channelId),+ delay,+ ]);+ if (!active) return;+ if (!needsConnection && call && !sameCall(call, token)) {+ // The server ended the session native still reports. Release+ // the newly issued membership and the stale native session.+ await releaseStaleNativeSession(call);+ return;+ }+ if (needsConnection) await options.connect(token);+ call = { channelId: token.channelId, callId: token.callId };+ } else {+ // Let the joining scope finish mounting before dispatching its+ // completion, just as the token/connect path does.+ await Promise.resolve();+ }+ if (!active) return;+ options.rollbackJoin();+ options.setError(null);+ settled = true;+ request.resolve();+ const connected = call ?? {+ channelId: request.channelId,+ callId: null,+ };+ dispatch({ t: 'connected', call: connected });+ try {+ const current = machine.getState();+ if (current.t === 'active' && sameCall(current.call, connected))+ options.onJoined(connected);+ } catch (error) {+ options.reportError(error);+ }+ } catch (error) {+ fail(error);+ }+ }+ void connect();+ return () => {+ active = false;+ clearTimeout(timeout);+ clearTimeout(delayTimer);+ finishDelay();+ if (!settled) request.reject(new Error('Call join cancelled'));+ };+ },+ active: ({ call }, dispatch) => {+ options.setError(null);+ let active = true;+ const unwatch = options.watch(+ call,+ (reason) => {+ if (!active) return;+ const retry = shouldRejoin(reason);+ dispatch({ t: 'disconnected', retry, at: Date.now() });+ if (!retry) notifyLeft(call.channelId);+ },+ () => {+ if (active) void leaveEndedNativeSession(call.channelId);+ }+ );+ return () => {+ active = false;+ unwatch();+ };+ },+ 'retry-wait': ({ attempt }, dispatch) => {+ options.setError('Call disconnected. Reconnecting…');+ const timer = setTimeout(() => {+ // The session owns this channel even if the initiating view navigates.+ // A new join or leave exits the scope and cancels the recovery.+ const refusal = checkAutoRejoinTiming({+ attempt,+ now: Date.now(),+ currentChannelId: attempt.channelId,+ });+ if (refusal) {+ options.setError(null);+ dispatch({ t: 'finish' });+ notifyLeft(attempt.channelId);+ } else dispatch({ t: 'retry' });+ }, AUTO_REJOIN_DELAY_MS);+ return () => clearTimeout(timer);+ },+ checking: ({ attempt }, dispatch) => {+ let active = true;+ async function recover() {+ let activeCall: ActiveCallLookup;+ try {+ activeCall = await options.lookup(attempt.channelId);+ } catch (error) {+ if (!active) return;+ options.reportError(error);+ activeCall = 'unavailable';+ }+ if (!active) return;+ if (+ checkAutoRejoinTiming({+ attempt,+ now: Date.now(),+ currentChannelId: attempt.channelId,+ }) ||+ checkAutoRejoinTarget({ attempt, activeCall })+ ) {+ options.setError(null);+ dispatch({ t: 'finish' });+ notifyLeft(attempt.channelId);+ return;+ }+ try {+ await join(attempt.channelId);+ } catch (error) {+ options.reportError(error);+ }+ }+ void recover();+ return () => {+ active = false;+ };+ },+ failed: ({ channelId, error }) => {+ options.rollbackJoin();+ options.setError(+ thrownResultErrorHasCode(error, 'CONFLICT')+ ? ALREADY_IN_CALL_MESSAGE+ : 'Unable to join the call. Please check your connection.'+ );+ let active = true;+ // Recovery must not keep Try again pending, or tear down a newer join.+ async function cleanUpFailedJoin() {+ try {+ await options.disconnect({ endNativeCall: false });+ } catch (error) {+ options.reportError(error);+ }+ if (!active) return;+ try {+ await leaveServer(channelId);+ } catch (error) {+ options.reportError(error);+ }+ }+ void cleanUpFailedJoin();+ return () => {+ active = false;+ };+ },+ leaving: ({ request }, dispatch) => {+ let active = true;+ let settled = false;+ options.rollbackJoin();+ options.setError(null);+ const finish = (error?: unknown) => {+ if (!active) return;+ settled = true;+ if (error) request.reject(error);+ else request.resolve();+ dispatch({ t: 'finish' });+ };+ const timeout = setTimeout(+ () => finish(new Error('Leaving call timed out')),+ LEAVE_TIMEOUT_MS+ );+ async function disconnect() {+ try {+ try {+ await options.disconnect(request.options);+ if (!active) return;+ notifyLeft(request.channelId);+ options.onLeft(request.channelId);+ } finally {+ if (active && !request.skipServerLeave)+ await leaveServer(request.channelId);+ }+ finish();+ } catch (error) {+ if (active) finish(error);+ else options.reportError(error);+ }+ }+ void disconnect();+ return () => {+ active = false;+ clearTimeout(timeout);+ if (!settled) {+ // Native end cleanup yields to a restored session or a new join.+ if (request.options?.endNativeCall === false) request.resolve();+ else request.reject(new Error('Call leave cancelled'));+ }+ };+ },+ },+ });++ function join(channelId: string, onJoin?: () => void): Promise<void> {+ if (disposed) return Promise.reject(new Error('Call lifecycle disposed'));+ const state = machine.getState();+ if (state.t === 'joining')+ return state.request.channelId === channelId+ ? state.request.promise+ : Promise.reject(new Error('Already joining another call'));+ if (+ state.t === 'leaving' &&+ (state.request.options?.endNativeCall !== false ||+ state.request.channelId !== channelId)+ )+ return Promise.reject(new Error('Call is still leaving'));+ if (state.t === 'active') {+ try {+ onJoin?.();+ if (state.call.channelId !== channelId) {+ options.setError(ALREADY_IN_CALL_MESSAGE);+ return Promise.reject(new Error(ALREADY_IN_CALL_MESSAGE));+ }+ options.setError(null);+ return Promise.resolve();+ } catch (error) {+ return Promise.reject(error);+ }+ }+ const request: Join = { ...deferred(), channelId, onJoin };+ machine.dispatch({ t: 'join', request });+ return request.promise;+ }++ function leave(+ channelId: string,+ leaveOptions?: CallSessionDisconnectOptions+ ): Promise<void> {+ if (disposed) return Promise.reject(new Error('Call lifecycle disposed'));+ const state = machine.getState();+ if (state.t === 'leaving') {+ // Timers can freeze in a suspended webview. A resumed tap must be able+ // to replace a stale leave even before its timeout callback runs.+ const elapsed = Date.now() - state.request.startedAt;+ if (elapsed >= 0 && elapsed < LEAVE_TIMEOUT_MS)+ return state.request.promise;+ machine.dispatch({ t: 'finish' });+ }+ return startLeave(channelId, leaveOptions);+ }++ function startLeave(+ channelId: string,+ leaveOptions?: CallSessionDisconnectOptions,+ skipServerLeave = false+ ) {+ const request: Leave = {+ ...deferred(),+ channelId,+ startedAt: Date.now(),+ options: leaveOptions,+ skipServerLeave,+ };+ machine.dispatch({ t: 'leave', request });+ return request.promise;+ }++ async function leaveEndedNativeSession(channelId: string) {+ try {+ await leave(channelId, { endNativeCall: false });+ } catch (error) {+ options.reportError(error);+ }+ }++ async function releaseStaleNativeSession(+ call: CallIdentity,+ skipServerLeave = false+ ) {+ const current = options.currentCall();+ if (current?.channelId === call.channelId && !sameCall(current, call)) {+ // Another native session now owns this channel; its membership must stay.+ machine.dispatch({ t: 'connected', call: current });+ return;+ }+ try {+ await startLeave(+ call.channelId,+ {+ endNativeCall: sameCall(current, call),+ },+ skipServerLeave+ );+ } catch (error) {+ options.reportError(error);+ }+ }++ async function restoreAfterLeave(call: CallIdentity) {+ const request: Join = {+ ...deferred(),+ channelId: call.channelId,+ restoredCall: call,+ };+ machine.dispatch({ t: 'join', request });+ try {+ await request.promise;+ } catch (error) {+ options.reportError(error);+ }+ }++ return {+ join,+ leave,+ getState: machine.getState,+ subscribe: machine.subscribe,+ syncSession: (call: CallIdentity | undefined) => {+ if (disposed) return;+ if (call) {+ const state = machine.getState();+ if (+ state.t === 'leaving' &&+ state.request.options?.endNativeCall === false &&+ state.request.channelId === call.channelId &&+ pendingServerLeaves.size > 0+ ) {+ // The native transport may already be restored, but the old DELETE+ // is still authoritative for membership until it settles.+ void restoreAfterLeave(call);+ return;+ }+ machine.dispatch({ t: 'adopt', call });+ return;+ }+ const state = machine.getState();+ if (state.t === 'joining') {+ // Requesting a token can register a server participant before media+ // connects. Clean up unless a new session supersedes this attempt.+ void leaveEndedNativeSession(state.request.channelId);+ return;+ }+ const channelId = match(state)+ .with({ t: 'active' }, ({ call }) => call.channelId)+ .with(+ { t: 'retry-wait' },+ { t: 'checking' },+ ({ attempt }) => attempt.channelId+ )+ .otherwise(() => undefined);+ if (channelId !== undefined) {+ machine.dispatch({ t: 'finish' });+ notifyLeft(channelId);+ }+ },+ onLeave: (listener: (channelId: string) => void) => {+ leaveListeners.add(listener);+ return () => {+ leaveListeners.delete(listener);+ };+ },+ dispose: () => {+ disposed = true;+ machine.dispose();+ leaveListeners.clear();+ },+ };+}diff --git a/apps/web/src/features/channel/Call/native-call-lifecycle.ts b/apps/web/src/features/channel/Call/native-call-lifecycle.tsnew file mode 100644index 0000000000..10db328c21--- /dev/null+++ b/apps/web/src/features/channel/Call/native-call-lifecycle.ts@@ -0,0 +1,50 @@+import { match, P } from 'ts-pattern';+import type { createCallLifecycle } from './call-lifecycle';+import type { NativeCallState } from './native-call-state';++/** Reconcile native events, including a call restored while an old leave settles. */+export function bindNativeCallLifecycle(+ nativeCall: Pick<NativeCallState, 'snapshot' | 'onSnapshot'>,+ lifecycle: ReturnType<typeof createCallLifecycle>+) {+ let nativeSessionObserved = false;+ const sync = () => {+ match(nativeCall.snapshot())+ .with({ connectionState: 'connected' }, (snapshot) => {+ nativeSessionObserved = true;+ lifecycle.syncSession({+ channelId: snapshot.channelId,+ callId: snapshot.callId.toLowerCase(),+ });+ })+ .with({ connectionState: P.union('connecting', 'reconnecting') }, () => {+ nativeSessionObserved = true;+ })+ .with(+ null,+ { connectionState: P.union('disconnected', 'disconnecting') },+ () => {+ // CallKit acknowledges start before media snapshots necessarily+ // arrive. An empty snapshot only ends an observed native session.+ if (nativeSessionObserved) lifecycle.syncSession(undefined);+ }+ )+ .exhaustive();+ };+ const unsubscribeState = lifecycle.subscribe((state) => {+ if (state.t === 'joining') nativeSessionObserved = false;+ if (+ state.t === 'joining' ||+ state.t === 'idle' ||+ state.t === 'failed' ||+ state.t === 'active'+ ) {+ sync();+ }+ });+ const unsubscribeSnapshot = nativeCall.onSnapshot(sync);+ return () => {+ unsubscribeSnapshot();+ unsubscribeState();+ };+}diff --git a/apps/web/src/features/channel/Call/native-call-state.ts b/apps/web/src/features/channel/Call/native-call-state.tsindex cb03b8e0b1..9cf312ed48 100644--- a/apps/web/src/features/channel/Call/native-call-state.ts+++ b/apps/web/src/features/channel/Call/native-call-state.ts@@ -3,8 +3,10 @@ import {createComponent,createContext,createSignal,+ onCleanup,type ParentProps,type Setter,+ untrack,useContext,} from 'solid-js';import {@@ -32,6 +34,10 @@ export type NativeCallSnapshot = {export type NativeCallState = {snapshot: Accessor<NativeCallSnapshot | null>;setSnapshot: Setter<NativeCallSnapshot | null>;+ /** Observe native updates directly, including the current snapshot. */+ onSnapshot: (+ listener: (snapshot: NativeCallSnapshot | null) => void+ ) => () => void;bootstrapChannelId: Accessor<string | null>;setBootstrapChannelId: Setter<string | null>;participantIdentities: Accessor<string[]>;@@ -42,8 +48,19 @@ export type NativeCallState = {const NativeCallContext = createContext<NativeCallState>();-function createNativeCallState(): NativeCallState {+export function createNativeCallState(): NativeCallState {const [snapshot, setSnapshot] = createSignal<NativeCallSnapshot | null>(null);+ const listeners = new Set<(snapshot: NativeCallSnapshot | null) => void>();+ onCleanup(() => listeners.clear());+ const updateSnapshot: NativeCallState['setSnapshot'] = (value) => {+ const next = setSnapshot(value);+ untrack(() => {+ for (const listener of [...listeners]) {+ if (listeners.has(listener)) listener(next);+ }+ });+ return next;+ };// Tracks the channel from early native CallKit events before the full native// media snapshot is available. snapshot remains authoritative once set.const [bootstrapChannelId, setBootstrapChannelId] = createSignal<@@ -56,7 +73,14 @@ function createNativeCallState(): NativeCallState {return {snapshot,- setSnapshot,+ setSnapshot: updateSnapshot,+ onSnapshot: (listener) => {+ listeners.add(listener);+ untrack(() => listener(snapshot()));+ return () => {+ listeners.delete(listener);+ };+ },bootstrapChannelId,setBootstrapChannelId,participantIdentities,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.tsindex f4e532d7dd..9b91b9ee53 100644--- a/apps/web/src/features/channel/Call/tests/auto-rejoin.test.ts+++ b/apps/web/src/features/channel/Call/tests/auto-rejoin.test.ts@@ -88,6 +88,16 @@ describe('auto-rejoin target', () => {).toBe('call_ended');});+ it('matches uppercase native UUIDs with lowercase server UUIDs', () => {+ const callId = '01991b2a-f4e0-7000-a000-111111111111';+ expect(+ checkAutoRejoinTarget({+ attempt: { ...attempt(), callId: callId.toUpperCase() },+ activeCall: { callId },+ })+ ).toBeNull();+ });+it('refuses to join a different call that started in the meantime', () => {expect(checkAutoRejoinTarget({diff --git a/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts b/apps/web/src/features/channel/Call/tests/call-lifecycle.test.tsnew file mode 100644index 0000000000..1ece7d7027--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts@@ -0,0 +1,504 @@+import { ThrownResultError } from '@core/util/result';+import type { CallTokenResponse } from '@service-call/client';+import type { DisconnectReason } from 'livekit-client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { type ActiveCallLookup, AUTO_REJOIN_DELAY_MS } from '../auto-rejoin';+import {+ createCallLifecycle,+ JOIN_TIMEOUT_MS,+ LEAVE_TIMEOUT_MS,+} from '../call-lifecycle';+import { LK_DISCONNECT_REASON } from '../livekit-loader';++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((yes) => {+ resolve = yes;+ });+ return { promise, resolve };+}++const call = { channelId: 'channel-1', callId: 'call-1' };+const token = {+ ...call,+ roomName: 'room-1',+ token: 'token',+ serverUrl: 'ws://localhost',+} satisfies CallTokenResponse;+const cleanups: (() => void)[] = [];++function setup() {+ let disconnected: (reason?: DisconnectReason) => void = () => {};+ let nativeEnded: () => void = () => {};+ const unwatch = vi.fn();+ const ports = {+ shouldRequestToken: vi.fn(() => true),+ requestToken: vi.fn(async () => token),+ connect: vi.fn(async () => {}),+ disconnect: vi.fn(async () => {}),+ leave: vi.fn(async () => {}),+ lookup: vi.fn<() => Promise<ActiveCallLookup>>(async () => ({+ callId: call.callId,+ })),+ currentCall: vi.fn(() => call),+ beginJoin: vi.fn(),+ rollbackJoin: vi.fn(),+ setError: vi.fn(),+ watch: vi.fn((_call, onDisconnect, onNativeEnd) => {+ disconnected = onDisconnect;+ nativeEnded = onNativeEnd;+ return unwatch;+ }),+ onJoined: vi.fn(),+ onLeft: vi.fn(),+ reportError: vi.fn(),+ } satisfies Parameters<typeof createCallLifecycle>[0];+ const lifecycle = createCallLifecycle(ports);+ cleanups.push(lifecycle.dispose);+ return {+ lifecycle,+ ports,+ unwatch,+ disconnect: (reason?: DisconnectReason) => disconnected(reason),+ nativeEnd: () => nativeEnded(),+ async join() {+ const promise = lifecycle.join(call.channelId);+ await vi.advanceTimersByTimeAsync(300);+ await promise;+ },+ };+}++describe('shared call lifecycle', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(1_700_000_000_000);+ });+ afterEach(() => {+ for (const cleanup of cleanups.splice(0)) cleanup();+ vi.useRealTimers();+ });++ it('shares one in-flight join across controls and rejects a competing channel', async () => {+ const { lifecycle, ports } = setup();+ const first = lifecycle.join(call.channelId);+ expect(lifecycle.join(call.channelId)).toBe(first);+ await expect(lifecycle.join('channel-2')).rejects.toThrow(+ 'Already joining'+ );+ expect(ports.requestToken).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(300);+ await first;+ expect(ports.connect).toHaveBeenCalledExactlyOnceWith(token);+ expect(lifecycle.getState()).toEqual({ t: 'active', call });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('publishes an answer only after the connection completes', async () => {+ const { lifecycle, ports } = setup();+ const connection = deferred<void>();+ ports.connect.mockReturnValueOnce(connection.promise);+ const onJoin = vi.fn();+ const promise = lifecycle.join(call.channelId, onJoin);+ expect(onJoin).toHaveBeenCalledOnce();+ await vi.advanceTimersByTimeAsync(300);+ expect(ports.onJoined).not.toHaveBeenCalled();+ connection.resolve();+ await promise;+ expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(call);+ expect(ports.watch).toHaveBeenCalledOnce();+ });++ it('keeps the existing session when selecting its call tab again', async () => {+ const { lifecycle, ports, join } = setup();+ await join();+ const selectTab = vi.fn();+ await lifecycle.join(call.channelId, selectTab);+ expect(selectTab).toHaveBeenCalledOnce();+ expect(ports.connect).toHaveBeenCalledOnce();+ expect(ports.watch).toHaveBeenCalledOnce();+ });++ it('adopts an existing native session without requesting a token', async () => {+ const { lifecycle, ports } = setup();+ ports.shouldRequestToken.mockReturnValue(false);+ await lifecycle.join(call.channelId);+ expect(ports.requestToken).not.toHaveBeenCalled();+ expect(ports.connect).not.toHaveBeenCalled();+ expect(lifecycle.getState()).toEqual({ t: 'active', call });+ expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(call);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['joined', 'adopted'] as const)(+ 'preserves the %s live call when another channel tries to join',+ async (origin) => {+ const { lifecycle, ports, join, unwatch, disconnect } = setup();+ if (origin === 'joined') await join();+ else lifecycle.syncSession(call);+ const tokenRequests = ports.requestToken.mock.calls.length;+ const onLeave = vi.fn();+ const onJoin = vi.fn();+ lifecycle.onLeave(onLeave);+ ports.requestToken.mockRejectedValueOnce(+ new ThrownResultError([+ { code: 'CONFLICT', message: 'Already in another call' },+ ])+ );+ await expect(lifecycle.join('channel-2', onJoin)).rejects.toThrow();+ await vi.advanceTimersByTimeAsync(300);+ expect(lifecycle.getState()).toEqual({ t: 'active', call });+ expect(ports.requestToken).toHaveBeenCalledTimes(tokenRequests);+ expect(ports.disconnect).not.toHaveBeenCalled();+ expect(ports.leave).not.toHaveBeenCalled();+ expect(unwatch).not.toHaveBeenCalled();+ expect(onLeave).not.toHaveBeenCalled();+ expect(onJoin).toHaveBeenCalledOnce();+ expect(ports.setError).toHaveBeenLastCalledWith(+ "You're already in another call. Leave your current call before joining a new one."+ );+ await lifecycle.join(call.channelId);+ expect(ports.setError).toHaveBeenLastCalledWith(null);+ disconnect(LK_DISCONNECT_REASON.CLIENT_INITIATED);+ expect(onLeave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ }+ );++ it('releases a timed-out join while cleanup hangs, and ignores its late token', async () => {+ const { lifecycle, ports } = setup();+ const oldToken = deferred<CallTokenResponse>();+ const cleanup = deferred<void>();+ ports.requestToken.mockReturnValueOnce(oldToken.promise);+ ports.disconnect.mockReturnValueOnce(cleanup.promise);+ const failed = expect(lifecycle.join(call.channelId)).rejects.toThrow(+ 'timed out'+ );+ await vi.advanceTimersByTimeAsync(JOIN_TIMEOUT_MS);+ await failed;+ expect(lifecycle.getState().t).toBe('failed');+ expect(ports.rollbackJoin).toHaveBeenCalled();+ const retry = lifecycle.join(call.channelId);+ await vi.advanceTimersByTimeAsync(300);+ await retry;+ oldToken.resolve(token);+ cleanup.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.connect).toHaveBeenCalledOnce();+ expect(ports.leave).not.toHaveBeenCalled();+ expect(lifecycle.getState().t).toBe('active');+ });++ it('does not publish an answer for a connection that completed after cancellation', async () => {+ const { lifecycle, ports } = setup();+ const connection = deferred<void>();+ ports.connect.mockReturnValueOnce(connection.promise);+ const cancelled = expect(lifecycle.join(call.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ await lifecycle.leave(call.channelId);+ await cancelled;+ connection.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.onJoined).not.toHaveBeenCalled();+ expect(lifecycle.getState().t).toBe('idle');+ });++ it.each([+ {+ error: new ThrownResultError([+ { code: 'CONFLICT', message: 'Already in another call' },+ ]),+ message:+ "You're already in another call. Leave your current call before joining a new one.",+ },+ {+ error: new Error('Network unavailable'),+ message: 'Unable to join the call. Please check your connection.',+ },+ ])(+ 'preserves join failures and displays $message',+ async ({ error, message }) => {+ const { lifecycle, ports } = setup();+ ports.requestToken.mockRejectedValueOnce(error);+ await expect(lifecycle.join(call.channelId)).rejects.toBe(error);+ expect(lifecycle.getState()).toEqual({+ t: 'failed',+ channelId: call.channelId,+ error,+ });+ expect(ports.setError).toHaveBeenLastCalledWith(message);+ }+ );++ it('cancels a pending join when native confirms the session ended', async () => {+ const { lifecycle, ports } = setup();+ const pending = deferred<CallTokenResponse>();+ ports.requestToken.mockReturnValueOnce(pending.promise);+ const cancelled = expect(lifecycle.join(call.channelId)).rejects.toThrow(+ 'cancelled'+ );+ lifecycle.syncSession(undefined);+ await cancelled;+ expect(lifecycle.getState().t).toBe('idle');+ expect(ports.setError).toHaveBeenLastCalledWith(null);+ pending.resolve(token);+ await vi.advanceTimersByTimeAsync(JOIN_TIMEOUT_MS);+ expect(ports.connect).not.toHaveBeenCalled();+ expect(ports.onJoined).not.toHaveBeenCalled();+ });++ it.each([0, 300])(+ 'leaves server membership when native cancels %s ms after requesting a token',+ async (elapsed) => {+ const { lifecycle, ports } = setup();+ let participantRegistered = false;+ ports.requestToken.mockImplementationOnce(async () => {+ participantRegistered = true;+ return token;+ });+ ports.leave.mockImplementationOnce(async () => {+ participantRegistered = false;+ });+ const connection = deferred<void>();+ ports.connect.mockReturnValueOnce(connection.promise);+ const cancelled = expect(lifecycle.join(call.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(elapsed);+ expect(participantRegistered).toBe(true);+ lifecycle.syncSession(undefined);+ lifecycle.syncSession(undefined);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.disconnect).toHaveBeenCalledExactlyOnceWith({+ endNativeCall: false,+ });+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ expect(participantRegistered).toBe(false);+ expect(lifecycle.getState().t).toBe('idle');+ connection.resolve();+ await vi.advanceTimersByTimeAsync(JOIN_TIMEOUT_MS);+ expect(ports.onJoined).not.toHaveBeenCalled();+ expect(ports.leave).toHaveBeenCalledOnce();+ }+ );++ it('leaves server membership even if native cancellation disconnect fails', async () => {+ const { lifecycle, ports } = setup();+ const failure = new Error('transport cleanup failed');+ ports.disconnect.mockRejectedValueOnce(failure);+ const connection = deferred<void>();+ ports.connect.mockReturnValueOnce(connection.promise);+ const cancelled = expect(lifecycle.join(call.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ lifecycle.syncSession(undefined);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ expect(ports.reportError).toHaveBeenCalledExactlyOnceWith(failure);+ expect(lifecycle.getState().t).toBe('idle');+ connection.resolve();+ });++ it('detaches the session listener before explicit leave and shares duplicate leaves', async () => {+ const { lifecycle, ports, unwatch, disconnect, join } = setup();+ await join();+ const serverLeave = deferred<void>();+ ports.leave.mockReturnValueOnce(serverLeave.promise);+ const onLeave = vi.fn();+ lifecycle.onLeave(onLeave);+ const first = lifecycle.leave(call.channelId);+ expect(lifecycle.leave(call.channelId)).toBe(first);+ expect(unwatch).toHaveBeenCalledOnce();+ disconnect(); // An emitter may already have captured its listener list.+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.lookup).not.toHaveBeenCalled();+ expect(onLeave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ serverLeave.resolve();+ await first;+ expect(ports.disconnect).toHaveBeenCalledOnce();+ expect(ports.leave).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('handles native call end through the same leave lifecycle', async () => {+ const { ports, nativeEnd, join } = setup();+ await join();+ nativeEnd();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.disconnect).toHaveBeenCalledExactlyOnceWith({+ endNativeCall: false,+ });+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ });++ it('rejoins only the same live call after a transport disconnect', async () => {+ const { lifecycle, ports, unwatch, disconnect, join } = setup();+ await join();+ disconnect();+ expect(unwatch).toHaveBeenCalledOnce();+ expect(lifecycle.getState().t).toBe('retry-wait');+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS + 300);+ expect(ports.lookup).toHaveBeenCalledExactlyOnceWith(call.channelId);+ expect(ports.connect).toHaveBeenCalledTimes(2);+ expect(lifecycle.getState()).toEqual({ t: 'active', call });+ });++ it.each([null, 'unavailable', { callId: 'replacement' }] as const)(+ 'never starts a new call when recovery lookup returns %s',+ async (result) => {+ const { lifecycle, ports, disconnect, join } = setup();+ await join();+ ports.lookup.mockResolvedValueOnce(result);+ disconnect();+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ expect(lifecycle.getState().t).toBe('idle');+ }+ );++ it.each(Object.values(LK_DISCONNECT_REASON))(+ 'does not recover intentional disconnect reason %s',+ async (reason) => {+ const { lifecycle, ports, disconnect, join } = setup();+ await join();+ const onLeave = vi.fn();+ lifecycle.onLeave(onLeave);+ disconnect(reason);+ expect(onLeave).toHaveBeenCalledOnce();+ expect(lifecycle.getState().t).toBe('idle');+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS);+ expect(ports.lookup).not.toHaveBeenCalled();+ }+ );++ it('cancels pending recovery when the user leaves during its lookup', async () => {+ const { lifecycle, ports, disconnect, join } = setup();+ await join();+ const lookup = deferred<ActiveCallLookup>();+ ports.lookup.mockReturnValueOnce(lookup.promise);+ disconnect();+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS);+ await lifecycle.leave(call.channelId);+ lookup.resolve({ callId: call.callId });+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ expect(lifecycle.getState().t).toBe('idle');+ });++ it.each(['retry-wait', 'checking'] as const)(+ 'cancels recovery when native ends during %s',+ async (phase) => {+ const { lifecycle, ports, disconnect, join } = setup();+ await join();+ const lookup = deferred<ActiveCallLookup>();+ ports.lookup.mockReturnValueOnce(lookup.promise);+ const onLeave = vi.fn();+ lifecycle.onLeave(onLeave);+ disconnect();+ if (phase === 'checking')+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS);+ expect(lifecycle.getState().t).toBe(phase);+ lifecycle.syncSession(undefined);+ lifecycle.syncSession(undefined);+ expect(lifecycle.getState().t).toBe('idle');+ expect(ports.setError).toHaveBeenLastCalledWith(null);+ expect(onLeave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ lookup.resolve({ callId: call.callId });+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS + 300);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ }+ );++ it('clears the recovery error when a live native session is adopted', async () => {+ const { lifecycle, ports, disconnect, join } = setup();+ await join();+ disconnect();+ expect(ports.setError).toHaveBeenLastCalledWith(+ 'Call disconnected. Reconnecting…'+ );+ lifecycle.syncSession(call);+ expect(lifecycle.getState()).toEqual({ t: 'active', call });+ expect(ports.setError).toHaveBeenLastCalledWith(null);+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS);+ expect(ports.lookup).not.toHaveBeenCalled();+ });++ it('refuses recovery after sleep, including a lookup frozen in flight', async () => {+ const { lifecycle, ports, disconnect, join } = setup();+ await join();+ const lookup = deferred<ActiveCallLookup>();+ ports.lookup.mockReturnValueOnce(lookup.promise);+ disconnect();+ await vi.advanceTimersByTimeAsync(AUTO_REJOIN_DELAY_MS);+ vi.setSystemTime(Date.now() + 60_000);+ lookup.resolve({ callId: call.callId });+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ expect(lifecycle.getState().t).toBe('idle');+ });++ it.each([LEAVE_TIMEOUT_MS + 1, -1])(+ 'allows a resumed leave after a wall-clock jump of %s ms',+ async (jump) => {+ const { lifecycle, ports } = setup();+ const oldDisconnect = deferred<void>();+ ports.disconnect.mockReturnValueOnce(oldDisconnect.promise);+ const oldLeave = expect(lifecycle.leave(call.channelId)).rejects.toThrow(+ 'cancelled'+ );+ vi.setSystemTime(Date.now() + jump);+ await lifecycle.leave(call.channelId);+ await oldLeave;+ oldDisconnect.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.disconnect).toHaveBeenCalledTimes(2);+ expect(ports.leave).toHaveBeenCalledOnce();+ expect(ports.onLeft).toHaveBeenCalledOnce();+ }+ );++ it('times out a hung leave and permits a new join', async () => {+ const { lifecycle, ports, join } = setup();+ ports.disconnect.mockReturnValueOnce(new Promise(() => {}));+ const failed = expect(lifecycle.leave(call.channelId)).rejects.toThrow(+ 'timed out'+ );+ await vi.advanceTimersByTimeAsync(LEAVE_TIMEOUT_MS);+ await failed;+ await join();+ expect(lifecycle.getState().t).toBe('active');+ });++ it('owns exactly one listener for an adopted session and cleans it on disposal', async () => {+ const { lifecycle, ports, unwatch, disconnect } = setup();+ lifecycle.syncSession(call);+ lifecycle.syncSession(call);+ expect(ports.watch).toHaveBeenCalledOnce();+ lifecycle.dispose();+ disconnect();+ expect(unwatch).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ await expect(lifecycle.join(call.channelId)).rejects.toThrow('disposed');+ await expect(lifecycle.leave(call.channelId)).rejects.toThrow('disposed');+ });++ it('can join again after foreground sync clears a native call that ended while suspended', async () => {+ const { lifecycle, ports, unwatch, join } = setup();+ const onLeave = vi.fn();+ lifecycle.onLeave(onLeave);+ lifecycle.syncSession(call);+ lifecycle.syncSession(undefined);+ lifecycle.syncSession(undefined);+ expect(lifecycle.getState().t).toBe('idle');+ expect(unwatch).toHaveBeenCalledOnce();+ expect(onLeave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ await join();+ expect(ports.requestToken).toHaveBeenCalledOnce();+ expect(ports.connect).toHaveBeenCalledOnce();+ expect(lifecycle.getState()).toEqual({ t: 'active', call });+ });+});diff --git a/apps/web/src/features/channel/Call/tests/native-call-lifecycle.test.ts b/apps/web/src/features/channel/Call/tests/native-call-lifecycle.test.tsnew file mode 100644index 0000000000..77459f3f45--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/native-call-lifecycle.test.ts@@ -0,0 +1,725 @@+import { createRoot } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ActiveCallLookup } from '../auto-rejoin';+import { createCallLifecycle, LEAVE_TIMEOUT_MS } from '../call-lifecycle';+import { bindNativeCallLifecycle } from '../native-call-lifecycle';+import {+ createNativeCallState,+ type NativeCallSnapshot,+} from '../native-call-state';++vi.mock('../callkit-drawer-theme', () => ({+ createCallKitDrawerTheme: () => () => ({}),+}));++const first: NativeCallSnapshot = {+ channelId: 'channel-1',+ callId: 'call-1',+ connectionState: 'connected',+ isAudioMuted: false,+ isVideoMuted: true,+ videoOverlayMode: 'hidden',+};+const second: NativeCallSnapshot = {+ ...first,+ channelId: 'channel-2',+ callId: 'call-2',+};+const identity = (call: NativeCallSnapshot) => ({+ channelId: call.channelId,+ callId: call.callId,+});+const cleanups: (() => void)[] = [];++function deferred() {+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<void>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}++function setup(initial: NativeCallSnapshot | null = first) {+ return createRoot((dispose) => {+ const native = createNativeCallState();+ native.setSnapshot(initial);+ const unwatch = vi.fn();+ const ports = {+ shouldRequestToken: vi.fn((_channelId: string) => true),+ requestToken: vi.fn(async () => ({+ ...identity(first),+ roomName: 'room-1',+ token: 'token',+ serverUrl: 'ws://localhost',+ })),+ connect: vi.fn(async () => {}),+ disconnect: vi.fn<+ Parameters<typeof createCallLifecycle>[0]['disconnect']+ >(async () => {+ native.setSnapshot(null);+ }),+ leave: vi.fn(async () => {}),+ lookup: vi.fn<() => Promise<ActiveCallLookup>>(async () => ({+ callId: first.callId,+ })),+ currentCall: () => {+ const snapshot = native.snapshot();+ return snapshot ? identity(snapshot) : undefined;+ },+ beginJoin: vi.fn(),+ rollbackJoin: vi.fn(),+ setError: vi.fn(),+ watch: vi.fn(() => unwatch),+ onJoined: vi.fn(),+ onLeft: vi.fn(),+ reportError: vi.fn(),+ } satisfies Parameters<typeof createCallLifecycle>[0];+ const lifecycle = createCallLifecycle(ports);+ const unbind = bindNativeCallLifecycle(native, lifecycle);+ cleanups.push(() => {+ unbind();+ lifecycle.dispose();+ dispose();+ });+ return { native, lifecycle, ports, unwatch, unbind, dispose };+ });+}++describe('native snapshot events and call ownership', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => {+ for (const cleanup of cleanups.splice(0)) cleanup();+ vi.useRealTimers();+ });++ it('adopts an existing native call at setup and preserves its watcher through media updates', () => {+ const { native, lifecycle, ports } = setup();+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(first),+ });+ const updated = native.setSnapshot(+ (snapshot) => snapshot && { ...snapshot, isAudioMuted: true }+ );+ expect(updated?.isAudioMuted).toBe(true);+ expect(native.snapshot()).toBe(updated);+ expect(ports.watch).toHaveBeenCalledOnce();+ expect(ports.connect).not.toHaveBeenCalled();+ expect(ports.onJoined).not.toHaveBeenCalled();+ });++ it('reconciles a missed native end immediately without waiting for a Solid effect', () => {+ const { native, lifecycle, unwatch } = setup();+ const onLeave = vi.fn();+ lifecycle.onLeave(onLeave);+ native.setSnapshot(null);+ expect(lifecycle.getState().t).toBe('idle');+ expect(unwatch).toHaveBeenCalledOnce();+ expect(onLeave).toHaveBeenCalledExactlyOnceWith(first.channelId);+ native.setSnapshot(null);+ expect(onLeave).toHaveBeenCalledOnce();+ });++ it('keeps native reconnecting snapshots under the existing call lifetime', () => {+ const { native, lifecycle, ports } = setup();+ native.setSnapshot({ ...first, connectionState: 'reconnecting' });+ native.setSnapshot(first);+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(first),+ });+ expect(ports.watch).toHaveBeenCalledOnce();+ });++ it.each(['resolve', 'reject', 'timeout'] as const)(+ 'adopts a newer native call after an old server leave completes with %s',+ async (completion) => {+ const { native, lifecycle, ports } = setup();+ const pending = deferred();+ ports.leave.mockReturnValueOnce(pending.promise);+ const leaving = lifecycle.leave(first.channelId);+ const result =+ completion === 'resolve'+ ? expect(leaving).resolves.toBeUndefined()+ : expect(leaving).rejects.toThrow();+ await vi.advanceTimersByTimeAsync(0);+ native.setSnapshot(second);+ expect(lifecycle.getState().t).toBe('leaving');+ if (completion === 'resolve') pending.resolve();+ else if (completion === 'reject') pending.reject(new Error('offline'));+ else await vi.advanceTimersByTimeAsync(LEAVE_TIMEOUT_MS);+ await result;+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ expect(ports.watch).toHaveBeenCalledTimes(2);+ expect(ports.watch).toHaveBeenLastCalledWith(+ identity(second),+ expect.any(Function),+ expect.any(Function)+ );+ pending.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ }+ );++ it('preserves a newer native call arriving before transport cleanup finishes', async () => {+ const { native, lifecycle, ports } = setup();+ const pending = deferred();+ ports.disconnect.mockImplementationOnce(() => pending.promise);+ const leaving = lifecycle.leave(first.channelId);+ native.setSnapshot(second);+ pending.resolve();+ await leaving;+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(first.channelId);+ });++ it('does not resurrect a replacement that also ends while leave is pending', async () => {+ const { native, lifecycle, ports } = setup();+ const pending = deferred();+ ports.leave.mockReturnValueOnce(pending.promise);+ const leaving = lifecycle.leave(first.channelId);+ await vi.advanceTimersByTimeAsync(0);+ native.setSnapshot(second);+ native.setSnapshot(null);+ pending.resolve();+ await leaving;+ expect(lifecycle.getState().t).toBe('idle');+ expect(ports.watch).toHaveBeenCalledOnce();+ });++ it('removes both subscriptions on disposal, including reconciliation after leave', async () => {+ const { native, lifecycle, ports, unbind } = setup();+ const pending = deferred();+ ports.leave.mockReturnValueOnce(pending.promise);+ const leaving = lifecycle.leave(first.channelId);+ await vi.advanceTimersByTimeAsync(0);+ unbind();+ native.setSnapshot(second);+ pending.resolve();+ await leaving;+ expect(lifecycle.getState().t).toBe('idle');+ native.setSnapshot(first);+ expect(ports.watch).toHaveBeenCalledOnce();+ });++ it('releases native snapshot listeners with their provider owner', () => {+ const { native, dispose } = setup(null);+ const listener = vi.fn();+ native.onSnapshot(listener);+ expect(listener).toHaveBeenCalledExactlyOnceWith(null);+ dispose();+ native.setSnapshot(first);+ expect(listener).toHaveBeenCalledOnce();+ });++ it.each(['connecting', 'connected'] as const)(+ 'cancels a native %s session that ends before start resolves',+ async (connectionState) => {+ const { native, lifecycle, ports } = setup(null);+ const pending = deferred();+ ports.connect.mockReturnValueOnce(pending.promise);+ const joining = lifecycle.join(first.channelId);+ const cancelled = expect(joining).rejects.toThrow('cancelled');+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ expect(lifecycle.getState()).toEqual({ t: 'idle' });+ expect(ports.disconnect).toHaveBeenCalledExactlyOnceWith({+ endNativeCall: false,+ });+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(first.channelId);+ pending.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.onJoined).not.toHaveBeenCalled();+ const retry = lifecycle.join(first.channelId);+ await vi.advanceTimersByTimeAsync(300);+ await retry;+ expect(ports.requestToken).toHaveBeenCalledTimes(2);+ }+ );++ it.each(['resolve', 'reject', 'timeout'] as const)(+ 'preserves a new native call when cancelled-join cleanup finishes with %s',+ async (completion) => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.leave.mockReturnValueOnce(cleanup.promise);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ expect(lifecycle.getState().t).toBe('leaving');+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(first.channelId);+ native.setSnapshot(second);+ if (completion === 'resolve') cleanup.resolve();+ else if (completion === 'reject') cleanup.reject(new Error('offline'));+ else await vi.advanceTimersByTimeAsync(LEAVE_TIMEOUT_MS);+ await vi.advanceTimersByTimeAsync(0);+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ expect(ports.watch).toHaveBeenCalledExactlyOnceWith(+ identity(second),+ expect.any(Function),+ expect.any(Function)+ );+ expect(ports.reportError).toHaveBeenCalledTimes(+ completion === 'resolve' ? 0 : 1+ );+ connection.resolve();+ cleanup.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.onJoined).not.toHaveBeenCalled();+ expect(ports.leave).toHaveBeenCalledOnce();+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ }+ );++ it.each([first, { ...first, callId: 'replacement' }])(+ 'keeps restored membership in $callId when native cancellation cleanup is superseded',+ async (restored) => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ let member = true;+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.disconnect.mockReturnValueOnce(cleanup.promise);+ ports.leave.mockImplementationOnce(async () => {+ member = false;+ });+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ native.setSnapshot(restored);+ cleanup.resolve();+ connection.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(member).toBe(true);+ expect(ports.leave).not.toHaveBeenCalled();+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(restored),+ });+ expect(ports.watch).toHaveBeenCalledOnce();+ expect(ports.onJoined).not.toHaveBeenCalled();+ expect(ports.reportError).not.toHaveBeenCalled();+ }+ );++ it('accepts a retry while native cancellation transport cleanup is still pending', async () => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.disconnect.mockReturnValueOnce(cleanup.promise);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ const retry = expect(+ lifecycle.join(first.channelId)+ ).resolves.toBeUndefined();+ await vi.advanceTimersByTimeAsync(300);+ await retry;+ cleanup.resolve();+ connection.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.requestToken).toHaveBeenCalledTimes(2);+ expect(ports.leave).not.toHaveBeenCalled();+ expect(ports.onJoined).toHaveBeenCalledOnce();+ expect(ports.reportError).not.toHaveBeenCalled();+ });++ it.each(['resolve', 'reject'] as const)(+ 'accepts a retry after an already-sent cancellation leave completes with %s',+ async (completion) => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.leave.mockReturnValueOnce(cleanup.promise);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.leave).toHaveBeenCalledOnce();+ const retry = lifecycle.join(first.channelId);+ const joined = expect(retry).resolves.toBeUndefined();+ expect(lifecycle.join(first.channelId)).toBe(retry);+ await vi.advanceTimersByTimeAsync(300);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ if (completion === 'resolve') cleanup.resolve();+ else cleanup.reject(new Error('offline'));+ await joined;+ expect(ports.requestToken).toHaveBeenCalledTimes(2);+ expect(ports.onJoined).toHaveBeenCalledOnce();+ connection.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.onJoined).toHaveBeenCalledOnce();+ }+ );++ it.each([+ { manualRetry: false, callId: first.callId },+ { manualRetry: true, callId: first.callId },+ { manualRetry: false, callId: '01991b2a-f4e0-7000-a000-111111111111' },+ ])(+ 'renews restored native membership after a sent leave (manual retry: $manualRetry, call: $callId)',+ async ({ manualRetry, callId }) => {+ const { native, lifecycle, ports } = setup(null);+ const restored = { ...first, callId: callId.toUpperCase() };+ ports.lookup.mockResolvedValue({ callId });+ const connection = deferred();+ const cleanup = deferred();+ let member = false;+ ports.shouldRequestToken.mockImplementation((channelId) => {+ const snapshot = native.snapshot();+ return (+ !snapshot ||+ snapshot.channelId !== channelId ||+ snapshot.connectionState === 'disconnected' ||+ snapshot.connectionState === 'disconnecting'+ );+ });+ ports.requestToken.mockImplementation(async () => {+ member = true;+ return {+ ...identity(first),+ callId,+ roomName: 'room-1',+ token: 'token',+ serverUrl: 'ws://localhost',+ };+ });+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.leave.mockImplementationOnce(async () => {+ await cleanup.promise;+ member = false;+ });+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ const retry = manualRetry ? lifecycle.join(first.channelId) : undefined;+ native.setSnapshot(restored);+ await vi.advanceTimersByTimeAsync(300);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ cleanup.resolve();+ await retry;+ await vi.advanceTimersByTimeAsync(0);+ expect(member).toBe(true);+ expect(ports.requestToken).toHaveBeenCalledTimes(2);+ expect(ports.connect).toHaveBeenCalledOnce();+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: { ...identity(first), callId },+ });+ expect(ports.watch).toHaveBeenCalledOnce();+ connection.resolve();+ }+ );++ it('cleans up if renewal returns a different call from the restored native session', async () => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.leave.mockReturnValueOnce(cleanup.promise);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ ports.shouldRequestToken.mockReturnValue(false);+ ports.requestToken.mockResolvedValueOnce({+ ...identity(first),+ callId: 'new-server-call',+ roomName: 'room-1',+ token: 'new-token',+ serverUrl: 'ws://localhost',+ });+ native.setSnapshot(first);+ cleanup.resolve();+ await vi.advanceTimersByTimeAsync(300);+ expect(lifecycle.getState().t).toBe('idle');+ expect(native.snapshot()).toBeNull();+ expect(ports.connect).toHaveBeenCalledOnce();+ expect(ports.leave).toHaveBeenCalledTimes(2);+ expect(ports.disconnect).toHaveBeenLastCalledWith({ endNativeCall: true });+ expect(ports.watch).not.toHaveBeenCalled();+ expect(ports.onJoined).not.toHaveBeenCalled();+ connection.resolve();+ });++ it.each([+ null,+ 'unavailable',+ { callId: 'replacement' },+ new Error('lookup offline'),+ ] as const)(+ 'never recreates a native call when automatic renewal lookup returns %j',+ async (result) => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.leave.mockReturnValueOnce(cleanup.promise);+ if (result instanceof Error) ports.lookup.mockRejectedValueOnce(result);+ else ports.lookup.mockResolvedValueOnce(result);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ native.setSnapshot(first);+ cleanup.resolve();+ await vi.advanceTimersByTimeAsync(300);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ expect(ports.connect).toHaveBeenCalledOnce();+ expect(ports.onJoined).not.toHaveBeenCalled();+ expect(ports.leave).toHaveBeenCalledOnce();+ expect(lifecycle.getState().t).toBe('idle');+ connection.resolve();+ }+ );++ it('does not end a different native channel that arrives during a renewal request', async () => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ const renewal = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.leave.mockReturnValueOnce(cleanup.promise);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ ports.shouldRequestToken.mockReturnValue(false);+ ports.requestToken.mockImplementationOnce(async () => {+ await renewal.promise;+ return {+ ...identity(first),+ callId: 'new-server-call',+ roomName: 'room-1',+ token: 'new-token',+ serverUrl: 'ws://localhost',+ };+ });+ ports.disconnect.mockImplementationOnce(async (options) => {+ if (options?.endNativeCall !== false) native.setSnapshot(null);+ });+ native.setSnapshot(first);+ cleanup.resolve();+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot(second);+ renewal.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.disconnect).toHaveBeenLastCalledWith({ endNativeCall: false });+ expect(native.snapshot()).toEqual(second);+ expect(ports.leave).toHaveBeenLastCalledWith(first.channelId);+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ connection.resolve();+ });++ it('does not renew a restored session that ends while its old leave is pending', async () => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.leave.mockReturnValueOnce(cleanup.promise);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await vi.advanceTimersByTimeAsync(0);+ native.setSnapshot(first);+ native.setSnapshot(null);+ cleanup.resolve();+ connection.resolve();+ await vi.advanceTimersByTimeAsync(300);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ expect(ports.onJoined).not.toHaveBeenCalled();+ expect(lifecycle.getState().t).toBe('idle');+ });++ it('finishes the old channel cleanup before following a different native channel', async () => {+ const { native, lifecycle, ports } = setup(null);+ const connection = deferred();+ const cleanup = deferred();+ ports.connect.mockReturnValueOnce(connection.promise);+ ports.disconnect.mockReturnValueOnce(cleanup.promise);+ const cancelled = expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'cancelled'+ );+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot({ ...first, connectionState: 'connecting' });+ native.setSnapshot(null);+ await cancelled;+ await expect(lifecycle.join(second.channelId)).rejects.toThrow(+ 'still leaving'+ );+ native.setSnapshot(second);+ cleanup.resolve();+ connection.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(first.channelId);+ expect(ports.requestToken).toHaveBeenCalledOnce();+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ });++ it('adopts a native replacement before the old start transaction resolves', async () => {+ const { native, lifecycle, ports } = setup(null);+ const pending = deferred();+ ports.connect.mockReturnValueOnce(pending.promise);+ const joining = lifecycle.join(first.channelId);+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot(first);+ native.setSnapshot(second);+ pending.resolve();+ await joining;+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ expect(ports.onJoined).not.toHaveBeenCalled();+ });++ it.each([+ null,+ { ...second, connectionState: 'disconnected' as const },+ { ...second, connectionState: 'disconnecting' as const },+ ])(+ 'ignores an empty or stale ended snapshot while native start is pending (%j)',+ async (snapshot) => {+ const { native, lifecycle, ports } = setup(null);+ const pending = deferred();+ ports.connect.mockReturnValueOnce(pending.promise);+ const joining = lifecycle.join(first.channelId);+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot(snapshot);+ pending.resolve();+ await joining;+ // Start can resolve before the first media snapshot, so another empty+ // notification must not end the acknowledged call either.+ native.setSnapshot(snapshot);+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(first),+ });+ expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(identity(first));+ expect(ports.disconnect).not.toHaveBeenCalled();+ expect(ports.leave).not.toHaveBeenCalled();+ }+ );++ it.each(['disconnected', 'disconnecting'] as const)(+ 'allows a real new join while the old native snapshot is %s',+ async (connectionState) => {+ const { native, lifecycle, ports } = setup();+ native.setSnapshot({ ...first, connectionState });+ expect(lifecycle.getState().t).toBe('idle');+ const joining = lifecycle.join(first.channelId);+ await vi.advanceTimersByTimeAsync(300);+ await joining;+ expect(ports.requestToken).toHaveBeenCalledExactlyOnceWith(+ first.channelId+ );+ expect(ports.connect).toHaveBeenCalledOnce();+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(first),+ });+ }+ );++ it('does not treat the initial missing snapshot as an end while starting a native call', async () => {+ const { lifecycle, ports } = setup(null);+ const joining = lifecycle.join(first.channelId);+ await vi.advanceTimersByTimeAsync(300);+ await joining;+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(first),+ });+ expect(ports.onJoined).toHaveBeenCalledOnce();+ });++ it('adopts a native replacement when an old start transaction rejects', async () => {+ const { native, lifecycle, ports } = setup(null);+ const pending = deferred();+ ports.connect.mockReturnValueOnce(pending.promise);+ // The native controller preserves a different call during failed cleanup.+ ports.disconnect.mockImplementationOnce(async () => {});+ const joining = lifecycle.join(first.channelId);+ const rejected = expect(joining).rejects.toThrow('already active');+ await vi.advanceTimersByTimeAsync(300);+ native.setSnapshot(second);+ pending.reject(new Error('already active'));+ await rejected;+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(second),+ });+ expect(ports.watch).toHaveBeenCalledOnce();+ expect(ports.leave).not.toHaveBeenCalled();+ expect(ports.setError).toHaveBeenLastCalledWith(null);+ });+});diff --git a/apps/web/src/features/channel/Call/tests/use-call.test.ts b/apps/web/src/features/channel/Call/tests/use-call.test.tsnew file mode 100644index 0000000000..037f2e878b--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/use-call.test.ts@@ -0,0 +1,44 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { CallLifecycleState } from '../call-lifecycle';+import { useCall } from '../use-call';++let state: CallLifecycleState;+let error: string | null;++vi.mock('../CallContext', () => ({+ useCallContext: () => ({+ callLifecycle: { getState: () => state },+ isInCall: () => state.t === 'active',+ activeChannelId: () => (state.t === 'active' ? state.call.channelId : null),+ joinError: () => error,+ }),+}));++describe('call view errors', () => {+ beforeEach(() => {+ state = { t: 'active', call: { channelId: 'channel-1', callId: 'call-1' } };+ error = null;+ });++ it('keeps the active call overlay visible when another channel cannot join', () => {+ const active = useCall(() => 'channel-1');+ const other = useCall(() => 'channel-2');+ error =+ "You're already in another call. Leave your current call before joining a new one.";+ expect(active.isInThisChannel()).toBe(true);+ expect(active.joinError()).toBeNull();+ expect(other.isInThisChannel()).toBe(false);+ expect(other.joinError()).toBe(error);+ });++ it('still exposes a failed join error when there is no live session', () => {+ const call = useCall(() => 'channel-1');+ state = {+ t: 'failed',+ channelId: 'channel-1',+ error: new Error('offline'),+ };+ error = 'Unable to join the call. Please check your connection.';+ expect(call.joinError()).toBe(error);+ });+});diff --git a/apps/web/src/features/channel/Call/use-call.ts b/apps/web/src/features/channel/Call/use-call.tsindex 2d265b6720..7b27a6d39f 100644--- a/apps/web/src/features/channel/Call/use-call.ts+++ b/apps/web/src/features/channel/Call/use-call.ts@@ -1,422 +1,48 @@-import { analytics } from '@app/lib/analytics';-import { useChannelsContext } from '@core/context/channels';-import { useUserId } from '@core/context/user';-import { throwOnErr } from '@core/util/result';-import {- invalidateActiveCallQueries,- useLeaveCallMutation,-} from '@queries/call/call';-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 { onCleanup } from 'solid-js';import { useCallContext } from './CallContext';-import { publishCallResolution } from './call-resolution';-import { LK_DISCONNECT_REASON, LK_ROOM_EVENT } from './livekit-loader';-import { registerCallKitCallEndedHandler } from './use-callkit';+import type { CallSessionDisconnectOptions } from './CallSessionController';type UseCallOptions = {- /** Called after successfully joining a call. */+ /** Select the call tab when Join is requested, including a refused join. */onJoin?: () => void;- /** Called when the call ends for any reason (user leave, disconnect, kicked, etc.). */+ /** Called when this channel's call ends for any reason. */onLeave?: () => void;};-type JoinCallContext = {- channelId: string;-};--const JOIN_TIMEOUT_MS = 15_000;-const MAX_AUTO_REJOIN_ATTEMPTS = 1;--type ActiveJoinAttempt = {- channelId: string;- promise: Promise<void>;-};--function shouldAutoRejoin(reason?: DisconnectReason) {- switch (reason) {- case LK_DISCONNECT_REASON.CLIENT_INITIATED:- case LK_DISCONNECT_REASON.DUPLICATE_IDENTITY:- case LK_DISCONNECT_REASON.PARTICIPANT_REMOVED:- case LK_DISCONNECT_REASON.ROOM_DELETED:- case LK_DISCONNECT_REASON.ROOM_CLOSED:- return false;- default:- return true;- }-}--// Module-level guard: only one join can be in flight at a time across all-// useCall() instances. The call button, call tab, auto-join flow, and in-call-// panel can all mount their own hook; without this, two components can race and-// call room.connect() while LiveKit is already reconnecting.-let activeJoinAttempt: ActiveJoinAttempt | null = null;--// Module-level guard: only one leave can be in flight at a time across all-// useCall() instances. Prevents a user-initiated leave and a concurrent-// CallKit call-ended event from both proceeding to disconnect+leaveMutation.-// Tracked as a start timestamp so a leave stuck on a hung network request-// cannot silently swallow every later leave tap.-const LEAVE_IN_FLIGHT_STALE_MS = 10_000;-let leaveInFlightSince: number | null = null;--function isLeaveInFlight(): boolean {- if (leaveInFlightSince === null) return false;- // Deliberately wall-clock, not performance.now(): the performance timeline- // freezes while iOS suspends the webview, so a monotonic delta would keep a- // pre-suspension leave "in flight" after resume — the stuck-leave symptom- // this latch exists to prevent.- const elapsed = Date.now() - leaveInFlightSince;- // A backwards wall-clock jump must release the latch, not extend it.- return elapsed >= 0 && elapsed < LEAVE_IN_FLIGHT_STALE_MS;-}--/**- * Hook that orchestrates joining/leaving calls by combining- * the API mutations with the platform call session controller.- *- * Join is implemented as a single TanStack mutation so optimistic UI, timeout,- * rollback, and server cleanup stay in onMutate / onError / onSuccess.- */+/** A view of the provider's shared call lifecycle. */export function useCall(channelId: () => string, options?: UseCallOptions) {const callCtx = useCallContext();- const channelsCtx = useChannelsContext();- const userId = useUserId();- const leaveMutation = useLeaveCallMutation();-- // Track the disconnect listener so we can swap it when the room changes.- 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;- globalThis.clearTimeout(autoRejoinTimer);- 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;-- if (!shouldAutoRejoin(reason)) {- options?.onLeave?.();- return;- }-- if (autoRejoinAttempts >= MAX_AUTO_REJOIN_ATTEMPTS) {- options?.onLeave?.();- return;- }-- autoRejoinAttempts += 1;- callCtx.setJoinError('Call disconnected. Reconnecting…');- const attempt: AutoRejoinAttempt = {- channelId: channelId(),- callId: listeningCallId,- scheduledAt: Date.now(),- };- autoRejoinTimer = globalThis.setTimeout(() => {- autoRejoinTimer = null;- void runAutoRejoin(attempt);- }, AUTO_REJOIN_DELAY_MS);- }-- function attachDisconnectListener() {- cleanupDisconnectListener?.();- cleanupDisconnectListener = null;+ const lifecycle = callCtx.callLifecycle;- 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- // token/Room instead of immediately dumping the user out of the call UI.- cleanupDisconnectListener?.();- cleanupDisconnectListener = null;- scheduleAutoRejoin(reason);- };- room.on(LK_ROOM_EVENT.Disconnected, handleDisconnect);- cleanupDisconnectListener = () =>- room.off(LK_ROOM_EVENT.Disconnected, handleDisconnect);- }-- // If the call is already active for this channel (e.g. the user navigated- // away and came back), eagerly attach the disconnect listener so onLeave- // fires when the call ends.- if (callCtx.isInCall() && callCtx.activeChannelId() === channelId()) {- attachDisconnectListener();- }-- onCleanup(() => {- cleanupDisconnectListener?.();- clearAutoRejoinTimer();- });-- createEffect(() => {- if (!callCtx.isInCall() || callCtx.activeChannelId() !== channelId())- return;-- const unregister = registerCallKitCallEndedHandler(() =>- leaveCall({ endNativeCall: false }).catch((e) =>- console.error('callkit: failed to leave ended call', e)- )+ if (options?.onLeave) {+ onCleanup(+ lifecycle.onLeave((id) => {+ if (id === channelId()) options.onLeave?.();+ }));-- onCleanup(unregister);- });-- /** Cleared in `joinCall` `finally` + safety timer so Try again never stays disabled if TanStack pending glitches. */- const [joinUiPending, setJoinUiPending] = createSignal(false);-- let cancelCurrentJoin: () => void = () => {};-- const joinCallMutation = useMutation(() => ({- mutationFn: async (id: string) => {- let cancelled = false;- cancelCurrentJoin = () => {- cancelled = true;- };-- const doConnect = async () => {- if (!callCtx.shouldRequestSessionToken(id)) {- callCtx.rollbackOptimisticJoin();- return;- }-- // Call the join API directly so a timed-out join attempt cannot leave- // `useJoinCallMutation` stuck pending and block the next retry.- const [tokenResponse] = await Promise.all([- throwOnErr(() => callServiceClient.getOrCreateCall(id)),- new Promise<void>((resolve) => setTimeout(resolve, 300)),- ]);- if (cancelled) return;-- await callCtx.connectSession(tokenResponse, {- channelTitle:- channelsCtx.channelsById()[tokenResponse.channelId]?.name ?? null,- });- if (cancelled) return;-- // Publish only once the session is connected — a cancelled or- // timed-out join must not silence this user's ring on other tabs.- // (onError sets `cancelled` via cancelCurrentJoin.)- const answeringUserId = userId();- if (answeringUserId) {- publishCallResolution({- type: 'answered',- callId: tokenResponse.callId,- answeredBy: answeringUserId,- });- }- };-- const timeout = new Promise<never>((_, reject) =>- setTimeout(- () => reject(new Error('Connection timed out')),- JOIN_TIMEOUT_MS- )- );-- await Promise.race([doConnect(), timeout]);- },- onMutate: (id: string): JoinCallContext => {- cancelCurrentJoin();- callCtx.beginOptimisticJoin(id);- options?.onJoin?.();- return { channelId: id };- },- onSuccess: () => {- autoRejoinAttempts = 0;- clearAutoRejoinTimer();- void invalidateActiveCallQueries();- attachDisconnectListener();- analytics.track('call_action', {- action: 'joined',- channelId: channelId(),- });- },- // Keep this handler synchronous: we undo the optimistic join and show the- // error message right away. LiveKit disconnect and the server leave call- // run in a fire-and-forget async block — on flaky networks those can take- // forever, and if we awaited them here TanStack would keep the mutation- // pending and the Try again button would stay stuck.- onError: (_err, channelId: string, _ctx: JoinCallContext | undefined) => {- cancelCurrentJoin();- callCtx.rollbackOptimisticJoin();- callCtx.setJoinError(- 'Unable to join the call. Please check your connection.'- );- void (async () => {- try {- await callCtx.disconnectSession({ endNativeCall: false });- } catch (e) {- console.error('join error recovery: disconnect failed', e);- }- try {- await leaveMutation.mutateAsync(channelId);- } catch (e) {- console.error('join error recovery: leave server state failed', e);- }- })();- },- }));-- const joinCall = async () => {- clearAutoRejoinTimer();- const id = channelId();- const existing = activeJoinAttempt;- if (existing && existing.channelId !== id) {- throw new Error('Already joining another call');- }-- const joinPromise = existing?.promise ?? joinCallMutation.mutateAsync(id);- if (!existing) {- activeJoinAttempt = { channelId: id, promise: joinPromise };- }-- setJoinUiPending(true);- const safetyMs = JOIN_TIMEOUT_MS + 5_000;- const safetyTimer = globalThis.setTimeout(- () => setJoinUiPending(false),- safetyMs- );- try {- await joinPromise;- } finally {- if (activeJoinAttempt?.promise === joinPromise) {- activeJoinAttempt = null;- }- globalThis.clearTimeout(safetyTimer);- setJoinUiPending(false);- }- };-- async function leaveCall(leaveOptions?: { endNativeCall?: boolean }) {- if (isLeaveInFlight()) return;- const leaveStartedAt = Date.now();- leaveInFlightSince = leaveStartedAt;- const id = channelId();- // Detach before disconnect so the RoomEvent.Disconnected handler- // doesn't double-fire onLeave.- cleanupDisconnectListener?.();- cleanupDisconnectListener = null;- clearAutoRejoinTimer();- try {- try {- await callCtx.disconnectSession(leaveOptions);- options?.onLeave?.();- analytics.track('call_action', {- action: 'left',- channelId: id,- leaveReason: 'user_initiated',- });- } finally {- await leaveMutation.mutateAsync(id);- }- } finally {- // A staled-out leave releases the guard to a newer attempt; don't let- // its late completion clear that newer attempt's claim.- if (leaveInFlightSince === leaveStartedAt) {- leaveInFlightSince = null;- }- }}return {- joinCall,- leaveCall,- // Rely on `joinUiPending` (finally + safety timer) so the button is not- // gated on `joinCallMutation.isPending`, which can stick true in edge cases.- isJoining: () => joinUiPending(),- isLeaving: () => leaveMutation.isPending,+ joinCall: () => lifecycle.join(channelId(), options?.onJoin),+ leaveCall: (options?: CallSessionDisconnectOptions) =>+ lifecycle.leave(channelId(), options),+ isJoining: () => {+ const state = lifecycle.getState();+ return state.t === 'joining' && state.request.channelId === channelId();+ },+ isLeaving: () => {+ const state = lifecycle.getState();+ return state.t === 'leaving' && state.request.channelId === channelId();+ },isInCall: callCtx.isInCall,isInThisChannel: () =>callCtx.isInCall() && callCtx.activeChannelId() === channelId(),- joinError: callCtx.joinError,+ joinError: () => {+ const state = lifecycle.getState();+ return state.t === 'active' && state.call.channelId === channelId()+ ? null+ : callCtx.joinError();+ },callCtx,};}diff --git a/apps/web/src/lib/queries/call/call.ts b/apps/web/src/lib/queries/call/call.tsindex 39d78645ea..2b5428b194 100644--- a/apps/web/src/lib/queries/call/call.ts+++ b/apps/web/src/lib/queries/call/call.ts@@ -14,13 +14,22 @@ import { callKeys } from './keys';export function useActiveCallQuery(channelId: Accessor<string>) {return useQuery(() => ({queryKey: callKeys.active(channelId()).queryKey,- queryFn: async () =>- await throwOnErr(() => callServiceClient.checkActiveCall(channelId())),+ queryFn: () => fetchActiveCall(channelId()),placeholderData: null,refetchInterval: 15_000,}));}+/** Fresh lookups keep recovery from re-creating a call that already ended. */+export function fetchActiveCall(channelId: string) {+ return throwOnErr(() => callServiceClient.checkActiveCall(channelId));+}++/** Each join attempt owns its request, including retries after a timeout. */+export function requestCallToken(channelId: string) {+ return throwOnErr(() => callServiceClient.getOrCreateCall(channelId));+}+/*** All active calls in channels the user is a member of, newest first. One* request app-wide; the websocketdiff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 3dcb29ec30..e9c41d8baf 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -340,6 +340,40 @@ and DMs section headers.On touch layouts, the `Recent`, `Channels`, and `DMs` pill tabs each retaintheir own loaded pages and load more as their active list approaches the end.+## Call lifecycle++The channel's call tab and floating call controls share one session. Repeated+Join clicks while connecting should produce one connection; leaving from either+control ends the same call. Navigate away and return while connected to check+that the call and its controls remain usable.++For recovery checks, keep another participant connected and briefly interrupt+the first participant's network. Recovery may rejoin that same live call. It+must not start a replacement call if the original ended, or rejoin after the+user chose Leave. A failed join must restore the Try again control even if+background cleanup is slow.++If another call prevents joining, the error should say to leave the current+call first. Trying to join another channel must keep the current call connected,+with its participants and controls intact. A restored live session must clear+any earlier join or recovery error. Failed Join, Call Again, and Leave actions must not produce unhandled+promise rejections.++On iOS, ending a call during connection must leave Join usable. If CallKit+restores or answers another call while an earlier join or leave finishes, the+controls must follow the current native call; finishing the old operation must+not restore the old call or remove the new call's end handler.+An empty native snapshot before the first media update must not cancel a new+join. Once native has reported the session, disconnecting or ending it must+cancel pending connection/recovery and allow a new join.+Cancelling after a token is issued must also remove server membership, even if+media has not connected yet. Repeated end events share that cleanup; a newer+native call must survive while cleanup for the cancelled attempt finishes.+Restore the same channel while transport cleanup is pending and check that no+server leave is sent for the restored session. Join must also accept a retry+during cancellation cleanup. If a server leave was already sent, the retry+shows Connecting and waits for that request before registering again.+## Channel tabsRadio group at the top of the channel pane: `Messages` / `Attachments` / `Participants`,