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
fix(calls): broadcast incoming-call ring across tabs to avoid duplicate ringers (#5651)
Peter Chinman91a7c07f93fd
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 12c5a01eba..70e301d3fc 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -80,7 +80,6 @@"@opentelemetry/api": "^1.9.1","@phosphor-icons/core": "^2.1.1","@pierre/diffs": "^1.3.5",- "@solid-primitives/broadcast-channel": "^0.1.1","@solid-primitives/context": "^0.3.2","@solid-primitives/event-bus": "^1.1.2","@solid-primitives/keyed": "^1.5.3",diff --git a/apps/web/src/components/app/ReactiveFavicon.tsx b/apps/web/src/components/app/ReactiveFavicon.tsxindex edec8fb491..bb801a68f8 100644--- a/apps/web/src/components/app/ReactiveFavicon.tsx+++ b/apps/web/src/components/app/ReactiveFavicon.tsx@@ -1,10 +1,28 @@import { updateFavicon } from '@app/util/favicon';-import { createBroadcastChannel } from '@solid-primitives/broadcast-channel';+import { createCrossTabBus } from '@core/cross-tab/cross-tab-bus';import { useReactiveColorString } from '@theme/signals/themeReactive';-import { createEffect, createSignal, on, onCleanup, onMount } from 'solid-js';+import { createEffect, createSignal, onCleanup, onMount } from 'solid-js';+import { match, P } from 'ts-pattern';import { useGlobalNotificationSource } from './GlobalAppState';-type BadgeMessage = { hasBadge: boolean };+type BadgeMessage = {+ hasBadge: boolean;+ /**+ * Publish time. Not read by subscribers; it makes each payload unique so+ * the bus's storage fallback fires (see `cross-tab-bus.ts`). Optional so+ * payloads from tabs still on a pre-bus bundle, which omit it, parse.+ */+ sentAt?: number;+};++const badgeBus = createCrossTabBus<BadgeMessage>({+ channelName: 'macro-favicon-badge',+ storageKey: 'macro.favicon-badge',+ parse: (value) =>+ match(value)+ .with({ hasBadge: P.boolean }, ({ hasBadge }) => ({ hasBadge }))+ .otherwise(() => null),+});export function ReactiveFavicon() {const [showNotificationBadge, setShowNotificationBadge] = createSignal(false);@@ -15,44 +33,38 @@ export function ReactiveFavicon() {const accentColor = useReactiveColorString('a0');const badgeColor = useReactiveColorString('a0');- // Create broadcast channel for badge state sync across tabs- const { message: badgeMessage, postMessage: postBadgeMessage } =- createBroadcastChannel<BadgeMessage>('macro-favicon-badge');-- // Listen for badge updates from other tabs- createEffect(- on(- badgeMessage,- (msg) => {- if (msg) {- setShowNotificationBadge(msg.hasBadge);- }- },- { defer: true }- )- );+ const postBadgeMessage = (hasBadge: boolean) => {+ badgeBus.publish({ hasBadge, sentAt: Date.now() });+ };// Remove notification badge when app is focusedconst handleVisibilityChange = () => {setIsAppFocused(!document.hidden);if (!document.hidden) {setShowNotificationBadge(false);- postBadgeMessage({ hasBadge: false });+ postBadgeMessage(false);}};onMount(() => {document.addEventListener('visibilitychange', handleVisibilityChange);+ // Sync badge state across tabs. Publishing also delivers locally, which+ // just re-sets the value the publisher already set.+ const unsubscribeBadgeMessages = badgeBus.subscribe((message) => {+ setShowNotificationBadge(message.hasBadge);+ });+const unsubscribeNotifications = globalNotifications.subscribe(() => {if (!isAppFocused()) {setShowNotificationBadge(true);- postBadgeMessage({ hasBadge: true });+ postBadgeMessage(true);}});onCleanup(() => {document.removeEventListener('visibilitychange', handleVisibilityChange);+ unsubscribeBadgeMessages();unsubscribeNotifications();});});diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsxindex 85c74151c5..4b8a399839 100644--- a/apps/web/src/features/auth/EmailAuth.tsx+++ b/apps/web/src/features/auth/EmailAuth.tsx@@ -3,6 +3,7 @@ import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flaimport { useAnalytics } from '@app/lib/analytics/analytics-context';import { updateUserAuth } from '@core/auth';import { redirectToEmailAuth } from '@core/auth/email';+import { publishLoginSuccess } from '@core/auth/login-events';import { LoadingBlock } from '@core/component/LoadingBlock';import { toast } from '@core/component/Toast/Toast';import { useSettingsState } from '@core/constant/SettingsState';@@ -61,8 +62,7 @@ function EmailSignupCallback(props: Pick<EmailAuthParams, 'successPath'>) {const onSuccessfulAuth = async () => {await updateUserAuth();await invalidateAllAfterLogin();- const channel = new BroadcastChannel('auth');- channel.postMessage({ type: 'login-success' });+ publishLoginSuccess();};const navigateToSuccess = () => {diff --git a/apps/web/src/features/block-call/sidebar/active-call-widget.tsx b/apps/web/src/features/block-call/sidebar/active-call-widget.tsxindex 362443e064..c50638efbe 100644--- a/apps/web/src/features/block-call/sidebar/active-call-widget.tsx+++ b/apps/web/src/features/block-call/sidebar/active-call-widget.tsx@@ -11,7 +11,10 @@ import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';import { ChannelTypeEnum } from '@service-storage/client';import { Avatar, Button, cn, Tooltip } from '@ui';import { createMemo, type FlowComponent, For, Show } from 'solid-js';-import { dismissIncomingCall, useVisibleIncomingCalls } from './incoming-calls';+import {+ dismissIncomingCallEverywhere,+ useVisibleIncomingCalls,+} from './incoming-calls';const SLIM_MAX = 4;@@ -157,7 +160,9 @@ export function SidebarActiveCallWidget(props: {<IncomingCallContextMenucallId={call.callId}channelId={call.channelId}- onDismiss={() => dismissIncomingCall(call.callId)}+ onDismiss={() =>+ dismissIncomingCallEverywhere(call.callId)+ }><Buttonaria-label={`${displayName(channel())} call`}@@ -213,7 +218,9 @@ export function SidebarActiveCallWidget(props: {<IncomingCallContextMenucallId={call.callId}channelId={call.channelId}- onDismiss={() => dismissIncomingCall(call.callId)}+ onDismiss={() =>+ dismissIncomingCallEverywhere(call.callId)+ }><div class="flex items-center gap-1.5 w-full rounded-lg p-2 text-ink-extra-muted hover:bg-ink/3"><button@@ -273,7 +280,7 @@ export function SidebarActiveCallWidget(props: {onClick={(e) => {e.preventDefault();e.stopPropagation();- dismissIncomingCall(call.callId);+ dismissIncomingCallEverywhere(call.callId);}}><XIcon class="size-3" />diff --git a/apps/web/src/features/block-call/sidebar/incoming-calls.ts b/apps/web/src/features/block-call/sidebar/incoming-calls.tsindex 5c639fdd64..bc85c96811 100644--- a/apps/web/src/features/block-call/sidebar/incoming-calls.ts+++ b/apps/web/src/features/block-call/sidebar/incoming-calls.ts@@ -9,6 +9,7 @@ import {getCallRecordResolution,publishCallResolution,} from '@channel/Call/call-resolution';+import { silenceIncomingCallRing } from '@channel/Call/ring-coordination';import { DEV_MODE_ENV } from '@core/constant/featureFlags';import { useChannelsContext } from '@core/context/channels';import { useUserId } from '@core/context/user';@@ -70,6 +71,18 @@ export function dismissIncomingCall(callId: string) {setIncomingCalls((calls) => calls.filter((call) => call.callId !== callId));}+/**+ * Dismisses an incoming call in this tab and silences its audible ring in+ * every tab — the tab making noise may be a sibling (see+ * `ring-coordination.ts`). Use for explicit user dismissals; programmatic+ * paths (resolutions, auto-dismiss, joining) run in every tab already and+ * should use `dismissIncomingCall`.+ */+export function dismissIncomingCallEverywhere(callId: string) {+ silenceIncomingCallRing(callId);+ dismissIncomingCall(callId);+}+function addIncomingCall(call: IncomingCall) {const existingTimeoutId = incomingCallTimeouts.get(call.callId);if (existingTimeoutId !== undefined) {diff --git a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx b/apps/web/src/features/channel/Call/CallStartedNotifier.tsxindex 8e789c9e6e..c631ea824a 100644--- a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx+++ b/apps/web/src/features/channel/Call/CallStartedNotifier.tsx@@ -14,6 +14,12 @@ import {publishCallResolution,} from './call-resolution';import { joinChannelCall } from './join-channel-call';+import {+ attachRingCoordination,+ participateInRing,+ type RingParticipation,+ silenceIncomingCallRing,+} from './ring-coordination';const RING_VOLUME = 0.11;const RING_NOTE_DURATION_S = 0.09;@@ -61,18 +67,48 @@ function closeCallNotification(callId: string) {activeCallNotifications.delete(callId);}-function startCallRinger(- callId: string,- shouldStop: () => boolean,- initialSound?: RingSound-): Ringer {+/**+ * Starts this tab's participation in ringing `callId`. Only the tab that+ * wins the cross-tab election actually makes noise; the others stay silent+ * but take the ring over if the audible tab goes away mid-ring (see+ * `ring-coordination.ts`).+ */+function startCallRinger(callId: string, shouldStop: () => boolean): Ringer {stopCallRinger(callId);- const ringer = startRingingLoop(shouldStop, initialSound, () => {- if (activeCallRingers.get(callId) === ringer) {- activeCallRingers.delete(callId);- }- });++ let loop: Ringer | undefined;+ let isReleasingLoop = false;+ let participation: RingParticipation | undefined;+ const ringer: Ringer = { stop: () => participation?.stop() };activeCallRingers.set(callId, ringer);++ participation = participateInRing({+ callId,+ shouldStop,+ maxDurationMs: MAX_RING_DURATION_MS,+ onAcquire: () => {+ loop = startRingingLoop(shouldStop, playRingSound(), () => {+ // The loop stopping on its own (user joined, max duration) also ends+ // the participation, so this tab stops heartbeating a claim it no+ // longer rings for. Guarded so a release-triggered stop does not end+ // the participation — a demoted tab must stay in the election as a+ // takeover candidate.+ if (!isReleasingLoop) participation?.stop();+ });+ },+ onRelease: () => {+ isReleasingLoop = true;+ loop?.stop();+ isReleasingLoop = false;+ loop = undefined;+ },+ onEnd: () => {+ if (activeCallRingers.get(callId) === ringer) {+ activeCallRingers.delete(callId);+ }+ },+ });+return ringer;}@@ -198,6 +234,11 @@ function startRingingLoop(* like `IncomingCallEvents` rely on it being mounted for instant dismissal,* falling back to their reconciliation poll otherwise.*+ * The ring itself is elected across tabs (`ring-coordination.ts`) so an+ * incoming call sounds like one phone instead of one per open tab; the toast+ * is already deduplicated separately by the platform-notification leader+ * election.+ ** Mount once near the app root, inside `<CallProvider>` and* `<ChannelsContextProvider>`. The backend already excludes the caller from* the broadcast (`call_service::send_call_event` filters on@@ -210,6 +251,11 @@ export function CallStartedNotifier() {const notif = usePlatformNotificationState();const userId = useUserId();+ // Attach up front so sibling tabs' ring claims are already recorded when+ // this tab's own `call_started` event arrives (event delivery across tabs+ // can be milliseconds to seconds apart).+ attachRingCoordination();+createCallResolutionsEffect((resolution) => {if (resolution.type === 'answered') {if (resolution.answeredBy !== userId()) return;@@ -280,11 +326,13 @@ async function emitCallStartedNotification(args: {}) {const { channelId, callId, createdBy, channelName, notif, isJoined } = args;- // Play the sound regardless of notification permission so a user with- // browser notifications denied still gets an audio cue. Keep re-ringing even- // when platform notifications are unavailable; in that case the loop stops- // when the user joins, the call ends, or after MAX_RING_DURATION_MS.- const ringer = startCallRinger(callId, isJoined, playRingSound());+ // Ring regardless of notification permission so a user with browser+ // notifications denied still gets an audio cue. Only the tab that wins the+ // cross-tab election makes noise; this tab still participates so it can+ // take the ring over if the audible tab closes mid-ring. The ring stops+ // when the user joins, the call ends, the ring is silenced in any tab, or+ // after MAX_RING_DURATION_MS.+ const ringer = startCallRinger(callId, isJoined);if (notif === 'not-supported') return;@@ -332,7 +380,11 @@ async function emitCallStartedNotification(args: {});handle.onDismiss(() => {untrack();- ringer.stop();+ // Closing the toast is an explicit "stop ringing": the audible tab may+ // be a sibling, so silence the ring everywhere rather than just here.+ // Also fires after our own `handle.close()` calls, where the ring is+ // ending anyway and the extra silence is harmless.+ silenceIncomingCallRing(callId);});} finally {if (pendingCallNotifications.get(callId) === pending) {diff --git a/apps/web/src/features/channel/Call/call-resolution.ts b/apps/web/src/features/channel/Call/call-resolution.tsindex c187fc1d4e..732ac6f4f6 100644--- a/apps/web/src/features/channel/Call/call-resolution.ts+++ b/apps/web/src/features/channel/Call/call-resolution.ts@@ -1,3 +1,4 @@+import { createCrossTabBus } from '@core/cross-tab/cross-tab-bus';import type { CallRecord } from '@service-call/client';import { onCleanup } from 'solid-js';import { match, P } from 'ts-pattern';@@ -7,14 +8,9 @@ import { match, P } from 'ts-pattern';* a ring resolved in one tab stops in every tab even when a background tab* missed the one-shot websocket event.*- * Resolutions publish over a BroadcastChannel, with a localStorage `storage`- * event as fallback for embedded browsers where BroadcastChannel is missing- * or unreliable. The channel is a hand-rolled module-level singleton rather- * than `@solid-primitives/broadcast-channel`: the primitive constructs- * `BroadcastChannel` unguarded (it would throw in exactly the environments- * the fallback exists for) and ties the channel's lifetime to a reactive- * owner, while publishes here happen from async owner-less contexts and the- * subscription registry must outlive any subscribing component.+ * Resolutions publish over the shared cross-tab bus — see `cross-tab-bus.ts`+ * for the transport (BroadcastChannel with a localStorage `storage` event+ * fallback) and the rationale for hand-rolling it.*/const CALL_RESOLUTION_CHANNEL = 'macro-call-resolution';@@ -34,12 +30,6 @@ export type CallResolution =type CallResolutionHandler = (resolution: CallResolution) => void;-const handlers = new Set<CallResolutionHandler>();-const handledResolutionKeys = new Set<string>();-const MAX_HANDLED_RESOLUTIONS = 100;-let broadcastChannel: BroadcastChannel | null | undefined;-let isStorageListenerAttached = false;-function getResolutionKey(resolution: CallResolution) {return resolution.type === 'answered'? `${resolution.type}:${resolution.callId}:${resolution.answeredBy}`@@ -59,61 +49,12 @@ function parseCallResolution(value: unknown): CallResolution | null {.otherwise(() => null);}-function emitCallResolution(value: unknown) {- const resolution = parseCallResolution(value);- if (!resolution) return;-- const key = getResolutionKey(resolution);- if (handledResolutionKeys.has(key)) return;- handledResolutionKeys.add(key);- if (handledResolutionKeys.size > MAX_HANDLED_RESOLUTIONS) {- const oldestKey = handledResolutionKeys.values().next().value;- if (oldestKey) handledResolutionKeys.delete(oldestKey);- }-- for (const handler of handlers) {- try {- handler(resolution);- } catch (error) {- console.error('Failed to handle call resolution', error);- }- }-}--function getBroadcastChannel() {- if (broadcastChannel !== undefined) return broadcastChannel;- if (typeof BroadcastChannel === 'undefined') {- broadcastChannel = null;- return broadcastChannel;- }-- try {- broadcastChannel = new BroadcastChannel(CALL_RESOLUTION_CHANNEL);- broadcastChannel.addEventListener('message', (event) =>- emitCallResolution(event.data)- );- } catch {- broadcastChannel = null;- }-- return broadcastChannel;-}--function handleStorage(event: StorageEvent) {- if (event.key !== CALL_RESOLUTION_STORAGE_KEY || !event.newValue) return;-- try {- emitCallResolution(JSON.parse(event.newValue));- } catch {- // Ignore malformed or stale values from older clients.- }-}--function attachStorageListener() {- if (isStorageListenerAttached || typeof window === 'undefined') return;- window.addEventListener('storage', handleStorage);- isStorageListenerAttached = true;-}+const callResolutionBus = createCrossTabBus<CallResolution>({+ channelName: CALL_RESOLUTION_CHANNEL,+ storageKey: CALL_RESOLUTION_STORAGE_KEY,+ parse: parseCallResolution,+ getMessageKey: getResolutionKey,+});/*** Publishes a terminal incoming-call state to this tab and sibling tabs.@@ -121,35 +62,12 @@ function attachStorageListener() {* embedded browsers where BroadcastChannel delivery is unreliable.*/export function publishCallResolution(resolution: CallResolution) {- emitCallResolution(resolution);-- try {- getBroadcastChannel()?.postMessage(resolution);- } catch {- // The storage event below remains available as a cross-tab fallback.- }-- try {- localStorage.setItem(- CALL_RESOLUTION_STORAGE_KEY,- JSON.stringify(resolution)- );- } catch {- // Storage can be disabled in private or embedded browser contexts —- // there, even reading the `localStorage` global throws (a `typeof` check- // would not catch that, since the global resolves but its getter throws).- }+ callResolutionBus.publish(resolution);}/** Subscribes to call resolutions originating locally or in another tab. */export function subscribeToCallResolutions(handler: CallResolutionHandler) {- handlers.add(handler);- getBroadcastChannel();- attachStorageListener();-- return () => {- handlers.delete(handler);- };+ return callResolutionBus.subscribe(handler);}/**diff --git a/apps/web/src/features/channel/Call/ring-coordination.ts b/apps/web/src/features/channel/Call/ring-coordination.tsnew file mode 100644index 0000000000..180bd87d64--- /dev/null+++ b/apps/web/src/features/channel/Call/ring-coordination.ts@@ -0,0 +1,464 @@+import { createCrossTabBus } from '@core/cross-tab/cross-tab-bus';+import { evictOldest } from '@core/util/evictOldest';+import { match, P } from 'ts-pattern';++/**+ * Cross-tab election of a single audible ringer per incoming call, so a call+ * ringing in six tabs sounds like one phone instead of six.+ *+ * Every tab that would ring joins the election with `participateInRing`. A+ * participant claims the ring by publishing `(callId, tabId, claimedAt)` and+ * starts ringing immediately; all participants order claims by+ * `(audible desc, claimedAt asc, tabId asc)` and only the winner keeps+ * making noise, so near-simultaneous claimants converge within one message+ * round-trip. Tabs the user has never interacted with claim with+ * `audible: false` (their AudioContext is likely blocked by the autoplay+ * policy, so their ring would be silent) and any audibly-capable tab+ * outranks them.+ *+ * The audible tab re-publishes its claim as a heartbeat. When the heartbeats+ * stop mid-ring (tab crashed) the suppressed tabs re-elect once the claim+ * goes stale, and an explicit `release` sent on pagehide short-cuts that+ * timeout for orderly tab closes — the ring fails over instead of dying with+ * the tab. A `silence` message (the user dismissed the incoming-call toast+ * or widget) stops the noise in every tab without touching the visual+ * affordances.+ *+ * Suppression only spans tabs reachable through the transports in+ * `cross-tab-bus.ts`; where both are unavailable every tab rings, which is+ * the pre-election behavior.+ */++const RING_CHANNEL = 'macro-call-ring';+const RING_STORAGE_KEY = 'macro.call-ring';++/** How often the audible tab re-publishes (heartbeats) its claim. */+const CLAIM_HEARTBEAT_INTERVAL_MS = 1_000;+/**+ * A claim not re-published within this window is considered dead. Generous+ * enough to ride out background-tab timer throttling and to let an answered+ * call's resolution arrive (answering stops the heartbeat immediately, but+ * the `answered` resolution needs a server round-trip) before suppressed+ * tabs mistake the winner's silence for a crash.+ */+const CLAIM_TTL_MS = 3_500;+/**+ * Minimum gap between defensive re-publishes. A live audible tab whose+ * heartbeats got throttled can be mistaken for dead and see a takeover+ * claim; it immediately re-asserts its claim so the usurper stands down,+ * rate-limited so dueling tabs cannot flood the channel.+ */+const CLAIM_DEFENSE_MIN_INTERVAL_MS = 250;+const MAX_TRACKED_CALLS = 50;+const MAX_SILENCED_CALLS = 100;++type RingClaimMessage = {+ type: 'claim';+ callId: string;+ tabId: string;+ /** Election key — stable across every heartbeat of one claim. */+ claimedAt: number;+ /** Whether this tab can actually make noise (see `isAudioLikelyBlocked`). */+ audible: boolean;+ /**+ * Publish time. Not part of the election; it makes each heartbeat's+ * payload unique so the storage fallback fires (see `cross-tab-bus.ts`).+ */+ sentAt: number;+};++type RingSilenceMessage = { type: 'silence'; callId: string; sentAt: number };++type RingReleaseMessage = {+ type: 'release';+ callId: string;+ tabId: string;+ sentAt: number;+};++type RingMessage = RingClaimMessage | RingSilenceMessage | RingReleaseMessage;++function parseRingMessage(value: unknown): RingMessage | null {+ return match(value)+ .with(+ {+ type: 'claim',+ callId: P.string,+ tabId: P.string,+ claimedAt: P.number,+ audible: P.boolean,+ sentAt: P.number,+ },+ ({ type, callId, tabId, claimedAt, audible, sentAt }) => ({+ type,+ callId,+ tabId,+ claimedAt,+ audible,+ sentAt,+ })+ )+ .with(+ { type: 'silence', callId: P.string, sentAt: P.number },+ ({ type, callId, sentAt }) => ({ type, callId, sentAt })+ )+ .with(+ { type: 'release', callId: P.string, tabId: P.string, sentAt: P.number },+ ({ type, callId, tabId, sentAt }) => ({ type, callId, tabId, sentAt })+ )+ .otherwise(() => null);+}++// Handlers are idempotent on repeat delivery and heartbeats must not be+// deduped, so the bus is created without a message key.+const ringBus = createCrossTabBus<RingMessage>({+ channelName: RING_CHANNEL,+ storageKey: RING_STORAGE_KEY,+ parse: parseRingMessage,+});++const tabId: string =+ globalThis.crypto?.randomUUID?.() ??+ `${Date.now()}-${Math.random().toString(36).slice(2)}`;++type TrackedClaim = {+ tabId: string;+ claimedAt: number;+ audible: boolean;+ /** Last time any publish of this claim was seen; drives staleness. */+ lastSeenAt: number;+};++export type RingParticipation = {+ /**+ * Ends this tab's participation without broadcasting anything: stops the+ * local ringer if it is the audible one and lets sibling tabs take the+ * ring over (via claim staleness) while the call is still unresolved. For+ * an explicit user dismissal use `silenceIncomingCallRing` instead.+ */+ stop: () => void;+};++export type RingParticipationOptions = {+ callId: string;+ /** Mirrors the ringer's stop condition (e.g. the user joined the call). */+ shouldStop: () => boolean;+ /**+ * Participation ends unconditionally this long after it starts, so a+ * takeover cannot outlive the original ring window.+ */+ maxDurationMs: number;+ /**+ * Start making noise: this tab won the election, either up front or by+ * taking over from a tab that went away mid-ring.+ */+ onAcquire: () => void;+ /**+ * Stop making noise: a better-placed tab holds the ring, or the ring was+ * silenced. Only ever called after a matching `onAcquire`.+ */+ onRelease: () => void;+ /** Called exactly once when the participation ends, whatever the cause. */+ onEnd?: () => void;+};++type Participation = {+ callId: string;+ options: RingParticipationOptions;+ state: 'audible' | 'suppressed';+ /** This tab's own claim while audible. */+ claim: { claimedAt: number; audible: boolean } | null;+ deadline: number;+ lastDefendedAt: number;+ ended: boolean;+ tickIntervalId: number | undefined;+};++const trackedClaims = new Map<string, TrackedClaim>();+const silencedCallIds = new Set<string>();+const participations = new Map<string, Participation>();++/**+ * Whether audio playback is likely blocked by the browser's autoplay policy.+ * A tab the user has never interacted with (opened in the background and+ * never focused) typically cannot start an AudioContext, so its ring would+ * be silent. Treated as capable when the API is unavailable.+ */+function isAudioLikelyBlocked(): boolean {+ if (typeof navigator === 'undefined') return false;+ const { userActivation } = navigator as Navigator & {+ userActivation?: { hasBeenActive?: boolean };+ };+ return userActivation ? userActivation.hasBeenActive === false : false;+}++/** Negative when `a` outranks `b`. Total order: audible, oldest, tab id. */+function compareClaims(+ a: { audible: boolean; claimedAt: number; tabId: string },+ b: { audible: boolean; claimedAt: number; tabId: string }+): number {+ if (a.audible !== b.audible) return a.audible ? -1 : 1;+ if (a.claimedAt !== b.claimedAt) return a.claimedAt - b.claimedAt;+ return a.tabId < b.tabId ? -1 : a.tabId > b.tabId ? 1 : 0;+}++function getLiveClaim(callId: string, now: number): TrackedClaim | undefined {+ const claim = trackedClaims.get(callId);+ if (!claim) return undefined;+ if (now - claim.lastSeenAt > CLAIM_TTL_MS) return undefined;+ // Never treat this tab's own residue as a live competitor.+ if (claim.tabId === tabId) return undefined;+ return claim;+}++function invokeCallback(callback: (() => void) | undefined, label: string) {+ try {+ callback?.();+ } catch (error) {+ console.error(`Ring participation ${label} callback failed`, error);+ }+}++function publishClaim(participation: Participation, now: number) {+ const { claim } = participation;+ if (!claim) return;+ trackedClaims.set(participation.callId, {+ tabId,+ claimedAt: claim.claimedAt,+ audible: claim.audible,+ lastSeenAt: now,+ });+ evictOldest(trackedClaims, MAX_TRACKED_CALLS);+ ringBus.publish({+ type: 'claim',+ callId: participation.callId,+ tabId,+ claimedAt: claim.claimedAt,+ audible: claim.audible,+ sentAt: now,+ });+}++function acquire(participation: Participation, now: number) {+ participation.state = 'audible';+ participation.claim = { claimedAt: now, audible: !isAudioLikelyBlocked() };+ publishClaim(participation, now);+ invokeCallback(participation.options.onAcquire, 'onAcquire');+}++function demote(participation: Participation) {+ if (participation.state !== 'audible') return;+ participation.state = 'suppressed';+ participation.claim = null;+ invokeCallback(participation.options.onRelease, 'onRelease');+}++function endParticipation(participation: Participation) {+ if (participation.ended) return;+ participation.ended = true;++ if (participation.tickIntervalId !== undefined) {+ window.clearInterval(participation.tickIntervalId);+ }+ if (participations.get(participation.callId) === participation) {+ participations.delete(participation.callId);+ }+ if (trackedClaims.get(participation.callId)?.tabId === tabId) {+ trackedClaims.delete(participation.callId);+ }+ demote(participation);+ invokeCallback(participation.options.onEnd, 'onEnd');+}++/**+ * Claims the ring if this tab would win the election against the best claim+ * currently known to be live; stays suppressed otherwise.+ */+function maybeClaim(participation: Participation, now: number) {+ const best = getLiveClaim(participation.callId, now);+ if (+ best &&+ compareClaims(best, {+ tabId,+ claimedAt: now,+ audible: !isAudioLikelyBlocked(),+ }) < 0+ ) {+ return;+ }+ acquire(participation, now);+}++function tick(participation: Participation) {+ const now = Date.now();+ if (+ now >= participation.deadline ||+ silencedCallIds.has(participation.callId) ||+ participation.options.shouldStop()+ ) {+ endParticipation(participation);+ return;+ }++ if (participation.state === 'audible') {+ publishClaim(participation, now);+ } else {+ maybeClaim(participation, now);+ }+}++function handleClaimMessage(message: RingClaimMessage) {+ if (message.tabId === tabId) return;+ const now = Date.now();++ const existing = trackedClaims.get(message.callId);+ const incoming: TrackedClaim = {+ tabId: message.tabId,+ claimedAt: message.claimedAt,+ audible: message.audible,+ lastSeenAt: now,+ };+ // Track the incoming claim when it is the first one seen, supersedes the+ // sender's own earlier claim (heartbeats included), replaces an expired+ // claim, or outranks the current one.+ if (+ !existing ||+ existing.tabId === incoming.tabId ||+ now - existing.lastSeenAt > CLAIM_TTL_MS ||+ compareClaims(incoming, existing) < 0+ ) {+ trackedClaims.set(message.callId, incoming);+ evictOldest(trackedClaims, MAX_TRACKED_CALLS);+ }++ const participation = participations.get(message.callId);+ if (!participation || participation.state !== 'audible') return;+ const ownClaim = participation.claim;+ if (!ownClaim) return;++ if (compareClaims(incoming, { tabId, ...ownClaim }) < 0) {+ demote(participation);+ return;+ }++ // A losing claim while we ring is a takeover attempt from a tab that+ // mistook us for dead (e.g. our heartbeats got throttled). Re-assert the+ // claim immediately so the usurper stands down.+ if (now - participation.lastDefendedAt >= CLAIM_DEFENSE_MIN_INTERVAL_MS) {+ participation.lastDefendedAt = now;+ publishClaim(participation, now);+ }+}++function handleSilenceMessage(message: RingSilenceMessage) {+ silencedCallIds.add(message.callId);+ evictOldest(silencedCallIds, MAX_SILENCED_CALLS);+ const participation = participations.get(message.callId);+ if (participation) endParticipation(participation);+}++function handleReleaseMessage(message: RingReleaseMessage) {+ if (trackedClaims.get(message.callId)?.tabId === message.tabId) {+ trackedClaims.delete(message.callId);+ }+ const participation = participations.get(message.callId);+ if (participation && participation.state === 'suppressed') {+ maybeClaim(participation, Date.now());+ }+}++function handleRingMessage(message: RingMessage) {+ match(message)+ .with({ type: 'claim' }, handleClaimMessage)+ .with({ type: 'silence' }, handleSilenceMessage)+ .with({ type: 'release' }, handleReleaseMessage)+ .exhaustive();+}++function handlePageHide() {+ // Orderly tab close: hand the ring to a surviving tab immediately instead+ // of making it wait out the claim TTL. Participations are also ended so a+ // page restored from the back/forward cache does not resume a stale ring.+ for (const participation of [...participations.values()]) {+ if (participation.state === 'audible') {+ ringBus.publish({+ type: 'release',+ callId: participation.callId,+ tabId,+ sentAt: Date.now(),+ });+ }+ endParticipation(participation);+ }+}++let isRingCoordinationAttached = false;++/**+ * Attaches the cross-tab listeners once for the lifetime of the tab. The+ * APIs below call it lazily, but call it at app mount (`CallStartedNotifier`+ * does) so sibling tabs' claims are already recorded by the time this tab's+ * own `call_started` event arrives.+ */+export function attachRingCoordination() {+ if (isRingCoordinationAttached || typeof window === 'undefined') return;+ isRingCoordinationAttached = true;+ ringBus.subscribe(handleRingMessage);+ window.addEventListener('pagehide', handlePageHide);+}++/**+ * Joins the cross-tab election for ringing `callId`. `onAcquire` fires when+ * this tab should make noise and `onRelease` when it should stop; a+ * suppressed participant stays ready to take the ring over until the call+ * resolves, the ring is silenced, or `maxDurationMs` elapses.+ */+export function participateInRing(+ options: RingParticipationOptions+): RingParticipation {+ attachRingCoordination();++ const existing = participations.get(options.callId);+ if (existing) endParticipation(existing);++ const now = Date.now();+ const participation: Participation = {+ callId: options.callId,+ options,+ state: 'suppressed',+ claim: null,+ deadline: now + options.maxDurationMs,+ lastDefendedAt: 0,+ ended: false,+ tickIntervalId: undefined,+ };++ // Silenced or already-stopped calls never ring; end before registering so+ // no timers or claims are created.+ if (silencedCallIds.has(options.callId) || options.shouldStop()) {+ participation.ended = true;+ invokeCallback(options.onEnd, 'onEnd');+ return { stop: () => {} };+ }++ participations.set(options.callId, participation);+ maybeClaim(participation, now);+ participation.tickIntervalId = window.setInterval(+ () => tick(participation),+ CLAIM_HEARTBEAT_INTERVAL_MS+ );++ return { stop: () => endParticipation(participation) };+}++/**+ * Silences the audible ringer for a call in every tab on this machine (the+ * user dismissed the incoming-call toast or widget). Visual affordances are+ * untouched — tabs keep their toasts and widgets; only the noise stops, and+ * no tab takes the ring over afterwards. Ringing on other devices is+ * unaffected; that resolves through call resolutions instead.+ */+export function silenceIncomingCallRing(callId: string) {+ attachRingCoordination();+ ringBus.publish({ type: 'silence', callId, sentAt: Date.now() });+}diff --git a/apps/web/src/features/channel/Call/tests/ring-coordination.test.ts b/apps/web/src/features/channel/Call/tests/ring-coordination.test.tsnew file mode 100644index 0000000000..e6c7d27532--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/ring-coordination.test.ts@@ -0,0 +1,325 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++class MockBroadcastChannel {+ static instance: MockBroadcastChannel | undefined;++ readonly postMessage = vi.fn();+ private messageHandler: ((event: { data: unknown }) => void) | undefined;++ constructor(readonly name: string) {+ MockBroadcastChannel.instance = this;+ }++ addEventListener(_type: string, handler: (event: { data: unknown }) => void) {+ this.messageHandler = handler;+ }++ emit(data: unknown) {+ this.messageHandler?.({ data });+ }+}++type PublishedMessage = { type: string; [key: string]: unknown };++function publishedMessages(type?: string): PublishedMessage[] {+ const calls = MockBroadcastChannel.instance?.postMessage.mock.calls ?? [];+ const messages = calls.map(([message]) => message as PublishedMessage);+ return type ? messages.filter((message) => message.type === type) : messages;+}++function foreignClaim(overrides: Partial<Record<string, unknown>> = {}) {+ return {+ type: 'claim',+ callId: 'call-1',+ // Strictly earlier than any claim made under the frozen test clock, so+ // the foreign tab deterministically wins ties.+ claimedAt: Date.now() - 1_000,+ tabId: 'other-tab',+ audible: true,+ sentAt: Date.now(),+ ...overrides,+ };+}++async function importRingCoordination() {+ return await import('../ring-coordination');+}++function createParticipant(+ module: Awaited<ReturnType<typeof importRingCoordination>>,+ overrides: Partial<Parameters<typeof module.participateInRing>[0]> = {}+) {+ const callbacks = {+ onAcquire: vi.fn(),+ onRelease: vi.fn(),+ onEnd: vi.fn(),+ };+ const participation = module.participateInRing({+ callId: 'call-1',+ shouldStop: () => false,+ maxDurationMs: 30_000,+ ...callbacks,+ ...overrides,+ });+ return { participation, ...callbacks };+}++describe('ring coordination', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(100_000);+ localStorage.clear();+ MockBroadcastChannel.instance = undefined;+ vi.resetModules();+ vi.stubGlobal('BroadcastChannel', MockBroadcastChannel);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it('elects the sole participant immediately and heartbeats its claim', async () => {+ const module = await importRingCoordination();+ const { onAcquire } = createParticipant(module);++ expect(onAcquire).toHaveBeenCalledTimes(1);+ const [claim] = publishedMessages('claim');+ expect(claim).toMatchObject({+ callId: 'call-1',+ claimedAt: 100_000,+ audible: true,+ });+ expect(+ JSON.parse(localStorage.getItem('macro.call-ring') ?? '')+ ).toMatchObject({ type: 'claim', callId: 'call-1' });++ await vi.advanceTimersByTimeAsync(2_000);+ const claims = publishedMessages('claim');+ expect(claims).toHaveLength(3);+ // Heartbeats keep the election key stable while staying unique on the+ // storage transport.+ expect(claims[2]).toMatchObject({ claimedAt: 100_000, sentAt: 102_000 });+ });++ it('stays suppressed while another tab holds a live claim', async () => {+ const module = await importRingCoordination();+ module.attachRingCoordination();+ MockBroadcastChannel.instance?.emit(foreignClaim());++ const { onAcquire, onEnd } = createParticipant(module);++ expect(onAcquire).not.toHaveBeenCalled();+ expect(publishedMessages()).toHaveLength(0);++ await vi.advanceTimersByTimeAsync(2_000);+ expect(onAcquire).not.toHaveBeenCalled();+ expect(onEnd).not.toHaveBeenCalled();+ });++ it('records claims arriving over the storage fallback', async () => {+ const module = await importRingCoordination();+ module.attachRingCoordination();+ window.dispatchEvent(+ new StorageEvent('storage', {+ key: 'macro.call-ring',+ newValue: JSON.stringify(foreignClaim()),+ })+ );++ const { onAcquire } = createParticipant(module);+ expect(onAcquire).not.toHaveBeenCalled();+ });++ it('outranks a claim from a tab that cannot make noise', async () => {+ const module = await importRingCoordination();+ module.attachRingCoordination();+ MockBroadcastChannel.instance?.emit(+ foreignClaim({ audible: false, claimedAt: 99_000 })+ );++ const { onAcquire } = createParticipant(module);++ expect(onAcquire).toHaveBeenCalledTimes(1);+ expect(publishedMessages('claim')[0]).toMatchObject({ audible: true });+ });++ it('defers to an audibly-capable tab when this tab has no user activation', async () => {+ const originalDescriptor = Object.getOwnPropertyDescriptor(+ window.navigator,+ 'userActivation'+ );+ Object.defineProperty(window.navigator, 'userActivation', {+ value: { hasBeenActive: false },+ configurable: true,+ });++ try {+ const module = await importRingCoordination();+ module.attachRingCoordination();+ // Our own claim would be `audible: false`, so a later audible claim+ // from a sibling still wins.+ const { onAcquire, onRelease } = createParticipant(module);+ expect(onAcquire).toHaveBeenCalledTimes(1);+ expect(publishedMessages('claim')[0]).toMatchObject({ audible: false });++ MockBroadcastChannel.instance?.emit(foreignClaim({ claimedAt: 100_500 }));+ expect(onRelease).toHaveBeenCalledTimes(1);+ } finally {+ if (originalDescriptor) {+ Object.defineProperty(+ window.navigator,+ 'userActivation',+ originalDescriptor+ );+ } else {+ Reflect.deleteProperty(window.navigator, 'userActivation');+ }+ }+ });++ it('yields to an earlier claim, then takes the ring back once it goes stale', async () => {+ const module = await importRingCoordination();+ const { onAcquire, onRelease, onEnd } = createParticipant(module);+ expect(onAcquire).toHaveBeenCalledTimes(1);++ MockBroadcastChannel.instance?.emit(foreignClaim({ claimedAt: 99_500 }));+ expect(onRelease).toHaveBeenCalledTimes(1);++ // The foreign tab dies silently: no heartbeats. Once its claim exceeds+ // the TTL the suppressed participant re-elects itself.+ await vi.advanceTimersByTimeAsync(5_000);+ expect(onAcquire).toHaveBeenCalledTimes(2);+ const claims = publishedMessages('claim');+ expect(claims.at(-1)?.claimedAt).toBeGreaterThan(100_000);+ expect(onEnd).not.toHaveBeenCalled();+ });++ it('defends its claim against a losing takeover attempt', async () => {+ const module = await importRingCoordination();+ const { onRelease } = createParticipant(module);+ const claimsBefore = publishedMessages('claim').length;++ MockBroadcastChannel.instance?.emit(foreignClaim({ claimedAt: 101_000 }));++ expect(onRelease).not.toHaveBeenCalled();+ // An immediate re-publish tells the usurper the claim is still live.+ expect(publishedMessages('claim')).toHaveLength(claimsBefore + 1);+ });++ it('hands the ring over immediately when the audible tab releases it', async () => {+ const module = await importRingCoordination();+ module.attachRingCoordination();+ MockBroadcastChannel.instance?.emit(foreignClaim());++ const { onAcquire } = createParticipant(module);+ expect(onAcquire).not.toHaveBeenCalled();++ MockBroadcastChannel.instance?.emit({+ type: 'release',+ callId: 'call-1',+ tabId: 'other-tab',+ sentAt: Date.now(),+ });+ expect(onAcquire).toHaveBeenCalledTimes(1);+ });++ it('silence stops the audible ring and prevents any takeover', async () => {+ const module = await importRingCoordination();+ const { onRelease, onEnd } = createParticipant(module);++ MockBroadcastChannel.instance?.emit({+ type: 'silence',+ callId: 'call-1',+ sentAt: Date.now(),+ });+ expect(onRelease).toHaveBeenCalledTimes(1);+ expect(onEnd).toHaveBeenCalledTimes(1);++ // A silenced call never rings again in this tab, even without any live+ // competing claim.+ const late = createParticipant(module);+ expect(late.onAcquire).not.toHaveBeenCalled();+ expect(late.onEnd).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(late.onAcquire).not.toHaveBeenCalled();+ });++ it('silenceIncomingCallRing publishes and stops the local ringer', async () => {+ const module = await importRingCoordination();+ const { onRelease, onEnd } = createParticipant(module);++ module.silenceIncomingCallRing('call-1');++ expect(onRelease).toHaveBeenCalledTimes(1);+ expect(onEnd).toHaveBeenCalledTimes(1);+ expect(publishedMessages('silence')).toHaveLength(1);+ expect(+ JSON.parse(localStorage.getItem('macro.call-ring') ?? '')+ ).toMatchObject({ type: 'silence', callId: 'call-1' });+ });++ it('stop() is local-only so siblings can take the ring over', async () => {+ const module = await importRingCoordination();+ const { participation, onRelease, onEnd } = createParticipant(module);++ participation.stop();++ expect(onRelease).toHaveBeenCalledTimes(1);+ expect(onEnd).toHaveBeenCalledTimes(1);+ expect(publishedMessages('silence')).toHaveLength(0);+ expect(publishedMessages('release')).toHaveLength(0);++ // No further heartbeats: the claim is left to go stale.+ const claims = publishedMessages('claim').length;+ await vi.advanceTimersByTimeAsync(5_000);+ expect(publishedMessages('claim')).toHaveLength(claims);+ });++ it('ends participation at the ring deadline', async () => {+ const module = await importRingCoordination();+ const { onRelease, onEnd } = createParticipant(module, {+ maxDurationMs: 3_000,+ });++ await vi.advanceTimersByTimeAsync(3_000);++ expect(onRelease).toHaveBeenCalledTimes(1);+ expect(onEnd).toHaveBeenCalledTimes(1);+ const claims = publishedMessages('claim').length;+ await vi.advanceTimersByTimeAsync(3_000);+ expect(publishedMessages('claim')).toHaveLength(claims);+ });++ it('ends a suppressed participation instead of taking over once shouldStop flips', async () => {+ const module = await importRingCoordination();+ module.attachRingCoordination();+ MockBroadcastChannel.instance?.emit(foreignClaim());++ let stopped = false;+ const { onAcquire, onEnd } = createParticipant(module, {+ shouldStop: () => stopped,+ });+ stopped = true;++ // The foreign claim goes stale, but the participant must not ring for a+ // call the user already joined.+ await vi.advanceTimersByTimeAsync(6_000);+ expect(onAcquire).not.toHaveBeenCalled();+ expect(onEnd).toHaveBeenCalledTimes(1);+ });++ it('releases the ring on pagehide so survivors take over instantly', async () => {+ const module = await importRingCoordination();+ const { onRelease, onEnd } = createParticipant(module);++ window.dispatchEvent(new Event('pagehide'));++ expect(onRelease).toHaveBeenCalledTimes(1);+ expect(onEnd).toHaveBeenCalledTimes(1);+ expect(publishedMessages('release')).toHaveLength(1);+ expect(publishedMessages('release')[0]).toMatchObject({+ callId: 'call-1',+ });+ });+});diff --git a/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsx b/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsxindex 19fc265df9..6647bf3269 100644--- a/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsx+++ b/apps/web/src/features/notifications/components/PlatformNotificationProvider.tsx@@ -1,3 +1,4 @@+import { createTabLeaderSignal } from '@core/cross-tab/tab-leader';import { makePersisted } from '@solid-primitives/storage';import {type Accessor,@@ -8,7 +9,6 @@ import {type Setter,useContext,} from 'solid-js';-import { createTabLeaderSignal } from '../notification-election';import type {PlatformNotificationData,PlatformNotificationHandle,diff --git a/apps/web/src/features/notifications/index.ts b/apps/web/src/features/notifications/index.tsindex 662acd15d6..4cb6ad44c6 100644--- a/apps/web/src/features/notifications/index.ts+++ b/apps/web/src/features/notifications/index.ts@@ -16,7 +16,6 @@ export {usePlatformNotificationState,} from './components/PlatformNotificationProvider';export { NotificationsPlayground } from './components/Playground';-export { createTabLeaderSignal } from './notification-election';export {createEffectOnEntityTypeNotification,entityHasUnreadNotifications,diff --git a/apps/web/src/features/notifications/notification-election.ts b/apps/web/src/features/notifications/notification-election.tsdeleted file mode 100644index 3ba0700373..0000000000--- a/apps/web/src/features/notifications/notification-election.ts+++ /dev/null@@ -1,21 +0,0 @@-import { type Accessor, createSignal, onCleanup } from 'solid-js';-import { Tab } from 'tab-election';--export const createTabLeaderSignal = (namespace: string): Accessor<boolean> => {- const [isLeader, setIsLeader] = createSignal<boolean>(false);- const tab = new Tab(namespace);-- tab.waitForLeadership(() => {- setIsLeader(true);-- return () => {- setIsLeader(false);- };- });-- onCleanup(() => {- tab.close();- });-- return isLeader;-};diff --git a/apps/web/src/lib/core/auth/channel.ts b/apps/web/src/lib/core/auth/channel.tsdeleted file mode 100644index faa6536d20..0000000000--- a/apps/web/src/lib/core/auth/channel.ts+++ /dev/null@@ -1,81 +0,0 @@-import {- broadcastChannels,- setBroadcastChannels,-} from '@app/signal/broadcastChannels';-import { err, ok, ResultAsync } from 'neverthrow';--const AUTH_CHANNEL = 'auth';-const LOGIN_SUCCESS = 'login-success';--/**- * Gets or creates a broadcast channel for the authentication process.- *- * @returns The broadcast channel.- */-function getOrCreateAuthChannel(): BroadcastChannel {- let channel = broadcastChannels().get(AUTH_CHANNEL);- if (!channel) {- channel = new BroadcastChannel(AUTH_CHANNEL);- setBroadcastChannels(broadcastChannels().set(AUTH_CHANNEL, channel));- }- return channel;-}--function _waitForAuthSuccess(channel: BroadcastChannel): Promise<void> {- return new Promise((resolve) => {- channel.onmessage = (event) => {- if (event.data.type === LOGIN_SUCCESS) {- resolve();- }- };- });-}--/** Errot type for a promise timing out. */-export type TimeoutError = { tag: 'TimeoutError'; message: string };--/**- * Waits for the auth success message to be received on the given channel.- *- * @param channel The channel to wait for the message on.- * @param timeout The timeout in milliseconds.- * @returns A promise that resolves when the auth success message is received.- */-function waitForAuthSuccessOrTimeout(- channel: BroadcastChannel,- timeout: number-): ResultAsync<void, TimeoutError> {- return new ResultAsync(- new Promise((resolve) => {- const timeoutId = setTimeout(() => {- resolve(- err({- tag: 'TimeoutError',- message: 'Timeout waiting for auth success',- })- );- }, timeout);-- channel.onmessage = (event) => {- if (event.data.type === LOGIN_SUCCESS) {- clearTimeout(timeoutId);- resolve(ok(undefined));- }- };- })- );-}--const AUTH_TIMEOUT = 60_000;-/**- * Waits for the auth success message to be received on the channel.- *- * @returns A promise that resolves when the auth success message is received.- */-export function authenticateWithEmailPermissions(): ResultAsync<- void,- TimeoutError-> {- const channel = getOrCreateAuthChannel();- return waitForAuthSuccessOrTimeout(channel, AUTH_TIMEOUT);-}diff --git a/apps/web/src/lib/core/auth/login-events.ts b/apps/web/src/lib/core/auth/login-events.tsnew file mode 100644index 0000000000..fa505e064e--- /dev/null+++ b/apps/web/src/lib/core/auth/login-events.ts@@ -0,0 +1,30 @@+import { createCrossTabBus } from '@core/cross-tab/cross-tab-bus';+import { match } from 'ts-pattern';++type LoginSuccessMessage = {+ type: 'login-success';+ /**+ * Publish time. Makes each payload unique so the bus's storage fallback+ * fires (see `cross-tab-bus.ts`). Optional so payloads from tabs still on+ * a pre-bus bundle, which omit it, parse.+ */+ sentAt?: number;+};++const authBus = createCrossTabBus<LoginSuccessMessage>({+ channelName: 'auth',+ storageKey: 'macro.auth-login-success',+ parse: (value) =>+ match(value)+ .with({ type: 'login-success' }, ({ type }) => ({ type }))+ .otherwise(() => null),+});++/**+ * Announces a completed login to sibling tabs, e.g. from the login popup or+ * an email-link callback page. Subscribe with `authBus` here if a waiter is+ * ever needed; today the channel is publish-only.+ */+export function publishLoginSuccess() {+ authBus.publish({ type: 'login-success', sentAt: Date.now() });+}diff --git a/apps/web/src/lib/core/cross-tab/cross-tab-bus.ts b/apps/web/src/lib/core/cross-tab/cross-tab-bus.tsnew file mode 100644index 0000000000..3ba092350e--- /dev/null+++ b/apps/web/src/lib/core/cross-tab/cross-tab-bus.ts@@ -0,0 +1,143 @@+/**+ * Minimal cross-tab message bus: BroadcastChannel is the primary transport,+ * with a localStorage `storage` event as fallback for embedded browsers+ * where BroadcastChannel is missing or unreliable.+ *+ * This is fan-out only — every subscribing tab sees every message. For a+ * long-lived "exactly one tab owns this job" responsibility use the+ * lock-based election in `tab-leader.ts` instead; an election that needs+ * custom ranking or mid-flight takeover builds its own protocol on this bus+ * (see `features/channel/Call/ring-coordination.ts`).+ *+ * Hand-rolled rather than `@solid-primitives/broadcast-channel`: the+ * primitive constructs `BroadcastChannel` unguarded (it would throw in+ * exactly the environments the fallback exists for) and ties the channel's+ * lifetime to a reactive owner, while publishes happen from async owner-less+ * contexts and the subscriber registry must outlive any subscribing+ * component.+ *+ * Caveat of the storage fallback: writing a byte-identical value does not+ * mutate storage, so the browser fires no `storage` event for it. Messages+ * that are re-published verbatim (e.g. heartbeats) must carry a field, such+ * as a fresh timestamp, that makes every publish unique.+ */++import { evictOldest } from '@core/util/evictOldest';++const MAX_HANDLED_MESSAGE_KEYS = 100;++export type CrossTabBus<TMessage> = {+ /** Delivers a message to this tab's subscribers and to sibling tabs. */+ publish: (message: TMessage) => void;+ /**+ * Subscribes to messages originating locally or in another tab. Returns+ * an unsubscribe function.+ */+ subscribe: (handler: (message: TMessage) => void) => () => void;+};++export function createCrossTabBus<TMessage>(options: {+ /** BroadcastChannel name shared by every tab on the origin. */+ channelName: string;+ /** localStorage key backing the fallback transport. */+ storageKey: string;+ /** Validates and narrows a raw payload; return null to drop it. */+ parse: (value: unknown) => TMessage | null;+ /**+ * Optional dedup key. A message whose key was already handled is dropped+ * (LRU-bounded), so one publish delivered by both transports is handled+ * once. Omit for buses whose handlers are idempotent on repeat delivery.+ */+ getMessageKey?: (message: TMessage) => string;+}): CrossTabBus<TMessage> {+ const { channelName, storageKey, parse, getMessageKey } = options;++ const handlers = new Set<(message: TMessage) => void>();+ const handledMessageKeys = new Set<string>();+ let broadcastChannel: BroadcastChannel | null | undefined;+ let isStorageListenerAttached = false;++ function emit(value: unknown) {+ const message = parse(value);+ if (!message) return;++ if (getMessageKey) {+ const key = getMessageKey(message);+ if (handledMessageKeys.has(key)) return;+ handledMessageKeys.add(key);+ evictOldest(handledMessageKeys, MAX_HANDLED_MESSAGE_KEYS);+ }++ for (const handler of handlers) {+ try {+ handler(message);+ } catch (error) {+ console.error(`Failed to handle ${channelName} message`, error);+ }+ }+ }++ function getBroadcastChannel() {+ if (broadcastChannel !== undefined) return broadcastChannel;+ if (typeof BroadcastChannel === 'undefined') {+ broadcastChannel = null;+ return broadcastChannel;+ }++ try {+ broadcastChannel = new BroadcastChannel(channelName);+ broadcastChannel.addEventListener('message', (event) => emit(event.data));+ } catch {+ broadcastChannel = null;+ }++ return broadcastChannel;+ }++ function handleStorage(event: StorageEvent) {+ if (event.key !== storageKey || !event.newValue) return;++ try {+ emit(JSON.parse(event.newValue));+ } catch {+ // Ignore malformed or stale values from older clients.+ }+ }++ function attachStorageListener() {+ if (isStorageListenerAttached || typeof window === 'undefined') return;+ window.addEventListener('storage', handleStorage);+ isStorageListenerAttached = true;+ }++ function publish(message: TMessage) {+ emit(message);++ try {+ getBroadcastChannel()?.postMessage(message);+ } catch {+ // The storage write below remains available as a cross-tab fallback.+ }++ try {+ localStorage.setItem(storageKey, JSON.stringify(message));+ } catch {+ // Storage can be disabled in private or embedded browser contexts —+ // there, even reading the `localStorage` global throws (a `typeof`+ // check would not catch that, since the global resolves but its+ // getter throws).+ }+ }++ function subscribe(handler: (message: TMessage) => void) {+ handlers.add(handler);+ getBroadcastChannel();+ attachStorageListener();++ return () => {+ handlers.delete(handler);+ };+ }++ return { publish, subscribe };+}diff --git a/apps/web/src/lib/core/cross-tab/tab-leader.ts b/apps/web/src/lib/core/cross-tab/tab-leader.tsnew file mode 100644index 0000000000..5006626d3e--- /dev/null+++ b/apps/web/src/lib/core/cross-tab/tab-leader.ts@@ -0,0 +1,33 @@+import { type Accessor, createSignal, onCleanup } from 'solid-js';+import { Tab } from 'tab-election';++/**+ * Long-lived cross-tab leader election, backed by `tab-election` (Web Locks+ * API + BroadcastChannel). At most one tab per `namespace` is leader at a+ * time, and leadership fails over automatically when the leader tab closes+ * or crashes.+ *+ * Leadership is first-come-first-served with no way to rank candidates or+ * displace a live leader, and it requires the Locks API. An election that+ * needs either property — e.g. preferring audibly-capable tabs, or working+ * in embedded browsers without locks — builds its own protocol on+ * `cross-tab-bus.ts` instead (see `features/channel/Call/ring-coordination.ts`).+ */+export const createTabLeaderSignal = (namespace: string): Accessor<boolean> => {+ const [isLeader, setIsLeader] = createSignal<boolean>(false);+ const tab = new Tab(namespace);++ tab.waitForLeadership(() => {+ setIsLeader(true);++ return () => {+ setIsLeader(false);+ };+ });++ onCleanup(() => {+ tab.close();+ });++ return isLeader;+};diff --git a/apps/web/src/lib/core/cross-tab/tests/cross-tab-bus.test.ts b/apps/web/src/lib/core/cross-tab/tests/cross-tab-bus.test.tsnew file mode 100644index 0000000000..cd1be32206--- /dev/null+++ b/apps/web/src/lib/core/cross-tab/tests/cross-tab-bus.test.ts@@ -0,0 +1,203 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createCrossTabBus } from '../cross-tab-bus';++class MockBroadcastChannel {+ static instance: MockBroadcastChannel | undefined;++ readonly postMessage = vi.fn();+ private messageHandler: ((event: { data: unknown }) => void) | undefined;++ constructor(readonly name: string) {+ MockBroadcastChannel.instance = this;+ }++ addEventListener(_type: string, handler: (event: { data: unknown }) => void) {+ this.messageHandler = handler;+ }++ emit(data: unknown) {+ this.messageHandler?.({ data });+ }+}++type TestMessage = { id: string; sentAt: number };++function parseTestMessage(value: unknown): TestMessage | null {+ if (typeof value !== 'object' || value === null) return null;+ const { id, sentAt } = value as { id?: unknown; sentAt?: unknown };+ return typeof id === 'string' && typeof sentAt === 'number'+ ? { id, sentAt }+ : null;+}++let busCount = 0;++/**+ * Each test gets its own channel/storage names: buses attach module-lifetime+ * listeners by design, so reusing names would leak deliveries across tests.+ */+function createTestBus(options?: {+ getMessageKey?: (message: TestMessage) => string;+}) {+ busCount += 1;+ const storageKey = `test.cross-tab-bus.${busCount}`;+ const bus = createCrossTabBus<TestMessage>({+ channelName: `test-cross-tab-bus-${busCount}`,+ storageKey,+ parse: parseTestMessage,+ getMessageKey: options?.getMessageKey,+ });+ return { bus, storageKey };+}++function dispatchStorageEvent(key: string, value: unknown) {+ window.dispatchEvent(+ new StorageEvent('storage', { key, newValue: JSON.stringify(value) })+ );+}++describe('createCrossTabBus', () => {+ beforeEach(() => {+ localStorage.clear();+ MockBroadcastChannel.instance = undefined;+ vi.stubGlobal('BroadcastChannel', MockBroadcastChannel);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('publishes to this tab and both cross-tab transports', () => {+ const { bus, storageKey } = createTestBus();+ const handler = vi.fn();+ bus.subscribe(handler);++ const message = { id: 'a', sentAt: 1 };+ bus.publish(message);++ expect(handler).toHaveBeenCalledWith(message);+ expect(MockBroadcastChannel.instance?.postMessage).toHaveBeenCalledWith(+ message+ );+ expect(localStorage.getItem(storageKey)).toBe(JSON.stringify(message));+ });++ it('delivers messages arriving over BroadcastChannel', () => {+ const { bus } = createTestBus();+ const handler = vi.fn();+ bus.subscribe(handler);++ MockBroadcastChannel.instance?.emit({ id: 'a', sentAt: 1 });++ expect(handler).toHaveBeenCalledWith({ id: 'a', sentAt: 1 });+ });++ it('delivers messages arriving over the storage fallback, keyed', () => {+ const { bus, storageKey } = createTestBus();+ const handler = vi.fn();+ bus.subscribe(handler);++ dispatchStorageEvent(storageKey, { id: 'a', sentAt: 1 });+ dispatchStorageEvent('some-other-key', { id: 'b', sentAt: 2 });++ expect(handler).toHaveBeenCalledTimes(1);+ expect(handler).toHaveBeenCalledWith({ id: 'a', sentAt: 1 });+ });++ it('handles a message delivered by both transports once when keyed', () => {+ const { bus, storageKey } = createTestBus({+ getMessageKey: (message) => message.id,+ });+ const handler = vi.fn();+ bus.subscribe(handler);++ MockBroadcastChannel.instance?.emit({ id: 'a', sentAt: 1 });+ dispatchStorageEvent(storageKey, { id: 'a', sentAt: 1 });++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('re-delivers repeat messages when no message key is configured', () => {+ const { bus } = createTestBus();+ const handler = vi.fn();+ bus.subscribe(handler);++ MockBroadcastChannel.instance?.emit({ id: 'a', sentAt: 1 });+ MockBroadcastChannel.instance?.emit({ id: 'a', sentAt: 1 });++ expect(handler).toHaveBeenCalledTimes(2);+ });++ it('drops payloads the parser rejects', () => {+ const { bus, storageKey } = createTestBus();+ const handler = vi.fn();+ bus.subscribe(handler);++ MockBroadcastChannel.instance?.emit({ unexpected: true });+ dispatchStorageEvent(storageKey, 'not-a-message');++ expect(handler).not.toHaveBeenCalled();+ });++ it('keeps delivering to other handlers when one throws', () => {+ const consoleError = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const { bus } = createTestBus();+ const throwingHandler = vi.fn(() => {+ throw new Error('boom');+ });+ const handler = vi.fn();+ bus.subscribe(throwingHandler);+ bus.subscribe(handler);++ MockBroadcastChannel.instance?.emit({ id: 'a', sentAt: 1 });++ expect(handler).toHaveBeenCalledWith({ id: 'a', sentAt: 1 });+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });++ it('stops delivering after unsubscribe', () => {+ const { bus } = createTestBus();+ const handler = vi.fn();+ const unsubscribe = bus.subscribe(handler);++ unsubscribe();+ MockBroadcastChannel.instance?.emit({ id: 'a', sentAt: 1 });++ expect(handler).not.toHaveBeenCalled();+ });++ it('publishes via storage alone when BroadcastChannel is unavailable', () => {+ vi.stubGlobal('BroadcastChannel', undefined);+ const { bus, storageKey } = createTestBus();+ const handler = vi.fn();+ bus.subscribe(handler);++ const message = { id: 'a', sentAt: 1 };+ bus.publish(message);++ expect(handler).toHaveBeenCalledWith(message);+ expect(localStorage.getItem(storageKey)).toBe(JSON.stringify(message));+ });++ it('still posts to BroadcastChannel when localStorage writes throw', () => {+ const { bus } = createTestBus();+ const handler = vi.fn();+ bus.subscribe(handler);+ vi.stubGlobal('localStorage', {+ setItem: () => {+ throw new Error('storage disabled');+ },+ });++ const message = { id: 'a', sentAt: 1 };+ expect(() => bus.publish(message)).not.toThrow();++ expect(handler).toHaveBeenCalledWith(message);+ expect(MockBroadcastChannel.instance?.postMessage).toHaveBeenCalledWith(+ message+ );+ });+});diff --git a/apps/web/src/lib/core/util/evictOldest.ts b/apps/web/src/lib/core/util/evictOldest.tsnew file mode 100644index 0000000000..63d200a33e--- /dev/null+++ b/apps/web/src/lib/core/util/evictOldest.ts@@ -0,0 +1,15 @@+/**+ * Evicts entries in insertion order until `collection` holds at most+ * `maxSize`. Set and Map iterate in insertion order, so this turns a plain+ * collection into a drop-oldest bounded cache.+ */+export function evictOldest<K>(+ collection: Set<K> | Map<K, unknown>,+ maxSize: number+) {+ while (collection.size > maxSize) {+ const next = collection.keys().next();+ if (next.done) break;+ collection.delete(next.value);+ }+}diff --git a/apps/web/src/lib/core/util/licenseUpdateBroadcastChannel.ts b/apps/web/src/lib/core/util/licenseUpdateBroadcastChannel.tsindex 266e87ad4e..9c04e5ce42 100644--- a/apps/web/src/lib/core/util/licenseUpdateBroadcastChannel.ts+++ b/apps/web/src/lib/core/util/licenseUpdateBroadcastChannel.ts@@ -1,14 +1,33 @@-const licenseUpdateChannel = new BroadcastChannel('license-update');+import { createCrossTabBus } from '@core/cross-tab/cross-tab-bus';+import { match } from 'ts-pattern';++type LicenseUpdateMessage = {+ type: 'license-updated';+ /**+ * Publish time. Makes each payload unique so the bus's storage fallback+ * fires (see `cross-tab-bus.ts`). Optional only for consistency with the+ * other buses — this channel had no publishers before the bus migration+ * (the legacy string interface was never called), so unlike the favicon+ * and login-success buses there is no older payload shape to accept.+ */+ sentAt?: number;+};++const licenseBus = createCrossTabBus<LicenseUpdateMessage>({+ channelName: 'license-update',+ storageKey: 'macro.license-update',+ parse: (value) =>+ match(value)+ .with({ type: 'license-updated' }, ({ type }) => ({ type }))+ .otherwise(() => null),+});/*** utility interface for sending license update events across browser tabs without need to ipc (more direct)*/export const licenseChannel = {- subscribe: (handler: () => void) => {- licenseUpdateChannel.addEventListener('message', handler);- return () => licenseUpdateChannel.removeEventListener('message', handler);- },+ subscribe: (handler: () => void) => licenseBus.subscribe(handler),post: () => {- licenseUpdateChannel.postMessage('license updated');+ licenseBus.publish({ type: 'license-updated', sentAt: Date.now() });},};diff --git a/apps/web/src/lib/queries/soup/backfill.ts b/apps/web/src/lib/queries/soup/backfill.tsindex 0ab85936a0..31698f3a85 100644--- a/apps/web/src/lib/queries/soup/backfill.ts+++ b/apps/web/src/lib/queries/soup/backfill.ts@@ -1,5 +1,5 @@import { ENABLE_GRAPHQL_BACKFILL } from '@core/constant/featureFlags';-import { createTabLeaderSignal } from '@notifications/notification-election';+import { createTabLeaderSignal } from '@core/cross-tab/tab-leader';import { SoupBackfillDocument } from '@service-storage/graphql/generated/graphql';import {type FetchGraphqlSoupOptions,diff --git a/apps/web/src/lib/signals/broadcastChannels.ts b/apps/web/src/lib/signals/broadcastChannels.tsdeleted file mode 100644index 7c931cd434..0000000000--- a/apps/web/src/lib/signals/broadcastChannels.ts+++ /dev/null@@ -1,5 +0,0 @@-import { createSignal } from 'solid-js';--export const [broadcastChannels, setBroadcastChannels] = createSignal<- Map<string, BroadcastChannel>->(new Map<string, BroadcastChannel>());diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex 410104e69b..4fd30aa106 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -32,6 +32,7 @@ import { GlobalAppStateProvider } from '@components/app/GlobalAppState';import { Layout } from '@components/app/Layout';import { ReactiveFavicon } from '@components/app/ReactiveFavicon';import { LAYOUT_ROUTE } from '@components/app/split-layout/SplitLayoutRoute';+import { publishLoginSuccess } from '@core/auth/login-events';import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';import { LoadingBlock } from '@core/component/LoadingBlock';import { ToastRegion } from '@core/component/Toast/ToastRegion';@@ -297,16 +298,12 @@ const ROUTES: RouteDefinition[] = [{path: '/login/popup/success',component: () => {- const channel = new BroadcastChannel('auth');-onMount(() => {- channel.postMessage({ type: 'login-success' });- channel.close();+ publishLoginSuccess();window.close();});onCleanup(() => {- channel.close();window.close();});@@ -316,8 +313,7 @@ const ROUTES: RouteDefinition[] = [<Buttonvariant="base"onClick={() => {- channel.postMessage({ type: 'login-success' });- channel.close();+ publishLoginSuccess();window.close();}}>diff --git a/bun.lock b/bun.lockindex 3318bae185..f42abea8a3 100644--- a/bun.lock+++ b/bun.lock@@ -55,7 +55,6 @@"@opentelemetry/api": "^1.9.1","@phosphor-icons/core": "^2.1.1","@pierre/diffs": "^1.3.5",- "@solid-primitives/broadcast-channel": "^0.1.1","@solid-primitives/context": "^0.3.2","@solid-primitives/event-bus": "^1.1.2","@solid-primitives/keyed": "^1.5.3",@@ -1427,8 +1426,6 @@"@smithy/util-utf8": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],- "@solid-primitives/broadcast-channel": ["@solid-primitives/[email protected]", "", { "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-7wjQvY320E8elCcuruoJJohDHLzw6l7tAvHXZez5FAolb9BGsk3sPJ9wKDHsdRx0ww2cPg8GeUrGFdJ+5CnCxA=="],-"@solid-primitives/context": ["@solid-primitives/[email protected]", "", { "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-6fvTtpK17PFHnUf/UOc1TzBjd+kLFjtA62aRFEm1kDP9ufTo7FYW2kUzQAWbfbRHi30yjBJtopbR8qd6nShwyg=="],"@solid-primitives/event-bus": ["@solid-primitives/[email protected]", "", { "dependencies": { "@solid-primitives/utils": "^6.4.1" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-5aYvB/kLiWhL6TmpH/QvFRjwIArknEEHDzxA7hvnJZ+/BFixGeB7yqWEJORYeig7kOzC+XqUbjDmpJhHriP4EA=="],diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.jsonindex 75870beb4f..27772b187a 100644--- a/nix-support/node_modules-hashes.json+++ b/nix-support/node_modules-hashes.json@@ -1,6 +1,6 @@{"nodeModules": {- "aarch64-darwin": "sha256-G+0YuImb+ULJX59bZdUICCQiewNQ4N5csROrt6VmuI4=",- "x86_64-linux": "sha256-pm/7bLHzRNqi4Qw0axp3TIAf9SKfSVBnvJYPVC+dnPA="+ "aarch64-darwin": "sha256-ms6ZphoQP1awt+QzGmjUXNUFoWzYQCqB1Iytden6X0o=",+ "x86_64-linux": "sha256-//19aldyGPEDNVGH5ZAmnuWC7R4znCni5A1wYqMdiT8="}-}\ No newline at end of file+}