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.

feat(calls): Frontend implementation (#2335)

Will Hutchinsonfdb40cbf123b
diff --git a/js/app/justfile b/js/app/justfile
index 6f6b68bc10..5f9ce3c817 100644
--- a/js/app/justfile
+++ b/js/app/justfile
@@ -1,10 +1,17 @@
dev-tauri:
cd packages/app && bun run --bun dev:tauri
-# Run the app with all services locally
+# List available local service names
+local-services:
+ @sed -n "s/.*'\([a-z][-a-z]*\)':.*/\1/p" packages/core/constant/servers.ts | sort -u
+
+# Run the app with local services (defaults to ALL)
# This assumes you have followed the RUNNING_LOCALLLY.md instructions
+servers := 'ALL'
+port := '3000'
+
local:
- cd packages/app && VITE_LOCAL_SERVERS='ALL' bun run --bun dev
+ cd packages/app && PORT='{{port}}' VITE_LOCAL_SERVERS='{{servers}}' bun run --bun dev
local-dcs:
cd packages/app && VITE_LOCAL_SERVERS='cognition-service,cognition-websocket-service' bun run --bun dev
diff --git a/js/app/packages/app/vite.base.ts b/js/app/packages/app/vite.base.ts
index 3dcf72234d..0f4f0ab8c0 100644
--- a/js/app/packages/app/vite.base.ts
+++ b/js/app/packages/app/vite.base.ts
@@ -131,13 +131,13 @@ export const createAppViteConfig = ({
],
},
server: {
- port: 3000,
+ port: Number(process.env.PORT || 3000),
host: '0.0.0.0',
strictPort: true,
hmr: {
protocol: 'ws',
host: process.env.TAURI_DEV_HOST || 'localhost',
- port: 3000,
+ port: Number(process.env.PORT || 3000),
},
cors: true,
watch: {
diff --git a/js/app/packages/block-channel/component/ModalsProvider.tsx b/js/app/packages/block-channel/component/ModalsProvider.tsx
index ee1dca718b..468fb197bc 100644
--- a/js/app/packages/block-channel/component/ModalsProvider.tsx
+++ b/js/app/packages/block-channel/component/ModalsProvider.tsx
@@ -8,10 +8,14 @@ import { AttachmentsDrawer, useAttachments } from './AttachmentsModal';
import type { Attachment } from '@queries/channel/types';
import { ParticipantManagerDialog } from './ParticipantManager';
import { useChannelContext } from '@block-channel/hooks/channel';
+import { CallProvider, CallOverlay, useCall } from '@channel/Call';
type ChannelModalsContextValue = {
openParticipants: () => void;
attachments: () => Attachment[];
+ joinCall: () => Promise<void>;
+ leaveCall: () => Promise<void>;
+ isInCall: () => boolean;
};
export const ChannelModalsContext = createContext<ChannelModalsContextValue>();
@@ -24,17 +28,39 @@ export function useChannelModals() {
}
export function ModalsProvider(props: ParentProps) {
+ return (
+ <CallProvider>
+ <ModalsProviderInner>{props.children}</ModalsProviderInner>
+ </CallProvider>
+ );
+}
+
+function ModalsProviderInner(props: ParentProps) {
const blockId = useBlockId();
const notificationSource = useGlobalNotificationSource();
const channelContext = useChannelContext();
const [participantsOpen, setParticipantsOpen] = createSignal(false);
const attachments = useAttachments();
+ const call = useCall(() => blockId);
return (
<ChannelModalsContext.Provider
- value={{ openParticipants: () => setParticipantsOpen(true), attachments }}
+ value={{
+ openParticipants: () => setParticipantsOpen(true),
+ attachments,
+ joinCall: call.joinCall,
+ leaveCall: call.leaveCall,
+ isInCall: call.isInThisChannel,
+ }}
>
- {props.children}
+ <div class="relative h-full">
+ {props.children}
+ <Show when={call.isInThisChannel()}>
+ <div class="absolute inset-0 z-50">
+ <CallOverlay onLeave={call.leaveCall} />
+ </div>
+ </Show>
+ </div>
<NotificationsDrawer
entity={{ id: blockId, type: 'channel' }}
notificationSource={notificationSource}
diff --git a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
index d45587954f..614ecb104d 100644
--- a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
@@ -6,7 +6,14 @@ import {
import { ChannelTopBarLiveIndicators } from '@channel/Channel/ChannelTopBarLiveIndicators';
import { useBlockId } from '@core/block';
import { EntityPermissionsGate } from '@core/component/EntityPermissionsGate';
-import { createSignal, Match, Suspense, Switch } from 'solid-js';
+import {
+ type Component,
+ createSignal,
+ Match,
+ Show,
+ Suspense,
+ Switch,
+} from 'solid-js';
import { blockHandleSignal } from '@core/signal/load';
import { createMethodRegistration } from '@core/orchestrator';
import { URL_PARAMS } from '@block-channel/constants';
@@ -25,6 +32,12 @@ import { ChannelParticipantsTab } from '@channel/Participants/ChannelParticipant
import { ChannelDebouncedNotificationReadMarker } from '@notifications/components/DebouncedNotificationReadMarker';
import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
import type { BlockChannelProps } from './Block';
+import { CallProvider, CallOverlay, useCall } from '@channel/Call';
+import { ENABLE_CALLS } from '@core/constant/featureFlags';
+import { SplitHeaderRight } from '@app/component/split-layout/components/SplitHeader';
+import { Button } from '@ui/components/Button';
+import PhoneIcon from '@icon/regular/phone.svg';
+import PhoneDisconnectIcon from '@icon/regular/phone-disconnect.svg';
type ChannelTargetMessageParams = {
[URL_PARAMS.message]?: string;
@@ -36,10 +49,56 @@ type ChannelPropsTargetMessage = Pick<
'targetMessageId' | 'targetMessageReplyId'
>;
+const CallIcon: Component<{ isInCall: () => boolean }> = (props) => (
+ <Show when={props.isInCall()} fallback={<PhoneIcon />}>
+ <PhoneDisconnectIcon />
+ </Show>
+);
+
+function CallButton(props: {
+ joinCall: () => Promise<void>;
+ leaveCall: () => Promise<void>;
+ isInCall: () => boolean;
+ isPending: () => boolean;
+}) {
+ const handleClick = async () => {
+ if (props.isPending()) return;
+ try {
+ if (props.isInCall()) {
+ await props.leaveCall();
+ } else {
+ await props.joinCall();
+ }
+ } catch (e) {
+ console.error('Call action failed', e);
+ }
+ };
+
+ return (
+ <Button
+ onClick={handleClick}
+ disabled={props.isPending()}
+ tooltip={props.isInCall() ? 'Leave Call' : 'Call'}
+ class={
+ props.isInCall()
+ ? 'px-1 bg-accent/20 hover:bg-accent/30 text-accent-ink'
+ : 'px-1'
+ }
+ size="icon-sm"
+ >
+ <CallIcon isInCall={props.isInCall} />
+ </Button>
+ );
+}
+
function NewTop(props: {
channelId: string;
activeTab: ChannelTabId;
onTabChange: (value: ChannelTabId) => void;
+ joinCall: () => Promise<void>;
+ leaveCall: () => Promise<void>;
+ isInCall: () => boolean;
+ isPending: () => boolean;
}) {
const channelName = useChannelName(props.channelId);
const channelType = useChannelType(props.channelId);
@@ -62,6 +121,16 @@ function NewTop(props: {
activeTab={props.activeTab}
onTabChange={props.onTabChange}
/>
+ <Show when={ENABLE_CALLS()}>
+ <SplitHeaderRight>
+ <CallButton
+ joinCall={props.joinCall}
+ leaveCall={props.leaveCall}
+ isInCall={props.isInCall}
+ isPending={props.isPending}
+ />
+ </SplitHeaderRight>
+ </Show>
<ChannelTopBarLiveIndicators />
</Suspense>
);
@@ -73,9 +142,28 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
const notificationSource = useGlobalNotificationSource();
const channelId = useBlockId();
+
+ return (
+ <EntityPermissionsGate entityType="channel" entityId={channelId}>
+ <ChannelDebouncedNotificationReadMarker
+ notificationSource={notificationSource}
+ channelId={channelId}
+ debounceTime={500}
+ />
+ <CallProvider>
+ <NewChannelBlockAdapterInner channelId={channelId} {...props} />
+ </CallProvider>
+ </EntityPermissionsGate>
+ );
+}
+
+function NewChannelBlockAdapterInner(
+ props: { channelId: string } & BlockChannelProps
+) {
const blockHandle = blockHandleSignal.get;
const [activeTab, setActiveTab] =
createSignal<ChannelTabId>(DEFAULT_CHANNEL_TAB);
+ const call = useCall(() => props.channelId);
const convertTargetMessage = (
params: ChannelTargetMessageParams
@@ -110,34 +198,36 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
};
return (
- <EntityPermissionsGate entityType="channel" entityId={channelId}>
- <ChannelDebouncedNotificationReadMarker
- notificationSource={notificationSource}
- channelId={channelId}
- debounceTime={500}
+ <div class="relative h-full flex flex-col">
+ <Switch>
+ <Match when={activeTab() === 'messages'}>
+ <NewChannel
+ channelId={props.channelId}
+ onHandleReady={onChannelReady}
+ {...convertTargetMessage(props)}
+ />
+ </Match>
+ <Match when={activeTab() === 'attachments'}>
+ <ChannelAttachmentsTab channelId={props.channelId} />
+ </Match>
+ <Match when={activeTab() === 'participants'}>
+ <ChannelParticipantsTab channelId={props.channelId} />
+ </Match>
+ </Switch>
+ <Show when={call.isInThisChannel()}>
+ <div class="absolute inset-0 z-50">
+ <CallOverlay onLeave={call.leaveCall} />
+ </div>
+ </Show>
+ <NewTop
+ channelId={props.channelId}
+ activeTab={activeTab()}
+ onTabChange={setActiveTab}
+ joinCall={call.joinCall}
+ leaveCall={call.leaveCall}
+ isInCall={call.isInThisChannel}
+ isPending={() => call.isJoining() || call.isLeaving()}
/>
- <div class="relative h-full flex flex-col">
- <Switch>
- <Match when={activeTab() === 'messages'}>
- <NewChannel
- channelId={channelId}
- onHandleReady={onChannelReady}
- {...convertTargetMessage(props)}
- />
- </Match>
- <Match when={activeTab() === 'attachments'}>
- <ChannelAttachmentsTab channelId={channelId} />
- </Match>
- <Match when={activeTab() === 'participants'}>
- <ChannelParticipantsTab channelId={channelId} />
- </Match>
- </Switch>
- <NewTop
- channelId={channelId}
- activeTab={activeTab()}
- onTabChange={setActiveTab}
- />
- </div>
- </EntityPermissionsGate>
+ </div>
);
}
diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsx
index 1f7c57d95f..90ed15be14 100644
--- a/js/app/packages/block-channel/component/Top.tsx
+++ b/js/app/packages/block-channel/component/Top.tsx
@@ -21,12 +21,14 @@ import Bell from '@icon/regular/bell.svg';
import HashIcon from '@icon/regular/hash.svg';
import LinkIcon from '@icon/regular/link.svg';
import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';
+import PhoneIcon from '@icon/regular/phone.svg';
+import PhoneDisconnectIcon from '@icon/regular/phone-disconnect.svg';
import UsersIcon from '@icon/regular/users.svg';
import type { ChannelParticipant } from '@queries/channel/types';
import type { ChannelType } from '@service-comms/generated/models/channelType';
import { ChannelTypeEnum } from '@service-comms/client';
import { useUserId } from '@core/context/user';
-import { createMemo, Show } from 'solid-js';
+import { type Component, createMemo, Show } from 'solid-js';
import { AttachmentsButton } from './AttachmentsModal';
import { useChannelContext } from '@block-channel/hooks/channel';
import { isChannelAdminOrOwner } from '@queries/channel/derived';
@@ -35,6 +37,7 @@ import { ParticipantManagerButton } from './ParticipantManager';
import { useAnalytics } from '@app/component/analytics-context';
import { Tabs, type TabItem } from '@core/component/Tabs';
import type { ChannelTabId } from '@channel/Channel/channel-tabs';
+import { ENABLE_CALLS } from '@core/constant/featureFlags';
type TopIconProps = {
channelType: ChannelType;
@@ -111,6 +114,18 @@ export function ChannelTopLeft(props: ChannelTopLeftProps) {
);
}
+const CallIcon: Component = (iconProps) => {
+ const channelModals = useChannelModals();
+ return (
+ <Show
+ when={channelModals.isInCall()}
+ fallback={<PhoneIcon {...iconProps} />}
+ >
+ <PhoneDisconnectIcon {...iconProps} />
+ </Show>
+ );
+};
+
export function Top(props: TopProps) {
const analytics = useAnalytics();
@@ -173,6 +188,30 @@ export function Top(props: TopProps) {
<AttachmentsButton attachments={channelModals.attachments} />
),
},
+ {
+ label: () => (channelModals.isInCall() ? 'Leave Call' : 'Call'),
+ icon: CallIcon,
+ action: (() => {
+ let isTogglingCall = false;
+ return async () => {
+ if (isTogglingCall) return;
+ isTogglingCall = true;
+ try {
+ if (channelModals.isInCall()) {
+ await channelModals.leaveCall();
+ } else {
+ await channelModals.joinCall();
+ }
+ } catch (e) {
+ console.error('Call action failed', e);
+ } finally {
+ isTogglingCall = false;
+ }
+ };
+ })(),
+ isActive: () => channelModals.isInCall(),
+ condition: () => ENABLE_CALLS(),
+ },
{
label: 'Participants',
icon: UsersIcon,
diff --git a/js/app/packages/channel/Call/CallContext.tsx b/js/app/packages/channel/Call/CallContext.tsx
new file mode 100644
index 0000000000..33a13214c9
--- /dev/null
+++ b/js/app/packages/channel/Call/CallContext.tsx
@@ -0,0 +1,307 @@
+import {
+ Room,
+ RoomEvent,
+ ConnectionState,
+ Track,
+ type RemoteParticipant,
+ type LocalTrackPublication,
+} from 'livekit-client';
+import {
+ createContext,
+ createSignal,
+ useContext,
+ onCleanup,
+ type ParentProps,
+} from 'solid-js';
+import { createStore } from 'solid-js/store';
+import type { CallTokenResponse } from '@service-call/client';
+
+export type CallParticipantInfo = {
+ identity: string;
+ isSpeaking: boolean;
+ isMuted: boolean;
+ hasVideo: boolean;
+};
+
+type CallStoreState = {
+ connectionState: ConnectionState;
+ activeChannelId: string | null;
+ remoteParticipants: Map<string, RemoteParticipant>;
+ isAudioMuted: boolean;
+ isVideoMuted: boolean;
+ isScreenSharing: boolean;
+ trackVersion: number;
+ speakerVersion: number;
+};
+
+const initialState: CallStoreState = {
+ connectionState: ConnectionState.Disconnected,
+ activeChannelId: null,
+ remoteParticipants: new Map(),
+ isAudioMuted: false,
+ isVideoMuted: true,
+ isScreenSharing: false,
+ trackVersion: 0,
+ speakerVersion: 0,
+};
+
+export type CallState = {
+ /** The LiveKit Room instance, null when not in a call */
+ room: () => Room | null;
+ /** Current connection state */
+ connectionState: () => ConnectionState;
+ /** Whether the local user is currently in a call */
+ isInCall: () => boolean;
+ /** Channel ID of the active call */
+ activeChannelId: () => string | null;
+ /** Remote participants in the call */
+ remoteParticipants: () => Map<string, RemoteParticipant>;
+ /** Incremented when track subscription/mute state changes */
+ trackVersion: () => number;
+ /** Whether the local participant is currently speaking */
+ isLocalSpeaking: () => boolean;
+ /** Whether a remote participant is currently speaking (reactive) */
+ isParticipantSpeaking: (participant: RemoteParticipant) => boolean;
+ /** Whether local audio is muted */
+ isAudioMuted: () => boolean;
+ /** Whether local video is muted */
+ isVideoMuted: () => boolean;
+ /** Whether local screen share is active */
+ isScreenSharing: () => boolean;
+ /** Connect to a call using a token response */
+ connect: (tokenResponse: CallTokenResponse) => Promise<void>;
+ /** Disconnect from the current call */
+ disconnect: () => Promise<void>;
+ /** Toggle local audio */
+ toggleAudio: () => Promise<void>;
+ /** Toggle local video */
+ toggleVideo: () => Promise<void>;
+ /** Toggle screen sharing */
+ toggleScreenShare: () => Promise<void>;
+};
+
+const CallContext = createContext<CallState>();
+
+export function useCallContext(): CallState {
+ const ctx = useContext(CallContext);
+ if (!ctx) {
+ throw new Error('useCallContext must be used within <CallProvider />');
+ }
+ return ctx;
+}
+
+export function useCallContextOptional(): CallState | undefined {
+ return useContext(CallContext);
+}
+
+/**
+ * Primitive that manages the LiveKit room lifecycle, event listeners,
+ * and all readonly call state. Returns reactive state + mutation actions.
+ */
+function createCallState() {
+ const [room, setRoom] = createSignal<Room | null>(null);
+ const [store, setStore] = createStore<CallStoreState>({ ...initialState });
+
+ // --- internal helpers ---
+
+ function bumpTrackVersion() {
+ setStore('trackVersion', (v) => v + 1);
+ }
+
+ function syncParticipantMap(r: Room) {
+ setStore('remoteParticipants', new Map(r.remoteParticipants));
+ bumpTrackVersion();
+ }
+
+ function resetState() {
+ setStore({ ...initialState });
+ }
+
+ function attachRoomListeners(r: Room) {
+ r.on(RoomEvent.ConnectionStateChanged, (state: ConnectionState) => {
+ setStore('connectionState', state);
+ });
+
+ r.on(RoomEvent.ParticipantConnected, () => syncParticipantMap(r));
+ r.on(RoomEvent.ParticipantDisconnected, () => syncParticipantMap(r));
+
+ r.on(RoomEvent.TrackSubscribed, bumpTrackVersion);
+ r.on(RoomEvent.TrackUnsubscribed, bumpTrackVersion);
+ r.on(RoomEvent.TrackMuted, bumpTrackVersion);
+ r.on(RoomEvent.TrackUnmuted, bumpTrackVersion);
+
+ r.on(RoomEvent.ActiveSpeakersChanged, () => {
+ setStore('speakerVersion', (v) => v + 1);
+ });
+
+ r.on(RoomEvent.LocalTrackUnpublished, (pub: LocalTrackPublication) => {
+ if (pub.source === Track.Source.ScreenShare) {
+ setStore('isScreenSharing', false);
+ }
+ bumpTrackVersion();
+ });
+ r.on(RoomEvent.Disconnected, resetState);
+ }
+
+ function destroyRoom() {
+ const r = room();
+ if (r) {
+ r.removeAllListeners();
+ setRoom(null);
+ }
+ resetState();
+ }
+
+ // --- mutations ---
+
+ async function connect(tokenResponse: CallTokenResponse) {
+ const existingRoom = room();
+
+ // If switching to a different channel, tear down the old room entirely
+ if (existingRoom && store.activeChannelId !== tokenResponse.channelId) {
+ await existingRoom.disconnect();
+ destroyRoom();
+ }
+
+ let targetRoom: Room;
+ if (room()) {
+ // Reuse existing room instance (same channel, e.g. leave then rejoin)
+ targetRoom = room()!;
+ } else {
+ targetRoom = new Room();
+ attachRoomListeners(targetRoom);
+ setRoom(targetRoom);
+ }
+
+ setStore('activeChannelId', tokenResponse.channelId);
+
+ try {
+ await targetRoom.connect(tokenResponse.serverUrl, tokenResponse.token);
+ } catch (e) {
+ console.error('failed to connect to LiveKit room', e);
+ destroyRoom();
+ throw e;
+ }
+
+ // Sync participants that were already in the room when we connected
+ setStore('remoteParticipants', new Map(targetRoom.remoteParticipants));
+ bumpTrackVersion();
+
+ // Enable microphone by default, video off by default
+ try {
+ await targetRoom.localParticipant.setMicrophoneEnabled(true);
+ } catch (e) {
+ console.error('failed to enable microphone', e);
+ }
+ setStore('isAudioMuted', false);
+ setStore('isVideoMuted', true);
+ }
+
+ async function disconnect() {
+ const r = room();
+ if (r) {
+ try {
+ await r.disconnect();
+ } finally {
+ destroyRoom();
+ }
+ }
+ }
+
+ async function toggleAudio() {
+ const r = room();
+ if (!r) return;
+ const newMuted = !store.isAudioMuted;
+ try {
+ await r.localParticipant.setMicrophoneEnabled(!newMuted);
+ setStore('isAudioMuted', newMuted);
+ } catch (e) {
+ console.error('failed to toggle audio', e);
+ }
+ }
+
+ async function toggleVideo() {
+ const r = room();
+ if (!r) return;
+ const newMuted = !store.isVideoMuted;
+ try {
+ await r.localParticipant.setCameraEnabled(!newMuted);
+ setStore('isVideoMuted', newMuted);
+ } catch (e) {
+ console.error('failed to toggle video', e);
+ }
+ }
+
+ async function toggleScreenShare() {
+ const r = room();
+ if (!r) return;
+ const newSharing = !store.isScreenSharing;
+ try {
+ await r.localParticipant.setScreenShareEnabled(newSharing);
+ setStore('isScreenSharing', newSharing);
+ } catch (e) {
+ console.error('failed to toggle screen share', e);
+ }
+ }
+
+ // --- cleanup ---
+
+ const handleBeforeUnload = () => {
+ const r = room();
+ if (r) {
+ r.disconnect();
+ }
+ };
+ window.addEventListener('beforeunload', handleBeforeUnload);
+
+ onCleanup(() => {
+ window.removeEventListener('beforeunload', handleBeforeUnload);
+ const r = room();
+ if (r) {
+ r.disconnect();
+ r.removeAllListeners();
+ }
+ });
+
+ // --- public API ---
+
+ const state: CallState = {
+ // readonly state
+ room,
+ connectionState: () => store.connectionState,
+ isInCall: () => store.connectionState === ConnectionState.Connected,
+ activeChannelId: () => store.activeChannelId,
+ remoteParticipants: () => store.remoteParticipants,
+ trackVersion: () => store.trackVersion,
+ isLocalSpeaking: () => {
+ // Intentionally read store.speakerVersion to make this reactive so room()?.localParticipant.isSpeaking updates on speakerVersion changes.
+ store.speakerVersion;
+ return room()?.localParticipant.isSpeaking ?? false;
+ },
+ isParticipantSpeaking: (participant: RemoteParticipant) => {
+ // Intentionally read store.speakerVersion to make this reactive so participant.isSpeaking updates on speakerVersion changes.
+ store.speakerVersion;
+ return participant.isSpeaking;
+ },
+ isAudioMuted: () => store.isAudioMuted,
+ isVideoMuted: () => store.isVideoMuted,
+ isScreenSharing: () => store.isScreenSharing,
+
+ // mutations
+ connect,
+ disconnect,
+ toggleAudio,
+ toggleVideo,
+ toggleScreenShare,
+ };
+
+ return state;
+}
+
+export function CallProvider(props: ParentProps) {
+ const state = createCallState();
+
+ return (
+ <CallContext.Provider value={state}>{props.children}</CallContext.Provider>
+ );
+}
diff --git a/js/app/packages/channel/Call/CallOverlay.tsx b/js/app/packages/channel/Call/CallOverlay.tsx
new file mode 100644
index 0000000000..0c428c0cd0
--- /dev/null
+++ b/js/app/packages/channel/Call/CallOverlay.tsx
@@ -0,0 +1,307 @@
+import { Track, type RemoteParticipant } from 'livekit-client';
+import {
+ For,
+ Show,
+ createEffect,
+ createSignal,
+ onCleanup,
+ on,
+ type Component,
+ type JSX,
+} from 'solid-js';
+import PhoneDisconnect from '@icon/regular/phone-disconnect.svg';
+import Microphone from '@icon/regular/microphone.svg';
+import MicrophoneSlash from '@icon/regular/microphone-slash.svg';
+import VideoCamera from '@icon/regular/video-camera.svg';
+import VideoCameraSlash from '@icon/regular/video-camera-slash.svg';
+import Screencast from '@icon/regular/screencast.svg';
+import { useCallContext } from './CallContext';
+
+/**
+ * Generic track view that attaches/detaches a LiveKit track's media element.
+ * Callers resolve the track; this component handles the DOM lifecycle.
+ */
+function TrackView(props: {
+ track: Track | undefined;
+ fit?: 'cover' | 'contain';
+ mirror?: boolean;
+}) {
+ let ref!: HTMLDivElement;
+ let attachedTrack: Track | undefined;
+ let attachedElement: Element | undefined;
+
+ createEffect(
+ on(
+ () => props.track,
+ (track, prev) => {
+ if (prev === track) return;
+
+ prev?.detach().forEach((el) => el.remove());
+ attachedTrack = undefined;
+ attachedElement = undefined;
+
+ if (!track) return;
+
+ const el = track.attach();
+ attachedTrack = track;
+ attachedElement = el;
+ Object.assign(el.style, {
+ width: '100%',
+ height: '100%',
+ objectFit: props.fit ?? 'cover',
+ transform: props.mirror ? 'scaleX(-1)' : '',
+ });
+ ref.appendChild(el);
+ }
+ )
+ );
+
+ onCleanup(() => {
+ if (attachedTrack) {
+ attachedTrack.detach().forEach((el) => el.remove());
+ } else {
+ attachedElement?.remove();
+ }
+ });
+
+ return <div ref={ref} class="w-full h-full" />;
+}
+
+function ParticipantTile(props: { participant: RemoteParticipant }) {
+ const callCtx = useCallContext();
+
+ const micTrack = () => {
+ callCtx.trackVersion();
+ return props.participant.getTrackPublication(Track.Source.Microphone)
+ ?.track;
+ };
+
+ const cameraTrack = () => {
+ callCtx.trackVersion();
+ const pub = props.participant.getTrackPublication(Track.Source.Camera);
+ return pub?.isSubscribed && !pub.isMuted ? pub.track : undefined;
+ };
+
+ const isSpeaking = () => callCtx.isParticipantSpeaking(props.participant);
+
+ return (
+ <div
+ class="relative flex items-center justify-center rounded-lg overflow-hidden bg-surface-2 min-h-[120px]"
+ classList={{ 'ring-2 ring-accent-2': isSpeaking() }}
+ >
+ {/* Attach remote audio so we can hear this participant (visually hidden to avoid stealing layout) */}
+ <div class="absolute w-0 h-0 overflow-hidden">
+ <TrackView track={micTrack()} />
+ </div>
+ <Show
+ when={cameraTrack()}
+ fallback={
+ <div class="flex items-center justify-center w-full h-full p-4">
+ <div class="w-12 h-12 rounded-full bg-surface-3 flex items-center justify-center text-ink-muted text-lg font-medium">
+ {props.participant.identity.charAt(0).toUpperCase()}
+ </div>
+ </div>
+ }
+ >
+ <TrackView track={cameraTrack()} />
+ </Show>
+ <div class="absolute bottom-1 left-1 px-1.5 py-0.5 rounded bg-surface-0/70 text-ink text-xs truncate max-w-[80%]">
+ {props.participant.identity}
+ </div>
+ </div>
+ );
+}
+
+const ControlButton: Component<{
+ onClick: () => Promise<void> | void;
+ active?: boolean;
+ danger?: boolean;
+ children?: JSX.Element;
+}> = (props) => {
+ const [isPending, setIsPending] = createSignal(false);
+
+ const handleClick = async () => {
+ if (isPending()) return;
+ setIsPending(true);
+ try {
+ await props.onClick();
+ } catch (e) {
+ console.error('ControlButton action failed', e);
+ } finally {
+ setIsPending(false);
+ }
+ };
+
+ return (
+ <button
+ onClick={handleClick}
+ disabled={isPending()}
+ class="w-10 h-10 rounded-full flex items-center justify-center transition-colors"
+ classList={{
+ 'opacity-50 cursor-not-allowed': isPending(),
+ 'bg-failure text-panel hover:bg-failure/80':
+ props.danger && !isPending(),
+ 'bg-surface-2 text-ink hover:bg-surface-3':
+ !props.danger && !props.active && !isPending(),
+ 'bg-accent-2 text-panel hover:bg-accent-3':
+ !props.danger && props.active && !isPending(),
+ }}
+ >
+ {props.children}
+ </button>
+ );
+};
+
+function ScreenShareTile(props: { participant: RemoteParticipant }) {
+ const callCtx = useCallContext();
+ const screenTrack = () => {
+ callCtx.trackVersion();
+ return props.participant.getTrackPublication(Track.Source.ScreenShare)
+ ?.track;
+ };
+
+ return (
+ <div class="relative flex items-center justify-center rounded-lg overflow-hidden bg-surface-2">
+ <TrackView track={screenTrack()} fit="contain" />
+ <div class="absolute bottom-1 left-1 px-1.5 py-0.5 rounded bg-surface-0/70 text-ink text-xs truncate max-w-[80%]">
+ {props.participant.identity}'s screen
+ </div>
+ </div>
+ );
+}
+
+export function CallOverlay(props: { onLeave: () => void }) {
+ const callCtx = useCallContext();
+
+ const participants = () =>
+ Array.from(callCtx.remoteParticipants().values()).filter((p) => !p.isAgent);
+
+ const isLocalSpeaking = () => callCtx.isLocalSpeaking();
+
+ const localVideoTrack = () => {
+ callCtx.trackVersion();
+ const r = callCtx.room();
+ if (!r || callCtx.isVideoMuted()) return undefined;
+ return r.localParticipant.getTrackPublication(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)
+ ?.track;
+ };
+
+ const remoteScreenShares = () => {
+ callCtx.trackVersion();
+ return participants().filter((p) => {
+ const pub = p.getTrackPublication(Track.Source.ScreenShare);
+ return pub?.isSubscribed && !pub.isMuted;
+ });
+ };
+
+ const hasAnyScreenShare = () =>
+ callCtx.isScreenSharing() || remoteScreenShares().length > 0;
+
+ const gridCols = () => {
+ const count = participants().length + 1; // +1 for local
+ if (count <= 1) return 'grid-cols-1';
+ if (count <= 4) return 'grid-cols-2';
+ return 'grid-cols-3';
+ };
+
+ return (
+ <div class="flex flex-col h-full bg-surface-0">
+ {/* Screen share area */}
+ <Show when={hasAnyScreenShare()}>
+ <div class="flex-1 min-h-0 p-2">
+ <div class="h-full rounded-lg overflow-hidden bg-surface-2 flex items-center justify-center">
+ <Show when={callCtx.isScreenSharing()}>
+ <div class="relative w-full h-full">
+ <TrackView track={localScreenTrack()} fit="contain" />
+ <div class="absolute bottom-1 left-1 px-1.5 py-0.5 rounded bg-surface-0/70 text-ink text-xs">
+ Your screen
+ </div>
+ </div>
+ </Show>
+ <For each={remoteScreenShares()}>
+ {(participant) => <ScreenShareTile participant={participant} />}
+ </For>
+ </div>
+ </div>
+ </Show>
+
+ {/* Participants grid */}
+ <div
+ class={`${hasAnyScreenShare() ? 'h-[140px] shrink-0' : 'flex-1 min-h-0'} grid ${gridCols()} gap-2 p-2 auto-rows-fr overflow-hidden`}
+ >
+ {/* Local participant */}
+ <div
+ class="relative flex items-center justify-center rounded-lg overflow-hidden bg-surface-2 min-h-[120px]"
+ classList={{
+ 'ring-2 ring-accent-2': isLocalSpeaking(),
+ }}
+ >
+ <Show
+ when={!callCtx.isVideoMuted()}
+ fallback={
+ <div class="flex items-center justify-center w-full h-full p-4">
+ <div class="w-12 h-12 rounded-full bg-surface-3 flex items-center justify-center text-ink-muted text-lg font-medium">
+ You
+ </div>
+ </div>
+ }
+ >
+ <TrackView track={localVideoTrack()} mirror />
+ </Show>
+ <div class="absolute bottom-1 left-1 px-1.5 py-0.5 rounded bg-surface-0/70 text-ink text-xs">
+ You
+ </div>
+ </div>
+
+ <For each={participants()}>
+ {(participant) => <ParticipantTile participant={participant} />}
+ </For>
+ </div>
+
+ {/* Controls bar */}
+ <div class="flex items-center justify-center gap-3 p-3 bg-surface-1 border-t border-edge">
+ <ControlButton
+ onClick={() => callCtx.toggleAudio()}
+ active={!callCtx.isAudioMuted()}
+ >
+ <Show
+ when={!callCtx.isAudioMuted()}
+ fallback={<MicrophoneSlash class="w-5 h-5" />}
+ >
+ <Microphone class="w-5 h-5" />
+ </Show>
+ </ControlButton>
+
+ <ControlButton
+ onClick={() => callCtx.toggleVideo()}
+ active={!callCtx.isVideoMuted()}
+ >
+ <Show
+ when={!callCtx.isVideoMuted()}
+ fallback={<VideoCameraSlash class="w-5 h-5" />}
+ >
+ <VideoCamera class="w-5 h-5" />
+ </Show>
+ </ControlButton>
+
+ <ControlButton
+ onClick={() => callCtx.toggleScreenShare()}
+ active={callCtx.isScreenSharing()}
+ >
+ <Screencast class="w-5 h-5" />
+ </ControlButton>
+
+ <ControlButton onClick={props.onLeave} danger>
+ <PhoneDisconnect class="w-5 h-5" />
+ </ControlButton>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/channel/Call/index.ts b/js/app/packages/channel/Call/index.ts
new file mode 100644
index 0000000000..c70c2fa1ab
--- /dev/null
+++ b/js/app/packages/channel/Call/index.ts
@@ -0,0 +1,8 @@
+export {
+ CallProvider,
+ useCallContext,
+ useCallContextOptional,
+} from './CallContext';
+export type { CallState } from './CallContext';
+export { useCall } from './useCall';
+export { CallOverlay } from './CallOverlay';
diff --git a/js/app/packages/channel/Call/useCall.ts b/js/app/packages/channel/Call/useCall.ts
new file mode 100644
index 0000000000..32c9fb006d
--- /dev/null
+++ b/js/app/packages/channel/Call/useCall.ts
@@ -0,0 +1,51 @@
+import { useJoinCallMutation, useLeaveCallMutation } from '@queries/call/call';
+import { useCallContext } from './CallContext';
+
+/**
+ * Hook that orchestrates joining/leaving calls by combining
+ * the API mutations with the LiveKit room connection.
+ */
+export function useCall(channelId: () => string) {
+ const callCtx = useCallContext();
+ const joinMutation = useJoinCallMutation();
+ const leaveMutation = useLeaveCallMutation();
+
+ async function joinCall() {
+ const id = channelId();
+ const tokenResponse = await joinMutation.mutateAsync(id);
+ try {
+ await callCtx.connect(tokenResponse);
+ } catch (e) {
+ // Roll back the backend join so it doesn't think we're in the call
+ try {
+ await leaveMutation.mutateAsync(id);
+ } catch (leaveErr) {
+ console.error(
+ 'Failed to roll back join after connect failure',
+ leaveErr
+ );
+ }
+ throw e;
+ }
+ }
+
+ async function leaveCall() {
+ const id = channelId();
+ try {
+ await callCtx.disconnect();
+ } finally {
+ await leaveMutation.mutateAsync(id);
+ }
+ }
+
+ return {
+ joinCall,
+ leaveCall,
+ isJoining: () => joinMutation.isPending,
+ isLeaving: () => leaveMutation.isPending,
+ isInCall: callCtx.isInCall,
+ isInThisChannel: () =>
+ callCtx.isInCall() && callCtx.activeChannelId() === channelId(),
+ callCtx,
+ };
+}
diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.ts
index b2152d00de..df0499fc7d 100644
--- a/js/app/packages/core/constant/featureFlags.ts
+++ b/js/app/packages/core/constant/featureFlags.ts
@@ -299,3 +299,14 @@ export const ENABLE_CLIENT_EMAIL_SIGNAL_FILTER = resolveFeatureFlag(
'ENABLE_CLIENT_EMAIL_SIGNAL_FILTER',
false
);
+
+// skips over posthog and sets the ENABLE_CALLS feature to true if we are in dev mode
+const ENABLE_CALLS_OVERRIDE = DEV_MODE_ENV ? true : undefined;
+
+export function ENABLE_CALLS(): boolean {
+ if (ENABLE_CALLS_OVERRIDE !== undefined) {
+ return ENABLE_CALLS_OVERRIDE;
+ }
+
+ return analytics.posthog.isFeatureEnabled('enable-calls') ?? false;
+}
diff --git a/js/app/packages/core/constant/servers.ts b/js/app/packages/core/constant/servers.ts
index 186f5e6b32..52f9f1bd58 100644
--- a/js/app/packages/core/constant/servers.ts
+++ b/js/app/packages/core/constant/servers.ts
@@ -62,10 +62,21 @@ function selectLocalServers(): Servers {
}
const servers = selectedLocalServers
.split(',')
- .filter(assertValidName)
- .reduce((acc: Servers, key: keyof Servers) => {
- acc[key] = serverHostLocal[key];
- console.log(`Using local server ${key}: ${acc}`);
+ .reduce((acc: Servers, entry: string) => {
+ // Support "service-name:port" to override the default local port
+ const [name, portOverride] = entry.split(':') as [
+ string,
+ string | undefined,
+ ];
+ if (!assertValidName(name)) return acc;
+ if (portOverride) {
+ const url = new URL(serverHostLocal[name]);
+ url.port = portOverride;
+ acc[name] = url.toString().replace(/\/$/, '');
+ } else {
+ acc[name] = serverHostLocal[name];
+ }
+ console.log(`Using local server ${name}: ${acc[name]}`);
return acc;
}, serverHostRemote);
return servers;
diff --git a/js/app/packages/queries/call/call.ts b/js/app/packages/queries/call/call.ts
new file mode 100644
index 0000000000..3e64a07cbf
--- /dev/null
+++ b/js/app/packages/queries/call/call.ts
@@ -0,0 +1,25 @@
+import { throwOnErr } from '@core/util/maybeResult';
+import { callServiceClient } from '@service-call/client';
+import { useMutation } from '@tanstack/solid-query';
+
+export function useJoinCallMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (channelId: string) =>
+ await throwOnErr(() => callServiceClient.getOrCreateCall(channelId)),
+ onError(error: Error) {
+ console.error('failed to join call', error);
+ },
+ }));
+}
+
+export function useLeaveCallMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: (channelId: string) =>
+ throwOnErr(() => callServiceClient.leaveCall(channelId)),
+ onError(error: Error) {
+ console.error('failed to leave call', error);
+ },
+ }));
+}
diff --git a/js/app/packages/service-clients/service-call/client.ts b/js/app/packages/service-clients/service-call/client.ts
index 7690501745..d2cd56b770 100644
--- a/js/app/packages/service-clients/service-call/client.ts
+++ b/js/app/packages/service-clients/service-call/client.ts
@@ -1,30 +1,12 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import { mapOk } from '@core/util/maybeResult';
+import type { CallTokenResponse } from '@service-storage/generated/schemas/callTokenResponse';
+import type { LeaveCallResponse } from '@service-storage/generated/schemas/leaveCallResponse';
+export type { CallTokenResponse, LeaveCallResponse };
const host: string = SERVER_HOSTS['document-storage-service'];
-export type CallTokenResponse = {
- callId: string;
- channelId: string;
- token: string;
- roomName: string;
- serverUrl: string;
-};
-
-export type LeaveCallResponse = {
- callEnded: boolean;
-};
-
-export type TranscriptSegmentPayload = {
- segmentId: string;
- speakerId: string;
- content: string;
- startedAt: string;
- endedAt: string | null;
- isFinal: boolean;
-};
-
export const callServiceClient = {
async getOrCreateCall(channelId: string) {
return mapOk(
@@ -43,14 +25,4 @@ export const callServiceClient = {
(result) => result
);
},
-
- async sendTranscriptSegment(
- channelId: string,
- segment: TranscriptSegmentPayload
- ) {
- return fetchWithToken(`${host}/call/${channelId}/transcript`, {
- method: 'POST',
- body: JSON.stringify(segment),
- });
- },
};