Skip to content

armgit / macro

Public Imported from GitHub
0

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

perf: lazy livekit, krisp, pdfjs (#4732)

teo5df76e8e72aa
diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsx
index ecad6d1a6e..a1269512ef 100644
--- a/js/app/packages/app/component/Layout.tsx
+++ b/js/app/packages/app/component/Layout.tsx
@@ -12,7 +12,8 @@ import {
import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
import { mountGlobalFocusListener } from '@app/signal/focus';
import { AutomationComposer } from '@block-automation/component';
-import { InCallPanel, useCallContextOptional } from '@channel/Call';
+import { useCallContextOptional } from '@channel/Call/CallContext';
+import { InCallPanel } from '@channel/Call/InCallPanel';
import { useIsAuthenticated } from '@core/auth';
import { usePaywallState } from '@core/constant/PaywallState';
import { isSoloSettings } from '@core/constant/SettingsState';
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index 1c499d6904..3e6c5ced01 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -9,9 +9,9 @@ import { PosthogProvider, usePosthog } from '@app/lib/analytics/posthog';
import { trackSignupCompletion } from '@app/lib/analytics/signupCompletion';
import { setHotkeyRoot } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
-import { CallKitSync } from '@channel/Call';
import { CallProvider } from '@channel/Call/CallContext';
import { CallStartedNotifier } from '@channel/Call/CallStartedNotifier';
+import { CallKitSync } from '@channel/Call/use-callkit';
import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';
import { toast } from '@core/component/Toast/Toast';
import { ToastRegion } from '@core/component/Toast/ToastRegion';
diff --git a/js/app/packages/app/component/app-sidebar/active-call-widget.tsx b/js/app/packages/app/component/app-sidebar/active-call-widget.tsx
index 1d98768394..10926f0771 100644
--- a/js/app/packages/app/component/app-sidebar/active-call-widget.tsx
+++ b/js/app/packages/app/component/app-sidebar/active-call-widget.tsx
@@ -1,9 +1,7 @@
-import {
- joinChannelCall,
- openChannelCallTab,
- stopCallRinger,
- useCallContextOptional,
-} from '@channel/Call';
+import { useCallContextOptional } from '@channel/Call/CallContext';
+import { stopCallRinger } from '@channel/Call/CallStartedNotifier';
+import { joinChannelCall } from '@channel/Call/join-channel-call';
+import { openChannelCallTab } from '@channel/Call/open-channel-call-tab';
import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
import { useChannelsContext } from '@core/context/channels';
diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsx
index 74a40031c6..275d8ca375 100644
--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx
+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx
@@ -34,7 +34,8 @@ import { LIST_VIEW_PATHS, type ListView } from '@app/constants/list-views';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useHotkeyInterceptor } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
-import { InCallPanel, useCallContextOptional } from '@channel/Call';
+import { useCallContextOptional } from '@channel/Call/CallContext';
+import { InCallPanel } from '@channel/Call/InCallPanel';
import { useHasPaidAccess } from '@core/auth';
import { useLogout } from '@core/auth/logout';
import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index 98828fa172..0bdeaf5d82 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -12,7 +12,7 @@ import {
} from '@block-channel/utils/link';
import { URL_PARAMS as EMAIL_PARAMS } from '@block-email/constants';
import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
-import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
+import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/constants';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
import {
diff --git a/js/app/packages/app/vite.base.ts b/js/app/packages/app/vite.base.ts
index 6fc88e899a..a51c4e0a19 100644
--- a/js/app/packages/app/vite.base.ts
+++ b/js/app/packages/app/vite.base.ts
@@ -124,6 +124,10 @@ export const createAppViteConfig = (): UserConfigFn => {
input: {
app: resolve(__dirname, 'index.html'),
},
+ // KaTeX and PDF.js are now reachable through lazy boundaries. Let
+ // Rollup place them naturally; forcing named chunks hoists shared
+ // CommonJS helpers into those chunks and makes the entry preload
+ // otherwise-lazy code.
output: NO_MINIFY
? {
// remove hashes from output paths
@@ -131,19 +135,11 @@ export const createAppViteConfig = (): UserConfigFn => {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
- manualChunks: {
- katex: ['katex'],
- pdfjs: ['pdfjs-dist'],
- },
}
: {
format: 'es',
chunkFileNames: '[name]-[hash].js',
entryFileNames: '[name]-[hash].js',
- manualChunks: {
- katex: ['katex'],
- pdfjs: ['pdfjs-dist'],
- },
},
},
assetsInlineLimit: (filePath) => {
diff --git a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
index 666b740f37..5ce2b5903e 100644
--- a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
@@ -7,16 +7,14 @@ import { useNavigatedFromJK } from '@app/component/useNavigatedFromJK';
import { globalSplitManager } from '@app/signal/splitLayout';
import { URL_PARAMS } from '@block-channel/constants';
import { ChannelAttachmentsTab } from '@channel/Attachments/ChannelAttachmentsTab';
-import {
- CallEventSync,
- ChannelCallAutoJoin,
- ChannelCallButton,
- ChannelCallTab,
- getCallJoinTab,
- isNativeIosCallKitEnabled,
- useCall,
- useCallContextOptional,
-} from '@channel/Call';
+import { useCallContextOptional } from '@channel/Call/CallContext';
+import { CallEventSync } from '@channel/Call/CallEventSync';
+import { ChannelCallAutoJoin } from '@channel/Call/ChannelCallAutoJoin';
+import { ChannelCallButton } from '@channel/Call/ChannelCallButton';
+import { ChannelCallTab } from '@channel/Call/ChannelCallTab';
+import { getCallJoinTab } from '@channel/Call/call-tabs';
+import { useCall } from '@channel/Call/use-call';
+import { isNativeIosCallKitEnabled } from '@channel/Call/use-callkit';
import {
type ChannelHandle,
type ChannelMessagesStateSnapshot,
diff --git a/js/app/packages/block-pdf/constants.ts b/js/app/packages/block-pdf/constants.ts
new file mode 100644
index 0000000000..64e13c2095
--- /dev/null
+++ b/js/app/packages/block-pdf/constants.ts
@@ -0,0 +1,14 @@
+// Keep navigation metadata independent from the PDF viewer implementation so
+// lightweight consumers do not pull the viewer onto the startup path.
+export const URL_PARAMS = {
+ pageNumber: 'pdf_page_number',
+ yPos: 'pdf_page_y',
+ x: 'pdf_page_x',
+ width: 'pdf_width',
+ height: 'pdf_height',
+ annotationId: 'pdf_ann_id',
+ searchPage: 'pdf_search_page',
+ searchSnippet: 'pdf_search_snippet',
+ searchRawQuery: 'pdf_search_raw_query',
+ searchHighlightTerms: 'pdf_search_highlight_terms',
+} as const;
diff --git a/js/app/packages/block-pdf/definition.ts b/js/app/packages/block-pdf/definition.ts
index cdc10f96d9..ebfec6e271 100644
--- a/js/app/packages/block-pdf/definition.ts
+++ b/js/app/packages/block-pdf/definition.ts
@@ -9,7 +9,7 @@ import type { GetDocumentResponseDataViewLocation } from '@service-storage/gener
import { fetchBinary } from '@service-storage/util/fetchBinary';
import { err, ok } from 'neverthrow';
import type { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
-import BlockPdf from './component/Block';
+import { lazy } from 'solid-js';
import PdfJsWorker from './PdfViewer/pdfjs-worker?worker';
export const definition = defineBlock({
@@ -19,7 +19,7 @@ export const definition = defineBlock({
pdf: 'application/pdf',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
},
- component: BlockPdf,
+ component: lazy(() => import('./component/Block')),
liveTrackingEnabled: true,
async load(source, intent) {
if (source.type === 'dss') {
diff --git a/js/app/packages/block-pdf/signal/location.ts b/js/app/packages/block-pdf/signal/location.ts
index 05acf32104..e9f9b9d9c1 100644
--- a/js/app/packages/block-pdf/signal/location.ts
+++ b/js/app/packages/block-pdf/signal/location.ts
@@ -1,3 +1,4 @@
+import { URL_PARAMS } from '@block-pdf/constants';
import type { PDFViewer } from '@block-pdf/PdfViewer';
import {
FindState,
@@ -30,18 +31,7 @@ import {
viewerReadySignal,
} from './pdfViewer';
-export const URL_PARAMS = {
- pageNumber: 'pdf_page_number',
- yPos: 'pdf_page_y',
- x: 'pdf_page_x',
- width: 'pdf_width',
- height: 'pdf_height',
- annotationId: 'pdf_ann_id',
- searchPage: 'pdf_search_page',
- searchSnippet: 'pdf_search_snippet',
- searchRawQuery: 'pdf_search_raw_query',
- searchHighlightTerms: 'pdf_search_highlight_terms',
-} as const;
+export { URL_PARAMS };
export type LocationSearchParams = {
annotationId?: string;
diff --git a/js/app/packages/block-pdf/store/comments/freeComments.ts b/js/app/packages/block-pdf/store/comments/freeComments.ts
index 3e4813a90a..5b24bdcd5d 100644
--- a/js/app/packages/block-pdf/store/comments/freeComments.ts
+++ b/js/app/packages/block-pdf/store/comments/freeComments.ts
@@ -12,7 +12,10 @@ import type {
PdfRoot,
ViewerCommentType,
} from '@block-pdf/type/comments';
-import type { IPlaceable, IThreadPlaceable } from '@block-pdf/type/placeables';
+import {
+ type IThreadPlaceable,
+ isThreadPlaceable,
+} from '@block-pdf/type/placeables';
import { createBlockMemo } from '@core/block';
import { useUserId } from '@core/context/user';
import {
@@ -21,9 +24,7 @@ import {
sortComments,
} from '../commentsResource';
-export function isThreadPlaceable(x: IPlaceable): x is IThreadPlaceable {
- return x.payloadType === 'thread';
-}
+export { isThreadPlaceable };
const getThreadPlaceablePos = (
placeable: IThreadPlaceable,
diff --git a/js/app/packages/block-pdf/type/coParse.ts b/js/app/packages/block-pdf/type/coParse.ts
index e8c0f1da2c..2dad3637c0 100644
--- a/js/app/packages/block-pdf/type/coParse.ts
+++ b/js/app/packages/block-pdf/type/coParse.ts
@@ -1,10 +1,10 @@
-import { isThreadPlaceable } from '@block-pdf/store/comments/freeComments';
import { v7 as uuid7 } from 'uuid';
import { z } from 'zod';
import {
type IPlaceable,
IPlaceableSchema,
IPlaceableServerSchema,
+ isThreadPlaceable,
} from '../type/placeables';
import { type IBookmark, IBookmarkSchema } from './Bookmark';
diff --git a/js/app/packages/block-pdf/type/placeables.ts b/js/app/packages/block-pdf/type/placeables.ts
index da7f93777d..16cd88c7a9 100644
--- a/js/app/packages/block-pdf/type/placeables.ts
+++ b/js/app/packages/block-pdf/type/placeables.ts
@@ -202,3 +202,9 @@ export const IPlaceableSchema = PlaceableBaseSchema.and(IPayloadSchema).and(
z.object({ internalId: z.string() })
);
export const IPlaceableServerSchema = PlaceableBaseSchema.and(IPayloadSchema);
+
+export function isThreadPlaceable(
+ placeable: IPlaceable
+): placeable is IThreadPlaceable {
+ return placeable.payloadType === 'thread';
+}
diff --git a/js/app/packages/channel/Call/CallAudioSink.tsx b/js/app/packages/channel/Call/CallAudioSink.tsx
index 9b2ff6de8b..a8b072333f 100644
--- a/js/app/packages/channel/Call/CallAudioSink.tsx
+++ b/js/app/packages/channel/Call/CallAudioSink.tsx
@@ -1,6 +1,6 @@
-import { Track } from 'livekit-client';
import { For, Show } from 'solid-js';
import { useCallContext } from './CallContext';
+import { LK_TRACK_SOURCE } from './livekit-loader';
import { TrackView } from './TrackView';
/**
@@ -25,7 +25,7 @@ export function CallAudioSink() {
.filter((p) => !p.isAgent)
.map((p) => ({
id: p.identity,
- track: p.getTrackPublication(Track.Source.Microphone)?.track,
+ track: p.getTrackPublication(LK_TRACK_SOURCE.Microphone)?.track,
}));
};
diff --git a/js/app/packages/channel/Call/CallContext.tsx b/js/app/packages/channel/Call/CallContext.tsx
index 22d6e2bc80..937a9067f8 100644
--- a/js/app/packages/channel/Call/CallContext.tsx
+++ b/js/app/packages/channel/Call/CallContext.tsx
@@ -1,18 +1,14 @@
import { analytics } from '@app/lib/analytics';
-import {
- isKrispNoiseFilterSupported,
- KrispNoiseFilter,
-} from '@livekit/krisp-noise-filter';
+import type { KrispNoiseFilter } from '@livekit/krisp-noise-filter';
import type { BackgroundProcessorWrapper } from '@livekit/track-processors';
import type { CallTokenResponse } from '@service-call/client';
import { makePersisted } from '@solid-primitives/storage';
-import {
- type AudioCaptureOptions,
+import type {
+ AudioCaptureOptions,
ConnectionState,
- type LocalTrack,
- type RemoteParticipant,
+ LocalTrack,
+ RemoteParticipant,
Room,
- Track,
} from 'livekit-client';
import {
createContext,
@@ -28,12 +24,27 @@ import {
type CallSessionDisconnectOptions,
createCallSessionController,
} from './CallSessionController';
-import { createLivekitJsCallController } from './LivekitJsCallController';
+import {
+ getKrisp,
+ getLivekit,
+ isKrispSupported,
+ LK_CONNECTION_STATE,
+ LK_TRACK_SOURCE,
+ loadKrisp,
+ loadLivekit,
+} from './livekit-loader';
import {
type NativeCallConnectionState,
useMaybeNativeCallState,
} from './native-call-state';
+type LivekitJsCallController = ReturnType<
+ typeof import('./LivekitJsCallController')['createLivekitJsCallController']
+>;
+type LivekitJsCallControllerOptions = Parameters<
+ typeof import('./LivekitJsCallController')['createLivekitJsCallController']
+>[0];
+
export type CallParticipantInfo = {
identity: string;
isSpeaking: boolean;
@@ -110,7 +121,7 @@ function normalizeNoiseSuppressionMode(
function effectiveCaptureModeForPreferredMode(
mode: MicNoiseSuppressionMode
): MicNoiseSuppressionMode {
- if (mode === 'krisp' && !isKrispNoiseFilterSupported()) return 'browser';
+ if (mode === 'krisp' && !isKrispSupported()) return 'browser';
return mode;
}
@@ -177,16 +188,16 @@ function nativeAudioProcessingConstraints(
}
function getLocalMicTrack(r: Room): LocalTrack | undefined {
- return r.localParticipant.getTrackPublication(Track.Source.Microphone)
+ return r.localParticipant.getTrackPublication(LK_TRACK_SOURCE.Microphone)
?.track as LocalTrack | undefined;
}
function isActiveCallConnectionState(state: ConnectionState): boolean {
return (
- state === ConnectionState.Connecting ||
- state === ConnectionState.Connected ||
- state === ConnectionState.Reconnecting ||
- state === ConnectionState.SignalReconnecting
+ state === LK_CONNECTION_STATE.Connecting ||
+ state === LK_CONNECTION_STATE.Connected ||
+ state === LK_CONNECTION_STATE.Reconnecting ||
+ state === LK_CONNECTION_STATE.SignalReconnecting
);
}
@@ -214,11 +225,11 @@ async function applyNativeAudioProcessingToMicTrack(
// Swift exposes a transient `disconnecting` state that livekit-client lacks.
const NATIVE_TO_LIVEKIT_STATE = {
- disconnected: ConnectionState.Disconnected,
- connecting: ConnectionState.Connecting,
- connected: ConnectionState.Connected,
- reconnecting: ConnectionState.Reconnecting,
- disconnecting: ConnectionState.Disconnected,
+ disconnected: LK_CONNECTION_STATE.Disconnected,
+ connecting: LK_CONNECTION_STATE.Connecting,
+ connected: LK_CONNECTION_STATE.Connected,
+ reconnecting: LK_CONNECTION_STATE.Reconnecting,
+ disconnecting: LK_CONNECTION_STATE.Disconnected,
} satisfies Record<NativeCallConnectionState, ConnectionState>;
type CallStoreState = {
@@ -250,7 +261,7 @@ type CallStoreState = {
};
const initialState: CallStoreState = {
- connectionState: ConnectionState.Disconnected,
+ connectionState: LK_CONNECTION_STATE.Disconnected,
activeChannelId: null,
activeCallId: null,
remoteParticipants: new Map(),
@@ -503,7 +514,7 @@ function createCallState() {
event,
preferredMode: persistedNoiseSuppressionMode(),
activeMode: store.noiseSuppressionMode,
- krispSupported: isKrispNoiseFilterSupported(),
+ krispSupported: isKrispSupported(),
hasMicTrack: !!micTrack,
micReadyState: mediaStreamTrack?.readyState,
hasProcessor: !!micTrack?.getProcessor(),
@@ -531,7 +542,7 @@ function createCallState() {
callId: store.activeCallId ?? undefined,
preferredMode: persistedNoiseSuppressionMode(),
activeMode: store.noiseSuppressionMode,
- krispSupported: isKrispNoiseFilterSupported(),
+ krispSupported: isKrispSupported(),
hasProcessor: !!micTrack?.getProcessor(),
constraintMismatch,
autoGainControl: settings?.autoGainControl,
@@ -586,14 +597,33 @@ function createCallState() {
const micTrack = getLocalMicTrack(r);
if (!isLiveLocalTrack(micTrack)) return;
- if (preferredMode === 'browser' || !isKrispNoiseFilterSupported()) {
+ if (preferredMode === 'browser') {
+ setStore('noiseSuppressionMode', 'browser');
+ await detachKrispFromMicTrack(r);
+ if (room() !== r) return;
+ await applyNativeAudioProcessingToMicTrack(r, 'browser');
+ if (room() !== r) return;
+ logMicAudioProcessing('browser-noise-suppression-enabled', r, {
+ reason: 'preferred',
+ });
+ return;
+ }
+
+ // Resolve Krisp before deciding whether the persisted preference can be
+ // honored. Import/load failures intentionally fall back to browser-native
+ // processing instead of failing call setup.
+ await loadKrisp().catch(() => null);
+ if (room() !== r || !isLiveLocalTrack(micTrack)) return;
+
+ const krispModule = getKrisp();
+ if (!krispModule || !krispModule.isKrispNoiseFilterSupported()) {
setStore('noiseSuppressionMode', 'browser');
await detachKrispFromMicTrack(r);
if (room() !== r) return;
await applyNativeAudioProcessingToMicTrack(r, 'browser');
if (room() !== r) return;
logMicAudioProcessing('browser-noise-suppression-enabled', r, {
- reason: preferredMode === 'browser' ? 'preferred' : 'krisp-unsupported',
+ reason: 'krisp-unsupported',
});
return;
}
@@ -620,7 +650,7 @@ function createCallState() {
// `quality` is model size/CPU cost, not suppression strength. The default
// medium model avoids the CPU pressure/dropouts that made voices sound
// muddy on busy machines while still enabling Krisp when supported.
- const krisp = KrispNoiseFilter({ quality: 'medium' });
+ const krisp = krispModule.KrispNoiseFilter({ quality: 'medium' });
setKrispFilter(krisp);
await micTrack.setProcessor(krisp);
if (room() !== r || !isLiveLocalTrack(micTrack)) {
@@ -695,7 +725,9 @@ function createCallState() {
const effect = store.backgroundEffect;
if (effect.type === 'none') return true;
- const camPub = r.localParticipant.getTrackPublication(Track.Source.Camera);
+ const camPub = r.localParticipant.getTrackPublication(
+ LK_TRACK_SOURCE.Camera
+ );
const camTrack = camPub?.track as LocalTrack | undefined;
if (!isLiveLocalTrack(camTrack)) return true;
@@ -754,7 +786,7 @@ function createCallState() {
if (prev) {
try {
const camPub = r.localParticipant.getTrackPublication(
- Track.Source.Camera
+ LK_TRACK_SOURCE.Camera
);
if (camPub?.track) {
await (camPub.track as LocalTrack).stopProcessor();
@@ -804,6 +836,12 @@ function createCallState() {
// --- device enumeration ---
async function enumerateDevices() {
+ // Device lists are only consumed after a browser call has loaded LiveKit.
+ // Native calls own device selection outside this JS context.
+ const livekitModule = getLivekit();
+ if (!livekitModule) return;
+ const { Room } = livekitModule;
+
try {
const devices = await Room.getLocalDevices('audioinput');
setStore(
@@ -849,7 +887,7 @@ function createCallState() {
function trackActiveDevices(r: Room) {
const micPub = r.localParticipant.getTrackPublication(
- Track.Source.Microphone
+ LK_TRACK_SOURCE.Microphone
);
if (micPub?.track) {
const settings = (
@@ -876,7 +914,9 @@ function createCallState() {
// Only set the active video device when we can read it from a live track.
// When video is off we leave it null — guessing would show the wrong
// selection if the browser's default differs from the first enumerated device.
- const camPub = r.localParticipant.getTrackPublication(Track.Source.Camera);
+ const camPub = r.localParticipant.getTrackPublication(
+ LK_TRACK_SOURCE.Camera
+ );
if (camPub?.track) {
const settings = (
camPub.track as LocalTrack
@@ -993,9 +1033,9 @@ function createCallState() {
(nativeCall?.bootstrapChannelId() ?? null) !== null) ||
(currentNativeCallSnapshot() === null &&
store.optimisticJoinChannelId !== null) ||
- currentConnectionState() === ConnectionState.Connecting ||
- currentConnectionState() === ConnectionState.Reconnecting ||
- currentConnectionState() === ConnectionState.SignalReconnecting;
+ currentConnectionState() === LK_CONNECTION_STATE.Connecting ||
+ currentConnectionState() === LK_CONNECTION_STATE.Reconnecting ||
+ currentConnectionState() === LK_CONNECTION_STATE.SignalReconnecting;
const currentJoinError = () =>
currentNativeCallSnapshot() ? null : store.joinError;
@@ -1036,7 +1076,37 @@ function createCallState() {
trackActiveDevices(targetRoom);
}
- const livekitJs = createLivekitJsCallController({
+ // Create the browser controller on first use. LiveKit gates signaling;
+ // Krisp deliberately does not, because its much larger chunk is optional
+ // media enhancement and finishLocalMediaSetup already runs in the background.
+ let livekitJs: LivekitJsCallController | null = null;
+ let livekitJsPromise: Promise<LivekitJsCallController> | null = null;
+ let browserConnectGeneration = 0;
+ let disposed = false;
+
+ function getLivekitJsController(): Promise<LivekitJsCallController> {
+ if (livekitJsPromise) return livekitJsPromise;
+
+ livekitJsPromise = Promise.all([
+ import('./LivekitJsCallController'),
+ loadLivekit(),
+ ])
+ .then(([module]) => {
+ if (disposed) {
+ throw new Error('Call provider disposed while LiveKit was loading');
+ }
+ livekitJs = module.createLivekitJsCallController(livekitJsOptions);
+ return livekitJs;
+ })
+ .catch((error: unknown) => {
+ livekitJsPromise = null;
+ throw error;
+ });
+
+ return livekitJsPromise;
+ }
+
+ const livekitJsOptions: LivekitJsCallControllerOptions = {
room,
setRoom,
state: () => ({
@@ -1076,12 +1146,25 @@ function createCallState() {
bumpTrackVersion,
bumpSpeakerVersion: () => setStore('speakerVersion', (v) => v + 1),
setScreenSharing: (value) => setStore('isScreenSharing', value),
- });
+ };
const callSession = createCallSessionController({
nativeCall,
- jsConnect: livekitJs.connect,
- jsDisconnect: livekitJs.disconnect,
+ jsConnect: async (tokenResponse) => {
+ const generation = ++browserConnectGeneration;
+ const controller = await getLivekitJsController();
+ if (disposed || generation !== browserConnectGeneration) return;
+ return controller.connect(tokenResponse);
+ },
+ jsDisconnect: async () => {
+ // Cancel a connect that is still waiting on its dynamic import. This is
+ // also reached by timeout/error recovery in useCall.
+ browserConnectGeneration += 1;
+ if (!livekitJsPromise) return;
+ const controller = await getLivekitJsController();
+ if (disposed) return;
+ return controller.disconnect();
+ },
clearOptimisticJoin: () => {
setStore('optimisticJoinChannelId', null);
setStore('joinError', null);
@@ -1138,7 +1221,7 @@ function createCallState() {
);
// Read the actual device the browser chose so the dropdown is accurate
const camPub = r.localParticipant.getTrackPublication(
- Track.Source.Camera
+ LK_TRACK_SOURCE.Camera
);
if (camPub?.track) {
const settings = (
@@ -1251,17 +1334,19 @@ function createCallState() {
// --- cleanup ---
const handleBeforeUnload = () => {
- livekitJs.disconnectBeforeUnload();
+ livekitJs?.disconnectBeforeUnload();
};
window.addEventListener('beforeunload', handleBeforeUnload);
onCleanup(() => {
+ disposed = true;
+ browserConnectGeneration += 1;
window.removeEventListener('beforeunload', handleBeforeUnload);
navigator.mediaDevices?.removeEventListener(
'devicechange',
handleDeviceChange
);
- livekitJs.dispose();
+ livekitJs?.dispose();
});
// --- public API ---
diff --git a/js/app/packages/channel/Call/CallOverlay.tsx b/js/app/packages/channel/Call/CallOverlay.tsx
index 70e69f1e54..4871b13581 100644
--- a/js/app/packages/channel/Call/CallOverlay.tsx
+++ b/js/app/packages/channel/Call/CallOverlay.tsx
@@ -4,7 +4,7 @@ import { useAuthor, useUserId } from '@core/context/user';
import { useProfilePictureUrl } from '@core/signal/profilePicture';
import { tryMacroId, useDisplayName } from '@core/user';
import { cn, InlineCheckbox, Tooltip } from '@ui';
-import { type RemoteParticipant, Track } from 'livekit-client';
+import type { RemoteParticipant, Track } from 'livekit-client';
import { For, type JSXElement, Show } from 'solid-js';
import { useCallContext } from './CallContext';
import { CallControls } from './CallControls/CallControls';
@@ -12,6 +12,7 @@ import {
CALL_PANEL_MEDIUM_NARROW_PX,
CALL_PANEL_VERY_NARROW_PX,
} from './call-panel-breakpoints';
+import { LK_TRACK_SOURCE } from './livekit-loader';
import { TrackView } from './TrackView';
import { useToggleShareWithTeam } from './use-toggle-share-with-team';
@@ -146,7 +147,7 @@ function ParticipantTile(props: { participant: RemoteParticipant }) {
const cameraTrack = () => {
callCtx.trackVersion();
- const pub = props.participant.getTrackPublication(Track.Source.Camera);
+ const pub = props.participant.getTrackPublication(LK_TRACK_SOURCE.Camera);
return pub?.isSubscribed && !pub.isMuted ? pub.track : undefined;
};
@@ -188,7 +189,7 @@ function ScreenShareTile(props: { participant: RemoteParticipant }) {
const [displayName] = useDisplayName(macroId());
const screenTrack = () => {
callCtx.trackVersion();
- return props.participant.getTrackPublication(Track.Source.ScreenShare)
+ return props.participant.getTrackPublication(LK_TRACK_SOURCE.ScreenShare)
?.track;
};
@@ -232,21 +233,22 @@ export function CallOverlay(props: { onLeave: () => void }) {
callCtx.trackVersion();
const r = callCtx.room();
if (!r || callCtx.isVideoMuted()) return undefined;
- return r.localParticipant.getTrackPublication(Track.Source.Camera)?.track;
+ return r.localParticipant.getTrackPublication(LK_TRACK_SOURCE.Camera)
+ ?.track;
};
const localScreenTrack = () => {
callCtx.trackVersion();
const r = callCtx.room();
if (!r || !callCtx.isScreenSharing()) return undefined;
- return r.localParticipant.getTrackPublication(Track.Source.ScreenShare)
+ return r.localParticipant.getTrackPublication(LK_TRACK_SOURCE.ScreenShare)
?.track;
};
const remoteScreenShares = () => {
callCtx.trackVersion();
return participants().filter((p) => {
- const pub = p.getTrackPublication(Track.Source.ScreenShare);
+ const pub = p.getTrackPublication(LK_TRACK_SOURCE.ScreenShare);
return !!pub?.track && pub.isSubscribed && !pub.isMuted;
});
};
diff --git a/js/app/packages/channel/Call/call-audio-receiver-stats.ts b/js/app/packages/channel/Call/call-audio-receiver-stats.ts
index b06e54e364..d2ddfeb4e2 100644
--- a/js/app/packages/channel/Call/call-audio-receiver-stats.ts
+++ b/js/app/packages/channel/Call/call-audio-receiver-stats.ts
@@ -1,4 +1,4 @@
-import { analytics } from '@app/lib/analytics';
+import { analytics } from '@app/lib/analytics/analytics';
import {
type AudioReceiverStats,
type RemoteAudioTrack,
diff --git a/js/app/packages/channel/Call/livekit-loader.ts b/js/app/packages/channel/Call/livekit-loader.ts
new file mode 100644
index 0000000000..feb21f292a
--- /dev/null
+++ b/js/app/packages/channel/Call/livekit-loader.ts
@@ -0,0 +1,97 @@
+/**
+ * Lazy loaders for the browser call SDKs.
+ *
+ * CallProvider mounts with the app shell, but LiveKit and Krisp are only needed
+ * once a browser call starts. Keeping all value imports in this module prevents
+ * both SDKs (including Krisp's inlined model) from entering the initial bundle.
+ */
+import type {
+ ConnectionState,
+ DisconnectReason,
+ RoomEvent,
+ Track,
+} from 'livekit-client';
+
+type LivekitModule = typeof import('livekit-client');
+type KrispModule = typeof import('@livekit/krisp-noise-filter');
+
+let livekit: LivekitModule | null = null;
+let livekitPromise: Promise<LivekitModule> | null = null;
+let krisp: KrispModule | null = null;
+let krispPromise: Promise<KrispModule> | null = null;
+
+export function loadLivekit(): Promise<LivekitModule> {
+ livekitPromise ??= import('livekit-client')
+ .then((module) => {
+ livekit = module;
+ return module;
+ })
+ .catch((error: unknown) => {
+ // A transient chunk/network failure must not poison every later retry.
+ livekitPromise = null;
+ throw error;
+ });
+ return livekitPromise;
+}
+
+export function getLivekit(): LivekitModule | null {
+ return livekit;
+}
+
+export function loadKrisp(): Promise<KrispModule> {
+ krispPromise ??= import('@livekit/krisp-noise-filter')
+ .then((module) => {
+ krisp = module;
+ return module;
+ })
+ .catch((error: unknown) => {
+ krispPromise = null;
+ throw error;
+ });
+ return krispPromise;
+}
+
+export function getKrisp(): KrispModule | null {
+ return krisp;
+}
+
+/** Returns false until Krisp has loaded or when the browser is unsupported. */
+export function isKrispSupported(): boolean {
+ return krisp?.isKrispNoiseFilterSupported() ?? false;
+}
+
+// Compile-time-checked mirrors let shell code compare SDK enum values without
+// evaluating livekit-client. A changed upstream value will fail type-checking.
+export const LK_CONNECTION_STATE = {
+ Disconnected: 'disconnected' as ConnectionState.Disconnected,
+ Connecting: 'connecting' as ConnectionState.Connecting,
+ Connected: 'connected' as ConnectionState.Connected,
+ Reconnecting: 'reconnecting' as ConnectionState.Reconnecting,
+ SignalReconnecting:
+ 'signalReconnecting' as ConnectionState.SignalReconnecting,
+} as const;
+
+export const LK_TRACK_SOURCE = {
+ Camera: 'camera' as Track.Source.Camera,
+ Microphone: 'microphone' as Track.Source.Microphone,
+ ScreenShare: 'screen_share' as Track.Source.ScreenShare,
+} as const;
+
+export const LK_ROOM_EVENT = {
+ Disconnected: 'disconnected' as RoomEvent.Disconnected,
+} as const;
+
+// DisconnectReason is a protobuf enum; the numeric values are wire-stable.
+export const LK_DISCONNECT_REASON = {
+ CLIENT_INITIATED: 1,
+ DUPLICATE_IDENTITY: 2,
+ PARTICIPANT_REMOVED: 4,
+ ROOM_DELETED: 5,
+ ROOM_CLOSED: 10,
+} as const satisfies {
+ CLIENT_INITIATED: DisconnectReason.CLIENT_INITIATED;
+ DUPLICATE_IDENTITY: DisconnectReason.DUPLICATE_IDENTITY;
+ PARTICIPANT_REMOVED: DisconnectReason.PARTICIPANT_REMOVED;
+ ROOM_DELETED: DisconnectReason.ROOM_DELETED;
+ ROOM_CLOSED: DisconnectReason.ROOM_CLOSED;
+};
diff --git a/js/app/packages/channel/Call/tests/livekit-loader.test.ts b/js/app/packages/channel/Call/tests/livekit-loader.test.ts
new file mode 100644
index 0000000000..4041d261e4
--- /dev/null
+++ b/js/app/packages/channel/Call/tests/livekit-loader.test.ts
@@ -0,0 +1,49 @@
+import {
+ ConnectionState,
+ DisconnectReason,
+ RoomEvent,
+ Track,
+} from 'livekit-client';
+import { describe, expect, it } from 'vitest';
+import {
+ getLivekit,
+ LK_CONNECTION_STATE,
+ LK_DISCONNECT_REASON,
+ LK_ROOM_EVENT,
+ LK_TRACK_SOURCE,
+ loadLivekit,
+} from '../livekit-loader';
+
+describe('livekit-loader', () => {
+ it('keeps enum mirrors aligned with the runtime SDK', () => {
+ expect(LK_CONNECTION_STATE).toEqual({
+ Disconnected: ConnectionState.Disconnected,
+ Connecting: ConnectionState.Connecting,
+ Connected: ConnectionState.Connected,
+ Reconnecting: ConnectionState.Reconnecting,
+ SignalReconnecting: ConnectionState.SignalReconnecting,
+ });
+ expect(LK_TRACK_SOURCE).toEqual({
+ Camera: Track.Source.Camera,
+ Microphone: Track.Source.Microphone,
+ ScreenShare: Track.Source.ScreenShare,
+ });
+ expect(LK_ROOM_EVENT.Disconnected).toBe(RoomEvent.Disconnected);
+ expect(LK_DISCONNECT_REASON).toEqual({
+ CLIENT_INITIATED: DisconnectReason.CLIENT_INITIATED,
+ DUPLICATE_IDENTITY: DisconnectReason.DUPLICATE_IDENTITY,
+ PARTICIPANT_REMOVED: DisconnectReason.PARTICIPANT_REMOVED,
+ ROOM_DELETED: DisconnectReason.ROOM_DELETED,
+ ROOM_CLOSED: DisconnectReason.ROOM_CLOSED,
+ });
+ });
+
+ it('shares one in-flight LiveKit import and exposes the loaded module', async () => {
+ const first = loadLivekit();
+ const second = loadLivekit();
+
+ expect(second).toBe(first);
+ const module = await first;
+ expect(getLivekit()).toBe(module);
+ });
+});
diff --git a/js/app/packages/channel/Call/use-call.ts b/js/app/packages/channel/Call/use-call.ts
index 4d2d65aaec..7b7dcf0c20 100644
--- a/js/app/packages/channel/Call/use-call.ts
+++ b/js/app/packages/channel/Call/use-call.ts
@@ -7,9 +7,10 @@ import {
} from '@queries/call/call';
import { callServiceClient } from '@service-call/client';
import { useMutation } from '@tanstack/solid-query';
-import { DisconnectReason, RoomEvent } from 'livekit-client';
+import type { DisconnectReason } from 'livekit-client';
import { createEffect, createSignal, onCleanup } from 'solid-js';
import { useCallContext } from './CallContext';
+import { LK_DISCONNECT_REASON, LK_ROOM_EVENT } from './livekit-loader';
import { registerCallKitCallEndedHandler } from './use-callkit';
type UseCallOptions = {
@@ -34,11 +35,11 @@ type ActiveJoinAttempt = {
function shouldAutoRejoin(reason?: DisconnectReason) {
switch (reason) {
- case DisconnectReason.CLIENT_INITIATED:
- case DisconnectReason.DUPLICATE_IDENTITY:
- case DisconnectReason.PARTICIPANT_REMOVED:
- case DisconnectReason.ROOM_DELETED:
- case DisconnectReason.ROOM_CLOSED:
+ 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;
@@ -115,9 +116,9 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
cleanupDisconnectListener = null;
scheduleAutoRejoin(reason);
};
- room.on(RoomEvent.Disconnected, handleDisconnect);
+ room.on(LK_ROOM_EVENT.Disconnected, handleDisconnect);
cleanupDisconnectListener = () =>
- room.off(RoomEvent.Disconnected, handleDisconnect);
+ room.off(LK_ROOM_EVENT.Disconnected, handleDisconnect);
}
// If the call is already active for this channel (e.g. the user navigated
diff --git a/js/app/packages/channel/Channel/ActiveCallMessage.tsx b/js/app/packages/channel/Channel/ActiveCallMessage.tsx
index 2bcc85d8ea..eec81d1413 100644
--- a/js/app/packages/channel/Channel/ActiveCallMessage.tsx
+++ b/js/app/packages/channel/Channel/ActiveCallMessage.tsx
@@ -1,4 +1,5 @@
-import { joinChannelCall, useCallContextOptional } from '@channel/Call';
+import { useCallContextOptional } from '@channel/Call/CallContext';
+import { joinChannelCall } from '@channel/Call/join-channel-call';
import PhoneIcon from '@icon/wide-call.svg';
import { useActiveCallQuery } from '@queries/call/call';
import { Button } from '@ui';
diff --git a/js/app/packages/core/component/DocumentPreview.tsx b/js/app/packages/core/component/DocumentPreview.tsx
index 6075aa7bcd..6aaa08e752 100644
--- a/js/app/packages/core/component/DocumentPreview.tsx
+++ b/js/app/packages/core/component/DocumentPreview.tsx
@@ -2,7 +2,7 @@ import { URL_PARAMS as URL_PARAMS_CANVAS } from '@block-canvas/constants';
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import { useOpenChatForAttachment } from '@block-chat/client';
import { URL_PARAMS as URL_PARAMS_MD } from '@block-md/constants';
-import { URL_PARAMS as URL_PARAMS_PDF } from '@block-pdf/signal/location';
+import { URL_PARAMS as URL_PARAMS_PDF } from '@block-pdf/constants';
import {
type BlockAlias,
type BlockName,
diff --git a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
index 2d52d3170a..4981918bb4 100644
--- a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
@@ -1,5 +1,5 @@
import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
-import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/signal/location';
+import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
import { itemToBlockName } from '@core/constant/allBlocks';
import { useChannelsContext } from '@core/context/channels';
diff --git a/js/app/packages/core/internal/BlockLoader.tsx b/js/app/packages/core/internal/BlockLoader.tsx
index 202308918a..f8ff86247b 100644
--- a/js/app/packages/core/internal/BlockLoader.tsx
+++ b/js/app/packages/core/internal/BlockLoader.tsx
@@ -28,6 +28,7 @@ import {
} from '../signal/load';
import type { Source, SourcePreload } from '../source';
import type { ObjectLike } from '../util/result';
+import { loadBlockDataAfterComponentPreload } from './loadBlockData';
export const blockDataSignal = createBlockSignal<unknown>();
export const blockLiveTrackingEnabledSignal = createBlockSignal<boolean>();
@@ -72,7 +73,10 @@ export function BlockLoader<
setEditPermissionEnabled(props.definition.editPermissionEnabled ?? false);
const getResult = createAsync(async () => {
- const result = await props.definition.load(props.source, 'initial');
+ const result = await loadBlockDataAfterComponentPreload(
+ () => props.definition.load(props.source, 'initial'),
+ props.definition.component.preload
+ );
if (result.isErr()) {
return err(result.error);
}
diff --git a/js/app/packages/core/internal/loadBlockData.test.ts b/js/app/packages/core/internal/loadBlockData.test.ts
new file mode 100644
index 0000000000..4504728180
--- /dev/null
+++ b/js/app/packages/core/internal/loadBlockData.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from 'vitest';
+import { loadBlockDataAfterComponentPreload } from './loadBlockData';
+
+describe('loadBlockDataAfterComponentPreload', () => {
+ it('starts both operations immediately and waits for component evaluation', async () => {
+ let finishPreload: (() => void) | undefined;
+ const preload = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishPreload = resolve;
+ })
+ );
+ const load = vi.fn(async () => 'loaded');
+
+ const result = loadBlockDataAfterComponentPreload(load, preload);
+ let settled = false;
+ void result.then(() => {
+ settled = true;
+ });
+
+ await Promise.resolve();
+ expect(load).toHaveBeenCalledOnce();
+ expect(preload).toHaveBeenCalledOnce();
+ expect(settled).toBe(false);
+
+ finishPreload?.();
+ await expect(result).resolves.toBe('loaded');
+ });
+
+ it('returns normally for an eager component without preload', async () => {
+ await expect(
+ loadBlockDataAfterComponentPreload(async () => 'loaded')
+ ).resolves.toBe('loaded');
+ });
+});
diff --git a/js/app/packages/core/internal/loadBlockData.ts b/js/app/packages/core/internal/loadBlockData.ts
new file mode 100644
index 0000000000..6673d8b5fb
--- /dev/null
+++ b/js/app/packages/core/internal/loadBlockData.ts
@@ -0,0 +1,15 @@
+/**
+ * Load block data and its lazy component in parallel, but do not publish the
+ * data until the component module has evaluated. Some legacy block modules
+ * register top-level effects during evaluation, and those registrations must
+ * exist before BlockEffectRunner reacts to the loaded data.
+ */
+export async function loadBlockDataAfterComponentPreload<T>(
+ load: () => Promise<T>,
+ preload?: () => Promise<unknown>
+): Promise<T> {
+ const componentPromise = preload?.() ?? Promise.resolve();
+ const dataPromise = load();
+ const [result] = await Promise.all([dataPromise, componentPromise]);
+ return result;
+}
diff --git a/js/app/packages/core/orchestrator.tsx b/js/app/packages/core/orchestrator.tsx
index 197770d994..f63931d870 100644
--- a/js/app/packages/core/orchestrator.tsx
+++ b/js/app/packages/core/orchestrator.tsx
@@ -21,6 +21,7 @@ import {
ValidNestingCombinations,
} from './block';
import type { BlockMethodsFor } from './blockMethodRegistry';
+import { LoadingBlock } from './component/LoadingBlock';
import { blocks as BLOCK_REGISTRY } from './constant/allBlocks';
import { BlockEffectRunner } from './internal/BlockEffectRunner';
import { BlockLoader } from './internal/BlockLoader';
@@ -209,7 +210,7 @@ function createBlockElement({
id={id}
handle={ownedHandle}
/>
- <Suspense>
+ <Suspense fallback={<LoadingBlock />}>
<Dynamic component={definition.component} {...opts?.params} />
</Suspense>
<BlockEffectRunner />
diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.ts
index 73af8c625d..482663e0c4 100644
--- a/js/app/packages/notifications/notification-navigation.ts
+++ b/js/app/packages/notifications/notification-navigation.ts
@@ -4,7 +4,7 @@ import {
navigateToChannelMessage,
} from '@block-channel/utils/link';
import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
-import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/signal/location';
+import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
import type { BlockAlias, BlockName } from '@core/block';
import {
type ItemLike,
diff --git a/js/app/packages/tauri/src/TauriProvider.tsx b/js/app/packages/tauri/src/TauriProvider.tsx
index 1e5bd0c6d5..24f31a6d1d 100644
--- a/js/app/packages/tauri/src/TauriProvider.tsx
+++ b/js/app/packages/tauri/src/TauriProvider.tsx
@@ -1,4 +1,5 @@
-import { NativeCallProvider, useCallKitSetup } from '@channel/Call';
+import { NativeCallProvider } from '@channel/Call/native-call-state';
+import { useCallKitSetup } from '@channel/Call/use-callkit';
import { NativeAppUpdateRequiredDialog } from '@core/mobile/NativeAppUpdateRequiredDialog';
import { isPlatform, isTauri } from '@core/util/platform';
import { PlatformNotificationProvider } from '@notifications';