feat: inbound calls in cal ai (#23890)

* feat: lang support

* fix: type errors

* feat: select voice agent

* refactor: address feedback

* refactor: address feedback

* refactor: missing import

* fix: types

* feat: add inbound calls

* chore: formatting

* chore

* feat: finish inbound call

* chore: formatting

* fix: update bug

* fix: types

* refactor: Agent Configuration Sheet (#23930)

* refactor: agent configuration sheet

* chore: use default phone numbre

* refactor: improvements

* refactor: improvements

* fix: types

* fix: feedback

* chore:

* fix: feedback

* fix: prompt

* fix: review

* fix: review

* refactor: class

* refactor: class

* refactor: rename

* Update apps/web/public/static/locales/en/common.json

* Update apps/web/public/static/locales/en/common.json

* chore: update set value

* fix: remove index

* fix: type error

* fix: update tetss

* fix: use logger

* refactor: don't use static

* fix: type

* fix: schema

* refactor:

---------

Co-authored-by: Carina Wollendorfer <[email protected]>
This commit is contained in:
Udit TakkarandCarina Wollendorfer authored and GitHub committed 2025-10-09 11:40:37 +01:00
1 parent bec49ef417
commit aa48e72c12
74 files changed
+2980 -1680

No files matched your search

@@ -3,7 +3,7 @@ import stripe from "@calcom/features/ee/payments/server/stripe";
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { prisma } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import { CHECKOUT_SESSION_TYPES } from "../../constants";
@@ -100,7 +100,8 @@ async function handleCalAIPhoneNumberSubscription(
throw new HttpCode(400, "Missing agentId for phone number subscription");
}
const agent = await PrismaAgentRepository.findByIdWithUserAccess({
const agentRepo = new PrismaAgentRepository(prisma);
const agent = await agentRepo.findByIdWithUserAccess({
agentId,
userId,
teamId: teamId ?? undefined,
@@ -130,7 +131,8 @@ async function handleCalAIPhoneNumberSubscription(
throw new HttpCode(400, "Invalid subscription data");
}
const newNumber = await PrismaPhoneNumberRepository.createPhoneNumber({
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
const newNumber = await phoneNumberRepo.createPhoneNumber({
userId,
teamId: teamId ?? undefined,
phoneNumber: calAIPhoneNumber.phone_number,
@@ -144,7 +146,7 @@ async function handleCalAIPhoneNumberSubscription(
try {
console.log("Attempting to link agent to phone number:", { agentId, phoneNumberId: newNumber.id });
const agent = await PrismaAgentRepository.findByIdWithUserAccess({
const agent = await agentRepo.findByIdWithUserAccess({
agentId,
userId,
});
@@ -1,5 +1,6 @@
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import prisma from "@calcom/prisma";
import type { LazyModule, SWHMap } from "./__handler";
import { HttpCode } from "./__handler";
@@ -12,8 +13,9 @@ const STRIPE_TEAM_PRODUCT_ID = process.env.STRIPE_TEAM_PRODUCT_ID || "";
const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) => {
const subscription = data.object;
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
const phoneNumber = await PrismaPhoneNumberRepository.findByStripeSubscriptionId({
const phoneNumber = await phoneNumberRepo.findByStripeSubscriptionId({
stripeSubscriptionId: subscription.id,
});
@@ -62,7 +64,7 @@ const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) =
async function handleCalAIPhoneNumberSubscriptionDeleted(
subscription: Data["object"],
phoneNumber: NonNullable<Awaited<ReturnType<typeof PrismaPhoneNumberRepository.findByStripeSubscriptionId>>>
phoneNumber: NonNullable<Awaited<ReturnType<PrismaPhoneNumberRepository["findByStripeSubscriptionId"]>>>
) {
if (!subscription.id) {
throw new HttpCode(400, "Subscription ID not found");
@@ -1,5 +1,5 @@
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import { prisma } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { SWHMap } from "./__handler";
@@ -14,7 +14,8 @@ const handler = async (data: Data) => {
throw new HttpCode(400, "Subscription ID not found");
}
const phoneNumber = await PrismaPhoneNumberRepository.findByStripeSubscriptionId({
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
const phoneNumber = await phoneNumberRepo.findByStripeSubscriptionId({
stripeSubscriptionId: subscription.id,
});
File diff suppressed because it is too large. Load diff
@@ -1,13 +1,7 @@
import { getCoreRowModel, getSortedRowModel, useReactTable, type ColumnDef } from "@tanstack/react-table";
import { useMemo, useState } from "react";
import {
DataTableProvider,
DataTableWrapper,
DataTableToolbar,
DataTableFilters,
useDataTable,
} from "@calcom/features/data-table";
import { DataTableProvider, DataTableWrapper } from "@calcom/features/data-table";
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
@@ -21,8 +15,8 @@ import { useVoicePreview } from "../hooks/useVoicePreview";
type Voice = {
voice_id: string;
voice_name: string;
provider: 'elevenlabs' | 'openai' | 'deepgram';
gender: 'male' | 'female';
provider: "elevenlabs" | "openai" | "deepgram";
gender: "male" | "female";
accent?: string;
age?: string;
preview_audio_url?: string;
@@ -35,7 +29,13 @@ type VoiceSelectionDialogProps = {
onVoiceSelect: (voiceId: string) => void;
};
function VoiceSelectionTable({ selectedVoiceId, onVoiceSelect }: { selectedVoiceId?: string; onVoiceSelect: (voiceId: string) => void }) {
function VoiceSelectionTable({
selectedVoiceId,
onVoiceSelect,
}: {
selectedVoiceId?: string;
onVoiceSelect: (voiceId: string) => void;
}) {
return (
<DataTableProvider useSegments={useSegments} defaultPageSize={1000}>
<VoiceSelectionContent selectedVoiceId={selectedVoiceId} onVoiceSelect={onVoiceSelect} />
@@ -43,14 +43,19 @@ function VoiceSelectionTable({ selectedVoiceId, onVoiceSelect }: { selectedVoice
);
}
function VoiceSelectionContent({ selectedVoiceId, onVoiceSelect }: { selectedVoiceId?: string; onVoiceSelect: (voiceId: string) => void }) {
function VoiceSelectionContent({
selectedVoiceId,
onVoiceSelect,
}: {
selectedVoiceId?: string;
onVoiceSelect: (voiceId: string) => void;
}) {
const { t } = useLocale();
const { playingVoiceId, handlePlayVoice } = useVoicePreview();
const [rowSelection, setRowSelection] = useState({});
const { data: voices, isLoading } = trpc.viewer.aiVoiceAgent.listVoices.useQuery();
const handleUseVoice = (voiceId: string) => {
onVoiceSelect(voiceId);
showToast("Voice selected successfully", "success");
@@ -78,16 +83,16 @@ function VoiceSelectionContent({ selectedVoiceId, onVoiceSelect }: { selectedVoi
onClick={() => handlePlayVoice(row.original.preview_audio_url, row.original.voice_id)}
className="rounded-full">
{playingVoiceId === row.original.voice_id ? (
<Icon name="pause" className="h-3 w-3 text-default" />
<Icon name="pause" className="text-default h-3 w-3" />
) : (
<Icon name="play" className="h-3 w-3 text-default" />
<Icon name="play" className="text-default h-3 w-3" />
)}
</Button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-subtle rounded-full flex items-center justify-center">
<Icon name="user" className="h-5 w-5 text-default" />
<div className="bg-subtle flex h-10 w-10 items-center justify-center rounded-full">
<Icon name="user" className="text-default h-5 w-5" />
</div>
<span className="font-medium text-emphasis">{row.original.voice_name}</span>
<span className="text-emphasis font-medium">{row.original.voice_name}</span>
</div>
</div>
),
@@ -100,24 +105,22 @@ function VoiceSelectionContent({ selectedVoiceId, onVoiceSelect }: { selectedVoi
cell: ({ row }) => (
<div className="flex gap-2 text-sm">
{row.original.accent && (
<span className="px-2 py-1 bg-subtle text-default rounded-md text-xs">
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
{row.original.accent}
</span>
)}
{row.original.gender && (
<span className="px-2 py-1 bg-subtle text-default rounded-md text-xs">
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
{row.original.gender}
</span>
)}
{row.original.provider && (
<span className="px-2 py-1 bg-subtle text-default rounded-md text-xs">
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
{row.original.provider}
</span>
)}
{row.original.age && (
<span className="px-2 py-1 bg-subtle text-default rounded-md text-xs">
{row.original.age}
</span>
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">{row.original.age}</span>
)}
</div>
),
@@ -127,9 +130,7 @@ function VoiceSelectionContent({ selectedVoiceId, onVoiceSelect }: { selectedVoi
accessorKey: "voice_id",
header: t("voice_id"),
size: 200,
cell: ({ row }) => (
<span className="text-sm text-muted font-mono">{row.original.voice_id}</span>
),
cell: ({ row }) => <span className="text-muted font-mono text-sm">{row.original.voice_id}</span>,
},
{
id: "actions",
@@ -142,13 +143,7 @@ function VoiceSelectionContent({ selectedVoiceId, onVoiceSelect }: { selectedVoi
color={selectedVoiceId === row.original.voice_id ? "primary" : "secondary"}
onClick={() => handleUseVoice(row.original.voice_id)}
className="whitespace-nowrap">
{selectedVoiceId === row.original.voice_id ? (
<>
{t("current_voice")}
</>
) : (
t("use_voice")
)}
{selectedVoiceId === row.original.voice_id ? <>{t("current_voice")}</> : t("use_voice")}
</Button>
),
},
@@ -171,7 +166,7 @@ function VoiceSelectionContent({ selectedVoiceId, onVoiceSelect }: { selectedVoi
});
return (
<div className="max-h-[500px] overflow-auto border border-subtle rounded-lg">
<div className="border-subtle max-h-[500px] overflow-auto rounded-lg border">
<DataTableWrapper<Voice>
testId="voice-selection-data-table"
table={table}
@@ -199,17 +194,11 @@ export function VoiceSelectionDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent enableOverflow className="sm:max-w-7xl h-[80vh] flex flex-col p-6">
<DialogHeader
title={t("select_voice")}
subtitle={t("choose_a_voice_for_your_agent")}
/>
<DialogContent enableOverflow className="flex h-[80vh] flex-col p-6 sm:max-w-7xl">
<DialogHeader title={t("select_voice")} subtitle={t("choose_a_voice_for_your_agent")} />
<div className="flex-1 overflow-hidden min-h-0 mt-4">
<VoiceSelectionTable
selectedVoiceId={selectedVoiceId}
onVoiceSelect={handleVoiceSelect}
/>
<div className="mt-4 min-h-0 flex-1 overflow-hidden">
<VoiceSelectionTable selectedVoiceId={selectedVoiceId} onVoiceSelect={handleVoiceSelect} />
</div>
</DialogContent>
</Dialog>
@@ -454,8 +454,7 @@ export function WebCallDialog({
type="button"
onClick={handleStartCall}
loading={createWebCallMutation.isPending || callStatus === "connecting"}
disabled={!hasCredits || createWebCallMutation.isPending || callStatus === "connecting"}
>
disabled={!hasCredits || createWebCallMutation.isPending || callStatus === "connecting"}>
<Icon name="phone" className="mr-2 h-4 w-4" />
{callStatus === "connecting" ? t("connecting") : t("start_web_call")}
</Button>
@@ -9,12 +9,12 @@ import type { WorkflowPermissions } from "@calcom/lib/server/repository/workflow
import type { WorkflowActions } from "@calcom/prisma/enums";
import { WorkflowTemplates } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { FormCard, FormCardBody } from "@calcom/ui/components/card";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { useAgentsData } from "../hooks/useAgentsData";
import { isCalAIAction, isSMSAction } from "../lib/actionHelperFunctions";
import type { FormValues } from "../pages/workflow";
import { AddActionDialog } from "./AddActionDialog";
@@ -58,8 +58,6 @@ export default function WorkflowDetailsPage(props: Props) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [eventTypeId]);
const steps = form.getValues("steps") || [];
const addAction = (
action: WorkflowActions,
sendTo?: string,
@@ -96,19 +94,14 @@ export default function WorkflowDetailsPage(props: Props) {
includeCalendarEvent: false,
verifiedAt: SCANNING_WORKFLOW_STEPS ? null : new Date(),
agentId: null,
inboundAgentId: null,
};
steps?.push(step);
form.setValue("steps", steps);
};
const agentQueriesTrpc = trpc.useQueries((t) =>
steps.map((step, index) => {
const watchedAgentId = form.watch(`steps.${index}.agentId`);
const agentId = step?.agentId ?? watchedAgentId ?? null;
return t.viewer.aiVoiceAgent.get({ id: agentId ?? "" }, { enabled: !!agentId });
})
);
const { outboundAgentQueries: agentQueriesTrpc, inboundAgentQueries: inboundAgentQueriesTrpc } =
useAgentsData(form);
return (
<>
@@ -145,6 +138,8 @@ export default function WorkflowDetailsPage(props: Props) {
{form.getValues("steps")?.map((step, index) => {
const agentData = agentQueriesTrpc[index]?.data;
const isAgentLoading = agentQueriesTrpc[index]?.isPending;
const inboundAgentData = inboundAgentQueriesTrpc[index]?.data;
const isInboundAgentLoading = inboundAgentQueriesTrpc[index]?.isPending;
return (
<div key={index}>
@@ -207,6 +202,9 @@ export default function WorkflowDetailsPage(props: Props) {
isDeleteStepDialogOpen={isDeleteStepDialogOpen}
isAgentLoading={isAgentLoading}
agentData={agentData}
inboundAgentData={inboundAgentData}
isInboundAgentLoading={isInboundAgentLoading}
allOptions={allOptions}
/>
</FormCardBody>
</FormCard>
@@ -67,10 +67,10 @@ import emailRatingTemplate from "../lib/reminders/templates/emailRatingTemplate"
import emailReminderTemplate from "../lib/reminders/templates/emailReminderTemplate";
import type { FormValues } from "../pages/workflow";
import "../style/styles.css";
import { AgentConfigurationSheet } from "./AgentConfigurationSheet";
import { TestPhoneCallDialog } from "./TestPhoneCallDialog";
import { TimeTimeUnitInput } from "./TimeTimeUnitInput";
import { WebCallDialog } from "./WebCallDialog";
import { AgentConfigurationSheet } from "./agent-configuration/AgentConfigurationSheet";
type User = RouterOutputs["viewer"]["me"]["get"];
@@ -92,6 +92,8 @@ type WorkflowStepProps = {
isDeleteStepDialogOpen?: boolean;
agentData?: RetellAgentWithDetails;
isAgentLoading?: boolean;
inboundAgentData?: RetellAgentWithDetails;
isInboundAgentLoading?: boolean;
};
const getTimeSectionText = (trigger: WorkflowTriggerEvents, t: TFunction) => {
@@ -157,6 +159,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
allOptions,
agentData,
isAgentLoading,
inboundAgentData,
isInboundAgentLoading: _isInboundAgentLoading,
isDeleteStepDialogOpen,
setIsDeleteStepDialogOpen,
onSaveWorkflow,
@@ -171,10 +175,10 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
const { data: userTeams } = trpc.viewer.teams.list.useQuery({}, { enabled: !teamId });
const [agentConfigurationSheet, setAgentConfigurationSheet] = useState<{
open: boolean;
activeTab?: "prompt" | "phoneNumber";
activeTab?: "outgoingCalls" | "phoneNumber" | "incomingCalls";
}>({
open: false,
activeTab: "prompt",
activeTab: "outgoingCalls",
});
const creditsTeamId = userTeams?.find(
@@ -210,12 +214,15 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
});
const stepAgentId = step?.agentId || form.watch(`steps.${step ? step.stepNumber - 1 : 0}.agentId`) || null;
const stepInboundAgentId =
step?.inboundAgentId || form.watch(`steps.${step ? step.stepNumber - 1 : 0}.inboundAgentId`) || null;
const updateAgentMutation = trpc.viewer.aiVoiceAgent.update.useMutation({
onSuccess: async () => {
showToast(t("agent_updated_successfully"), "success");
if (stepAgentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: stepAgentId });
const currentAgentId = stepAgentId || stepInboundAgentId;
if (currentAgentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: currentAgentId });
}
},
onError: (error: { message: string }) => {
@@ -227,8 +234,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
onSuccess: async () => {
showToast(t("phone_number_unsubscribed_successfully"), "success");
setIsUnsubscribeDialogOpen(false);
if (stepAgentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: stepAgentId });
const currentAgentId = stepAgentId || stepInboundAgentId;
if (currentAgentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: currentAgentId });
}
},
onError: (error: { message: string }) => {
@@ -844,7 +852,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
return;
}
if (!props.readOnly) {
setAgentConfigurationSheet({ open: true, activeTab: "prompt" });
setAgentConfigurationSheet({ open: true, activeTab: "outgoingCalls" });
}
}}>
<div>
@@ -962,7 +970,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
<DropdownItem
type="button"
StartIcon="pencil"
onClick={() => setAgentConfigurationSheet({ open: true, activeTab: "prompt" })}>
onClick={() =>
setAgentConfigurationSheet({ open: true, activeTab: "outgoingCalls" })
}>
{t("edit")}
</DropdownItem>
</DropdownMenuItem>
@@ -1519,11 +1529,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
activeTab={agentConfigurationSheet.activeTab}
onOpenChange={(val) => setAgentConfigurationSheet((prev) => ({ ...prev, open: val }))}
agentId={stepAgentId}
inboundAgentId={stepInboundAgentId}
agentData={agentData}
inboundAgentData={inboundAgentData}
onUpdate={(data) => {
updateAgentMutation.mutate({
//eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: stepAgentId!,
id: data.id,
teamId: teamId,
generalPrompt: data.generalPrompt,
beginMessage: data.beginMessage,
@@ -1536,6 +1547,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
workflowId={params?.workflow as string}
workflowStepId={step?.id}
form={form}
eventTypeOptions={props.allOptions}
/>
)}
@@ -1543,7 +1555,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
<TestPhoneCallDialog
open={isTestAgentDialogOpen}
onOpenChange={setIsTestAgentDialogOpen}
agentId={stepAgentId}
agentId={stepAgentId || ""}
teamId={teamId}
form={form}
/>
@@ -1553,7 +1565,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
<WebCallDialog
open={isWebCallDialogOpen}
onOpenChange={setIsWebCallDialogOpen}
agentId={stepAgentId}
agentId={stepAgentId || ""}
teamId={teamId}
isOrganization={props.isOrganization}
form={form}
@@ -0,0 +1,374 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import type { Language } from "@calcom/features/calAIPhone/providers/retellAI/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { ToggleGroup } from "@calcom/ui/components/form";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetBody,
SheetFooter,
} from "@calcom/ui/components/sheet";
import { showToast } from "@calcom/ui/components/toast";
import type { FormValues } from "../../pages/workflow";
import { WebCallDialog } from "../WebCallDialog";
import { IncomingCallsTab } from "./components/tabs/IncomingCallsTab";
import { OutgoingCallsTab } from "./components/tabs/OutgoingCallsTab";
import { PhoneNumberTab } from "./components/tabs/PhoneNumberTab";
import { useAgentForms } from "./hooks/useAgentForms";
import type { AgentFormValues } from "./types/schemas";
import { restorePromptComplexity } from "./utils/promptUtils";
type AgentConfigurationSheetProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
agentId?: string | null;
inboundAgentId?: string | null;
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
onUpdate: (data: AgentFormValues & { id: string }) => void;
readOnly?: boolean;
teamId?: number;
isOrganization?: boolean;
workflowId?: string;
workflowStepId?: number;
activeTab?: "outgoingCalls" | "phoneNumber" | "incomingCalls";
form: UseFormReturn<FormValues>;
eventTypeOptions?: Option[];
};
export function AgentConfigurationSheet({
open,
activeTab: _activeTab,
onOpenChange,
agentId,
inboundAgentId,
agentData,
inboundAgentData,
readOnly = false,
teamId,
isOrganization = false,
workflowId,
workflowStepId,
form,
eventTypeOptions = [],
}: AgentConfigurationSheetProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const [activeTab, setActiveTab] = useState<"outgoingCalls" | "phoneNumber" | "incomingCalls">(
_activeTab ?? "outgoingCalls"
);
const [isWebCallDialogOpen, setIsWebCallDialogOpen] = useState(false);
const activeAgentId = activeTab === "incomingCalls" ? inboundAgentId : agentId;
const { outboundAgentForm, inboundAgentForm } = useAgentForms({ agentData, inboundAgentData });
const updateAgentMutation = trpc.viewer.aiVoiceAgent.update.useMutation({
onSuccess: async () => {
if (activeAgentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: activeAgentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const handleAgentUpdate = async (data: AgentFormValues) => {
if (!agentId) return;
const updatePayload = {
generalPrompt: restorePromptComplexity(data.generalPrompt),
beginMessage: data.beginMessage,
language: data.language as Language,
voiceId: data.voiceId,
};
await updateAgentMutation.mutateAsync({
id: agentId,
teamId: teamId,
...updatePayload,
});
};
const handleInboundAgentUpdate = async (data: AgentFormValues) => {
if (!inboundAgentId) return;
const updatePayload = {
generalPrompt: restorePromptComplexity(data.generalPrompt),
beginMessage: data.beginMessage,
language: data.language as Language,
voiceId: data.voiceId,
};
await updateAgentMutation.mutateAsync({
id: inboundAgentId,
teamId: teamId,
...updatePayload,
});
};
return (
<>
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="sm:max-w-xl">
<SheetHeader showCloseButton={false} className="w-full">
<SheetTitle className="mb-6">{t("cal_ai_agent_configuration")}</SheetTitle>
<ToggleGroup
onValueChange={(val) => {
setActiveTab((val || "outgoingCalls") as "outgoingCalls" | "phoneNumber" | "incomingCalls");
}}
value={activeTab}
options={[
{ value: "outgoingCalls", label: t("outgoing_calls") },
{ value: "phoneNumber", label: t("phone_number") },
{ value: "incomingCalls", label: t("incoming_calls") },
]}
isFullWidth={true}
/>
</SheetHeader>
<SheetBody className="px-0">
{activeTab === "outgoingCalls" && (
<OutgoingCallsTab outboundAgentForm={outboundAgentForm} readOnly={readOnly} />
)}
{activeTab === "phoneNumber" && (
<PhoneNumberTab
agentData={agentData}
agentId={agentId}
readOnly={readOnly}
teamId={teamId}
workflowId={workflowId}
isOrganization={isOrganization}
form={form}
/>
)}
{activeTab === "incomingCalls" && (
<IncomingCallsTab
agentData={agentData}
inboundAgentData={inboundAgentData}
inboundAgentId={inboundAgentId}
inboundAgentForm={inboundAgentForm}
form={form}
eventTypeOptions={eventTypeOptions}
readOnly={readOnly}
teamId={teamId}
workflowStepId={workflowStepId}
/>
)}
</SheetBody>
<SheetFooter>
<div className="mr-auto">
<Dropdown>
<DropdownMenuTrigger asChild>
<Button
color="secondary"
className="rounded-[10px]"
disabled={readOnly}
EndIcon="chevron-down">
{t("test_agent")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="monitor"
onClick={() => {
setIsWebCallDialogOpen(true);
}}>
{t("web_call")}
</DropdownItem>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
</div>
<Button
className="justify-center"
type="button"
color="secondary"
onClick={() => onOpenChange(false)}>
{t("cancel")}
</Button>
<Button
type="button"
className="justify-center"
onClick={() => {
if (activeTab === "incomingCalls" && inboundAgentId) {
inboundAgentForm.handleSubmit(handleInboundAgentUpdate)();
} else if (activeTab === "outgoingCalls" && agentId) {
outboundAgentForm.handleSubmit(handleAgentUpdate)();
}
}}
disabled={
readOnly ||
updateAgentMutation.isPending ||
(activeTab === "outgoingCalls" && !outboundAgentForm.formState.isDirty) ||
(activeTab === "incomingCalls" && !inboundAgentForm.formState.isDirty) ||
(activeTab === "outgoingCalls" && !agentId) ||
(activeTab === "incomingCalls" && !inboundAgentId)
}
loading={updateAgentMutation.isPending}>
{t("save")}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
{activeAgentId && (
<WebCallDialog
open={isWebCallDialogOpen}
onOpenChange={setIsWebCallDialogOpen}
agentId={activeAgentId}
teamId={teamId}
isOrganization={isOrganization}
form={form}
/>
)}
{/* <ToolsDialog
open={toolDialogOpen}
onOpenChange={setToolDialogOpen}
toolDraft={toolDraft}
setToolDraft={setToolDraft}
onSave={handleToolDialogSave}
isEditing={editingToolIndex !== null}
/> */}
</>
);
}
// const ToolsDialog = ({
// open,
// onOpenChange,
// toolDraft,
// setToolDraft,
// onSave,
// isEditing,
// }: {
// open: boolean;
// onOpenChange: (open: boolean) => void;
// toolDraft: ToolDraft | null;
// setToolDraft: (draft: ToolDraft) => void;
// onSave: () => void;
// isEditing: boolean;
// }) => {
// const { t } = useLocale();
// const TOOL_TYPES = [
// { label: t("Check Availability"), value: "check_availability_cal" },
// { label: t("Book Appointment"), value: "book_appointment_cal" },
// { label: t("End Call"), value: "end_call" },
// ];
// return (
// <Dialog open={open} onOpenChange={onOpenChange}>
// <DialogContent
// enableOverflow
// title={isEditing ? t("Edit Function") : t("Add Function")}
// type="creation">
// <div className="flex flex-col gap-4">
// <div>
// <Label>{t("Type")}</Label>
// <Select
// options={TOOL_TYPES}
// value={TOOL_TYPES.find((opt) => opt.value === toolDraft?.type) || null}
// onChange={(option) => setToolDraft((d: ToolDraft) => ({ ...d, type: option?.value || "" }))}
// placeholder={t("Select function type")}
// />
// </div>
// <div>
// <Label>{t("Name")}</Label>
// <TextField
// required
// value={toolDraft?.name || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, name: e.target.value }))}
// placeholder={t("Enter function name")}
// />
// </div>
// <div>
// <Label>{t("Description")}</Label>
// <TextArea
// value={toolDraft?.description || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, description: e.target.value }))}
// placeholder={t("Enter description (optional)")}
// />
// </div>
// {(toolDraft?.type === "check_availability_cal" || toolDraft?.type === "book_appointment_cal") && (
// <>
// <div>
// <Label>
// {t("API Key (Cal.com)")}
// <span className="text-red-500"> *</span>
// </Label>
// <TextField
// required
// value={toolDraft?.cal_api_key || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, cal_api_key: e.target.value }))}
// placeholder={t("Enter Cal.com API key")}
// />
// </div>
// <div>
// <Label>
// {t("Event Type ID (Cal.com)")}
// <span className="text-red-500"> *</span>
// </Label>
// <TextField
// required
// value={toolDraft?.event_type_id || ""}
// onChange={(e) =>
// setToolDraft((d: ToolDraft) => ({
// ...d,
// event_type_id: e.target.value ? Number(e.target.value) : null,
// }))
// }
// placeholder={t("Enter Event Type ID")}
// type="number"
// />
// </div>
// <div>
// <Label>
// {t("Timezone")}
// <span className="text-red-500"> *</span>
// </Label>
// <TextField
// required
// value={toolDraft?.timezone || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, timezone: e.target.value }))}
// placeholder={t("America/Los_Angeles")}
// />
// <p className="mt-1 text-xs text-subtle">{t("Required for Cal.com calendar integration")}</p>
// </div>
// </>
// )}
// </div>
// <DialogFooter showDivider>
// <Button type="button" color="secondary" onClick={() => onOpenChange(false)}>
// {t("Cancel")}
// </Button>
// <Button type="button" onClick={onSave}>
// {t("Save")}
// </Button>
// </DialogFooter>
// </DialogContent>
// </Dialog>
// );
// };
@@ -0,0 +1,134 @@
import { CAL_AI_PHONE_NUMBER_MONTHLY_PRICE } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { Dialog } from "@calcom/ui/components/dialog";
import { DialogContent, DialogHeader, DialogFooter as BaseDialogFooter } from "@calcom/ui/components/dialog";
import { Label } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
interface BuyNumberDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
agentId?: string | null;
workflowId?: string;
teamId?: number;
}
export function BuyNumberDialog({ open, onOpenChange, agentId, workflowId, teamId }: BuyNumberDialogProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const buyNumberMutation = trpc.viewer.phoneNumber.buy.useMutation({
onSuccess: async (data: { checkoutUrl?: string; message?: string; phoneNumber?: unknown }) => {
if (data.checkoutUrl) {
window.location.href = data.checkoutUrl;
} else if (data.phoneNumber) {
showToast(t("phone_number_purchased_successfully"), "success");
await utils.viewer.me.get.invalidate();
onOpenChange(false);
if (agentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
} else {
showToast(data.message || t("something_went_wrong"), "error");
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent type="creation">
<DialogHeader
title={t("buy_a_new_number")}
subtitle={t("buy_number_for_x_per_month", {
priceInDollars: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE,
})}
/>
<div className="flex flex-col">
<div>
<div>
<Alert
className="mb-4"
severity="info"
message={t("only_us_phone_numbers_can_be_purchased_here")}
/>
<Label>{t("supported_call_destinations")}</Label>
<div className="-mb-4 grid grid-cols-2 gap-x-8 gap-y-1 text-sm">
<div className="flex items-center gap-2">
<span className="text-xl">🇺🇸</span>
<span className="text-default">United States</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇮🇳</span>
<span className="text-default">India</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇦🇺</span>
<span className="text-default">Australia</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇩🇪</span>
<span className="text-default">Germany</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇪🇸</span>
<span className="text-default">Spain</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇬🇧</span>
<span className="text-default">United Kingdom</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇲🇽</span>
<span className="text-default">Mexico</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇫🇷</span>
<span className="text-default">France</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇯🇵</span>
<span className="text-default">Japan</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇨🇦</span>
<span className="text-default">Canada</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇮🇹</span>
<span className="text-default">Italy</span>
</div>
</div>
</div>
</div>
<BaseDialogFooter showDivider className="relative">
<Button onClick={() => onOpenChange(false)} color="secondary">
{t("close")}
</Button>
<Button
StartIcon="external-link"
onClick={() => {
if (!agentId || !workflowId) {
return;
}
buyNumberMutation.mutate({
agentId: agentId,
workflowId: workflowId,
teamId: teamId ?? undefined,
});
}}
loading={buyNumberMutation.isPending}
disabled={buyNumberMutation.isPending}>
{t("buy_us_number_button", { priceInDollars: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE })}
</Button>
</BaseDialogFooter>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,93 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
import { Dialog as UIDialog } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
interface ConfirmationDialogsProps {
cancellingNumberId: number | null;
setCancellingNumberId: (id: number | null) => void;
numberToDelete: string | null;
setNumberToDelete: (number: string | null) => void;
agentId?: string | null;
}
export function ConfirmationDialogs({
cancellingNumberId,
setCancellingNumberId,
numberToDelete,
setNumberToDelete,
agentId,
}: ConfirmationDialogsProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const cancelSubscriptionMutation = trpc.viewer.phoneNumber.cancel.useMutation({
onSuccess: async (data: { message?: string }) => {
showToast(data.message || t("phone_number_subscription_cancelled_successfully"), "success");
setCancellingNumberId(null);
await utils.viewer.me.get.invalidate();
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
setCancellingNumberId(null);
},
});
const deletePhoneNumberMutation = trpc.viewer.phoneNumber.delete.useMutation({
onSuccess: async () => {
showToast(t("phone_number_deleted_successfully"), "success");
setNumberToDelete(null);
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
setNumberToDelete(null);
},
});
const confirmCancelSubscription = () => {
if (cancellingNumberId) {
cancelSubscriptionMutation.mutate({ phoneNumberId: cancellingNumberId });
}
};
const confirmDeletePhoneNumber = () => {
if (numberToDelete) {
deletePhoneNumberMutation.mutate({ phoneNumber: numberToDelete });
}
};
return (
<>
<UIDialog open={cancellingNumberId !== null} onOpenChange={() => setCancellingNumberId(null)}>
<ConfirmationDialogContent
isPending={cancelSubscriptionMutation.isPending}
variety="danger"
title={t("cancel_phone_number_subscription")}
confirmBtnText={t("yes_cancel_subscription")}
onConfirm={confirmCancelSubscription}>
{t("cancel_phone_number_subscription_confirmation")}
</ConfirmationDialogContent>
</UIDialog>
<UIDialog open={numberToDelete !== null} onOpenChange={() => setNumberToDelete(null)}>
<ConfirmationDialogContent
isPending={deletePhoneNumberMutation.isPending}
variety="danger"
title={t("delete_phone_number")}
confirmBtnText={t("yes_delete_phone_number")}
onConfirm={confirmDeletePhoneNumber}>
{t("delete_phone_number_confirmation")}
</ConfirmationDialogContent>
</UIDialog>
</>
);
}
@@ -0,0 +1,252 @@
import { Controller } from "react-hook-form";
import type { UseFormReturn } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Dialog } from "@calcom/ui/components/dialog";
import { DialogContent, DialogHeader, DialogFooter as BaseDialogFooter } from "@calcom/ui/components/dialog";
import { Form, Label, Switch, TextField } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import type { PhoneNumberFormValues } from "../../types/schemas";
interface ImportNumberDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
phoneNumberForm: UseFormReturn<PhoneNumberFormValues>;
showAdvancedFields: boolean;
setShowAdvancedFields: (show: boolean) => void;
agentId?: string | null;
workflowId?: string;
teamId?: number;
}
export function ImportNumberDialog({
open,
onOpenChange,
phoneNumberForm,
showAdvancedFields,
setShowAdvancedFields,
agentId,
workflowId,
teamId,
}: ImportNumberDialogProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const importNumberMutation = trpc.viewer.phoneNumber.import.useMutation({
onSuccess: async () => {
showToast(t("phone_number_imported_successfully"), "success");
onOpenChange(false);
phoneNumberForm.reset();
await utils.viewer.me.get.invalidate();
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const handleImportPhoneNumber = (values: PhoneNumberFormValues) => {
if (!agentId) {
showToast(t("agent_required_for_import"), "error");
return;
}
const mutationPayload = {
...values,
workflowId: workflowId,
agentId: agentId,
teamId: teamId,
};
importNumberMutation.mutate(mutationPayload);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent enableOverflow type="creation">
<DialogHeader title={t("import_phone_number")} subtitle={t("import_phone_number_description")} />
<Form form={phoneNumberForm} handleSubmit={(values) => handleImportPhoneNumber(values)}>
<div className="space-y-6">
<Controller
name="phoneNumber"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="phoneNumber"
label={
<span className="flex items-center gap-1">
{t("phone_number")}
<Tooltip content={t("phone_number_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
required
type="text"
placeholder="eg:- +12088782105"
onChange={(e) => {
phoneNumberForm.setValue("phoneNumber", e?.target.value, { shouldDirty: true });
}}
/>
)}
/>
<Controller
name="terminationUri"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="terminationUri"
label={
<span className="flex items-center gap-1">
{t("termination_uri")}
<Tooltip content={t("termination_uri_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
required
type="text"
placeholder="sip.example.co.pstn.twilio.com"
onChange={(e) => {
phoneNumberForm.setValue("terminationUri", e?.target.value, { shouldDirty: true });
}}
/>
)}
/>
<div className="bg-muted rounded-xl p-1">
<div className="flex items-center justify-between p-2">
<Label className="text-emphasis mb-0 text-sm font-medium leading-none">
{t("advanced")}
</Label>
<Switch size="sm" checked={showAdvancedFields} onCheckedChange={setShowAdvancedFields} />
</div>
{showAdvancedFields && (
<div className="bg-default space-y-5 rounded-lg p-4">
<Controller
name="sipTrunkAuthUsername"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="sipTrunkAuthUsername"
label={
<span className="flex items-center gap-1">
{t("sip_trunk_username")}
<Tooltip content={t("sip_trunk_username_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
type="text"
onChange={(e) => {
phoneNumberForm.setValue("sipTrunkAuthUsername", e?.target.value, {
shouldDirty: true,
});
}}
/>
)}
/>
<Controller
name="sipTrunkAuthPassword"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="sipTrunkAuthPassword"
label={
<span className="flex items-center gap-1">
{t("sip_trunk_password")}
<Tooltip content={t("sip_trunk_password_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
type="password"
onChange={(e) => {
phoneNumberForm.setValue("sipTrunkAuthPassword", e?.target.value, {
shouldDirty: true,
});
}}
/>
)}
/>
<Controller
name="nickname"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="nickname"
label={
<span className="flex items-center gap-1">
{t("nickname")}
<Tooltip content={t("nickname_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
type="text"
onChange={(e) => {
phoneNumberForm.setValue("nickname", e?.target.value, { shouldDirty: true });
}}
/>
)}
/>
</div>
)}
</div>
{/* Having trouble importing section */}
<div className="rounded-lg border p-2">
<div className="flex items-start gap-3">
<Icon name="info" className="text-subtle mt-0.5 h-5 w-5 flex-shrink-0" />
<div className="flex-1">
<p className="text-emphasis text-sm font-medium">{t("having_trouble_importing")}</p>
<p className="text-subtle mt-1 text-sm leading-tight">
{t("learn_how_to_get_your_terminator")}
</p>
</div>
<Button
type="button"
color="secondary"
size="base"
EndIcon="external-link"
href="https://cal.com/help/importing/import-numbers"
target="_blank"
className="text-emphasis my-auto">
{t("learn")}
</Button>
</div>
</div>
</div>
<BaseDialogFooter showDivider className="relative">
<Button onClick={() => onOpenChange(false)} color="secondary">
{t("cancel")}
</Button>
<Button
type="submit"
loading={importNumberMutation.isPending}
disabled={importNumberMutation.isPending}>
{t("create")}
</Button>
</BaseDialogFooter>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,176 @@
import { useRef } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { AddVariablesDropdown } from "@calcom/ui/components/editor";
import { Input, Label, TextArea } from "@calcom/ui/components/form";
import { DYNAMIC_TEXT_VARIABLES } from "../../../../lib/constants";
import type { AgentFormValues } from "../../types/schemas";
import { LanguageSelector } from "./LanguageSelector";
import { VoiceSelector } from "./VoiceSelector";
interface AgentConfigFormProps {
form: UseFormReturn<AgentFormValues>;
readOnly?: boolean;
selectedVoiceId?: string;
onVoiceDialogOpen: () => void;
}
export function AgentConfigForm({
form,
readOnly = false,
selectedVoiceId,
onVoiceDialogOpen,
}: AgentConfigFormProps) {
const { t } = useLocale();
const generalPromptRef = useRef<HTMLTextAreaElement | null>(null);
const addVariableToGeneralPrompt = (variable: string) => {
if (generalPromptRef.current) {
const currentPrompt = generalPromptRef.current.value || "";
const cursorPosition = generalPromptRef.current.selectionStart || currentPrompt.length;
const variableName = `{${variable.toUpperCase().replace(/ /g, "_")}}`;
const newPrompt = `${currentPrompt.substring(
0,
cursorPosition
)}${variableName}${currentPrompt.substring(cursorPosition)}`;
form.setValue("generalPrompt", newPrompt, { shouldDirty: true, shouldTouch: true });
requestAnimationFrame(() => {
if (generalPromptRef.current) {
generalPromptRef.current.focus();
generalPromptRef.current.setSelectionRange(
cursorPosition + variableName.length,
cursorPosition + variableName.length
);
}
});
}
};
return (
<div className="space-y-4">
<LanguageSelector control={form.control} name="language" disabled={readOnly} />
<VoiceSelector
selectedVoiceId={selectedVoiceId}
onVoiceDialogOpen={onVoiceDialogOpen}
disabled={readOnly}
/>
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("initial_message")} *</Label>
<p className="text-subtle mb-1.5 text-xs">{t("initial_message_description")}</p>
<Input
type="text"
{...form.register("beginMessage")}
placeholder={t("hi_how_are_you_doing")}
disabled={readOnly}
/>
</div>
<div>
<div className="mb-1.5">
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("general_prompt")} *</Label>
<p className="text-subtle text-xs">{t("general_prompt_description")}</p>
</div>
<div className="flex items-center justify-between rounded-t-lg border border-b-0 p-2">
{!readOnly && (
<AddVariablesDropdown
addVariable={addVariableToGeneralPrompt}
variables={[...DYNAMIC_TEXT_VARIABLES, "number_to_call"]}
addVariableButtonClassName="border rounded-[10px] py-1 px-1"
/>
)}
</div>
<TextArea
{...form.register("generalPrompt")}
ref={(e) => {
form.register("generalPrompt").ref(e);
generalPromptRef.current = e;
}}
placeholder={t("enter_the_general_prompt_for_the_agent")}
className="min-h-[500px] rounded-t-none"
disabled={readOnly}
/>
</div>
{/* Commented code for future tools implementation */}
{/* <div className="p-4 rounded-lg border border-subtle bg-default">
<div className="flex justify-between items-center mb-4">
<div>
<h4 className="text-sm font-medium text-emphasis">{t("Functions")}</h4>
<p className="text-xs text-subtle">
{t(
"Enable your agent with capabilities such as calendar bookings, call termination, etc."
)}
</p>
</div>
<Button
type="button"
onClick={openAddToolDialog}
color="secondary"
size="sm"
disabled={readOnly}>
<Icon name="plus" className="mr-2 w-4 h-4" />
{t("Add Function")}
</Button>
</div>
<div className="space-y-3">
{toolFields.map((tool, idx) => (
<div
key={tool.id}
className="flex justify-between items-center p-4 rounded-lg border transition-colors border-subtle bg-muted hover:bg-default">
<div className="flex gap-3">
<div className="flex justify-center items-center w-8 h-8 rounded-md border bg-default border-subtle">
<Icon name="zap" className="w-4 h-4 text-emphasis" />
</div>
<div>
<p className="font-medium text-emphasis">{tool.name}</p>
<p className="text-sm text-subtle">
{tool.type === "check_availability_cal" && t("Check Availability")}
{tool.type === "book_appointment_cal" && t("Book Appointment")}
{tool.type === "end_call" && t("End Call")}
</p>
</div>
</div>
<div className="flex gap-2 items-center">
<Button
type="button"
size="sm"
color="secondary"
variant="icon"
onClick={() => openEditToolDialog(idx)}
disabled={readOnly}>
<Icon name="pencil" className="w-4 h-4" />
</Button>
{tool.name !== "end_call" && (
<Button
type="button"
color="destructive"
variant="icon"
size="sm"
onClick={() => handleToolDelete(idx)}
disabled={readOnly}>
<Icon name="trash" className="w-4 h-4" />
</Button>
)}
</div>
</div>
))}
{toolFields.length === 0 && (
<div className="flex flex-col justify-center items-center p-6 text-center rounded-lg border border-subtle bg-muted">
<Icon name="zap" className="w-6 h-6 text-subtle" />
<p className="mt-2 text-sm text-subtle">{t("No functions configured yet")}</p>
<p className="text-xs text-subtle">
{t("Add functions to enable advanced capabilities")}
</p>
</div>
)}
</div>
</div> */}
</div>
);
}
@@ -0,0 +1,37 @@
import { Controller } from "react-hook-form";
import type { Control } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Label, Select } from "@calcom/ui/components/form";
import type { AgentFormValues } from "../../types/schemas";
import { LANGUAGE_OPTIONS } from "../../utils/constants";
interface LanguageSelectorProps {
control: Control<AgentFormValues>;
name: keyof AgentFormValues;
disabled?: boolean;
}
export function LanguageSelector({ control, name, disabled = false }: LanguageSelectorProps) {
const { t } = useLocale();
return (
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("language")}</Label>
<Controller
name={name}
control={control}
render={({ field }) => (
<Select
value={LANGUAGE_OPTIONS.find((option) => option.value === field.value)}
onChange={(option) => field.onChange(option?.value)}
options={LANGUAGE_OPTIONS}
isDisabled={disabled}
className="mb-4"
/>
)}
/>
</div>
);
}
@@ -0,0 +1,30 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Label } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
interface VoiceSelectorProps {
selectedVoiceId?: string;
onVoiceDialogOpen: () => void;
disabled?: boolean;
}
export function VoiceSelector({ selectedVoiceId, onVoiceDialogOpen, disabled = false }: VoiceSelectorProps) {
const { t } = useLocale();
return (
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("voice")}</Label>
<p className="text-subtle mb-1.5 text-xs">{t("select_voice_for_agent")}</p>
<Button
type="button"
color="secondary"
onClick={onVoiceDialogOpen}
disabled={disabled}
className="w-full justify-start">
<Icon name="user" className="mr-2 h-4 w-4" />
{selectedVoiceId ? <span className="text-sm">{selectedVoiceId}</span> : t("select_voice")}
</Button>
</div>
);
}
@@ -0,0 +1,190 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Label, Select } from "@calcom/ui/components/form";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import type { FormValues } from "../../../../pages/workflow";
import { VoiceSelectionDialog } from "../../../VoiceSelectionDialog";
import type { AgentFormValues } from "../../types/schemas";
import { AgentConfigForm } from "../forms/AgentConfigForm";
interface IncomingCallsTabProps {
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentId?: string | null;
inboundAgentForm: UseFormReturn<AgentFormValues>;
form: UseFormReturn<FormValues>;
eventTypeOptions: Option[];
readOnly?: boolean;
teamId?: number;
workflowStepId?: number;
}
export function IncomingCallsTab({
agentData,
inboundAgentData,
inboundAgentId,
inboundAgentForm,
form,
eventTypeOptions,
readOnly = false,
teamId,
workflowStepId,
}: IncomingCallsTabProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const [isVoiceDialogOpen, setIsVoiceDialogOpen] = useState(false);
const setupInboundAgentMutation = trpc.viewer.aiVoiceAgent.setupInboundAgent.useMutation({
onSuccess: async (data) => {
showToast(t("inbound_agent_setup_success"), "success");
// Update the form with the new inbound agent ID
if (data.agentId && form && workflowStepId) {
const stepIndex = form.getValues("steps")?.findIndex((s) => s.id === workflowStepId);
if (stepIndex !== undefined && stepIndex !== -1) {
form.setValue(`steps.${stepIndex}.inboundAgentId`, data.agentId, { shouldDirty: true });
}
}
// Invalidate and refetch the agent data
if (data.agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: data.agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const updateInboundAgentEventTypeMutation =
trpc.viewer.aiVoiceAgent.updateInboundAgentEventType.useMutation({
onSuccess: async () => {
showToast(t("agent_event_type_updated_successfully"), "success");
if (inboundAgentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: inboundAgentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const hasActivePhoneNumbers =
agentData?.outboundPhoneNumbers &&
agentData.outboundPhoneNumbers.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE || !phone.subscriptionStatus
).length > 0;
if (!hasActivePhoneNumbers) {
return (
<div className="border-subtle rounded-xl border p-8">
<div className="flex flex-col items-center space-y-6 text-center">
<div className="bg-muted flex h-16 w-16 items-center justify-center rounded-lg">
<Icon name="info" className="text-subtle h-8 w-8" />
</div>
<div className="space-y-2">
<h3 className="text-emphasis text-lg font-semibold">{t("setup_incoming_agent")}</h3>
<p className="text-subtle text-sm">{t("connect_a_phone_number_first")}</p>
</div>
</div>
</div>
);
}
if (!inboundAgentId) {
return (
<div className="border-subtle rounded-xl border p-8">
<div className="flex flex-col items-center space-y-6 text-center">
<div className="bg-muted flex h-16 w-16 items-center justify-center rounded-lg">
<Icon name="phone-incoming" className="text-subtle h-8 w-8" />
</div>
<div className="space-y-2">
<h3 className="text-emphasis text-lg font-semibold">{t("setup_inbound_agent")}</h3>
<p className="text-subtle text-sm">{t("setup_inbound_agent_for_incoming_calls")}</p>
</div>
<Button
onClick={() => {
const phoneNumber = agentData?.outboundPhoneNumbers?.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE ||
!phone.subscriptionStatus
)[0]?.phoneNumber;
if (!phoneNumber) {
showToast(t("no_active_phone_number_available"), "error");
return;
}
if (!workflowStepId) {
showToast(t("workflow_step_not_configured"), "error");
return;
}
setupInboundAgentMutation.mutate({
phoneNumber,
teamId,
workflowStepId: workflowStepId,
});
}}
className="px-6"
loading={setupInboundAgentMutation.isPending}
disabled={setupInboundAgentMutation.isPending || !workflowStepId}>
{t("setup_inbound_agent")}
</Button>
</div>
</div>
);
}
return (
<div className="space-y-4">
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("event_type")}</Label>
<p className="text-subtle mb-1.5 text-xs">{t("select_event_type_for_inbound_calls")}</p>
<Select
isSearchable={false}
innerClassNames={{ valueContainer: "font-medium" }}
className="text-sm font-medium"
isDisabled={readOnly || updateInboundAgentEventTypeMutation.isPending}
isLoading={updateInboundAgentEventTypeMutation.isPending}
onChange={(val) => {
if (val && inboundAgentId) {
updateInboundAgentEventTypeMutation.mutate({
agentId: inboundAgentId,
eventTypeId: parseInt(val.value),
teamId,
});
}
}}
value={eventTypeOptions.find((opt) => opt.value === inboundAgentData?.inboundEventTypeId?.toString())}
options={eventTypeOptions}
placeholder={t("select_event_type")}
/>
</div>
<AgentConfigForm
form={inboundAgentForm}
readOnly={readOnly}
selectedVoiceId={inboundAgentForm.watch("voiceId")}
onVoiceDialogOpen={() => setIsVoiceDialogOpen(true)}
/>
<VoiceSelectionDialog
open={isVoiceDialogOpen}
onOpenChange={setIsVoiceDialogOpen}
selectedVoiceId={inboundAgentForm.watch("voiceId")}
onVoiceSelect={(voiceId: string) => {
inboundAgentForm.setValue("voiceId", voiceId, { shouldDirty: true });
}}
/>
</div>
);
}
@@ -0,0 +1,35 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import { VoiceSelectionDialog } from "../../../VoiceSelectionDialog";
import type { AgentFormValues } from "../../types/schemas";
import { AgentConfigForm } from "../forms/AgentConfigForm";
interface OutgoingCallsTabProps {
outboundAgentForm: UseFormReturn<AgentFormValues>;
readOnly?: boolean;
}
export function OutgoingCallsTab({ outboundAgentForm, readOnly = false }: OutgoingCallsTabProps) {
const [isVoiceDialogOpen, setIsVoiceDialogOpen] = useState(false);
return (
<>
<AgentConfigForm
form={outboundAgentForm}
readOnly={readOnly}
selectedVoiceId={outboundAgentForm.watch("voiceId")}
onVoiceDialogOpen={() => setIsVoiceDialogOpen(true)}
/>
<VoiceSelectionDialog
open={isVoiceDialogOpen}
onOpenChange={setIsVoiceDialogOpen}
selectedVoiceId={outboundAgentForm.watch("voiceId")}
onVoiceSelect={(voiceId: string) => {
outboundAgentForm.setValue("voiceId", voiceId, { shouldDirty: true });
}}
/>
</>
);
}
@@ -0,0 +1,350 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import { CAL_AI_PHONE_NUMBER_MONTHLY_PRICE } from "@calcom/lib/constants";
import { formatPhoneNumber } from "@calcom/lib/formatPhoneNumber";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import type { FormValues } from "../../../../pages/workflow";
import { TestPhoneCallDialog } from "../../../TestPhoneCallDialog";
import { WebCallDialog } from "../../../WebCallDialog";
import { usePhoneNumberActions } from "../../hooks/usePhoneNumberActions";
import { BuyNumberDialog } from "../dialogs/BuyNumberDialog";
import { ConfirmationDialogs } from "../dialogs/ConfirmationDialogs";
import { ImportNumberDialog } from "../dialogs/ImportNumberDialog";
interface PhoneNumberTabProps {
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
readOnly?: boolean;
agentId?: string | null;
teamId?: number;
workflowId?: string;
isOrganization?: boolean;
form?: UseFormReturn<FormValues>;
}
export function PhoneNumberTab({
agentData,
readOnly = false,
agentId,
teamId,
workflowId,
isOrganization = false,
form,
}: PhoneNumberTabProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const [isBuyDialogOpen, setIsBuyDialogOpen] = useState(false);
const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
const [showAdvancedFields, setShowAdvancedFields] = useState(false);
const [isTestAgentDialogOpen, setIsTestAgentDialogOpen] = useState(false);
const [isWebCallDialogOpen, setIsWebCallDialogOpen] = useState(false);
const phoneNumberActions = usePhoneNumberActions();
const buyNumberMutation = trpc.viewer.phoneNumber.buy.useMutation({
onSuccess: async (data: { checkoutUrl?: string; message?: string; phoneNumber?: unknown }) => {
if (data.checkoutUrl) {
window.location.href = data.checkoutUrl;
} else if (data.phoneNumber) {
showToast(t("phone_number_purchased_successfully"), "success");
await utils.viewer.me.get.invalidate();
setIsBuyDialogOpen(false);
if (agentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
} else {
showToast(data.message || t("something_went_wrong"), "error");
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const importNumberMutation = trpc.viewer.phoneNumber.import.useMutation({
onSuccess: async () => {
showToast(t("phone_number_imported_successfully"), "success");
setIsImportDialogOpen(false);
await utils.viewer.me.get.invalidate();
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const updateAgentMutation = trpc.viewer.aiVoiceAgent.update.useMutation({
onSuccess: async () => {
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const hasActivePhoneNumbers =
agentData?.outboundPhoneNumbers &&
agentData.outboundPhoneNumbers.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE || !phone.subscriptionStatus
).length > 0;
if (hasActivePhoneNumbers) {
const activePhoneNumbers = agentData.outboundPhoneNumbers.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE || !phone.subscriptionStatus
);
const phoneNumber = activePhoneNumbers[0];
return (
<>
<div className="relative space-y-2">
{updateAgentMutation.isPending && (
<div className="absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-white/50">
<div className="flex items-center gap-2 text-sm text-gray-600">
<Icon name="loader" className="h-4 w-4 animate-spin" />
{t("updating")}...
</div>
</div>
)}
<div className="border-subtle rounded-lg border p-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<span className="text-emphasis text-sm">{formatPhoneNumber(phoneNumber.phoneNumber)}</span>
<Badge variant="green" size="md" withDot>
{t("active")}
</Badge>
{phoneNumber.subscriptionStatus && (
<span className="text-muted text-xs">
{t("phone_number_cost", {
price: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE,
})}
</span>
)}
</div>
</div>
<div className="flex items-center gap-1">
<Dropdown>
<DropdownMenuTrigger asChild>
<Button
color="secondary"
className="rounded-[10px]"
disabled={readOnly}
EndIcon="chevron-down">
{t("test_agent")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="phone"
onClick={() => {
setIsTestAgentDialogOpen(true);
}}>
{t("phone_call")}
</DropdownItem>
</DropdownMenuItem>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="monitor"
onClick={() => {
setIsWebCallDialogOpen(true);
}}>
{t("web_call")}
</DropdownItem>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
{!readOnly && (
<Dropdown>
<DropdownMenuTrigger asChild>
<Button type="button" color="secondary" variant="icon" StartIcon="ellipsis" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="trash"
color="destructive"
onClick={() => {
if (readOnly) return;
if (phoneNumber.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE) {
phoneNumberActions.handleCancelSubscription(phoneNumber.id);
} else {
phoneNumberActions.handleDeletePhoneNumber(phoneNumber.phoneNumber);
}
}}>
{phoneNumber.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE
? t("unsubscribe")
: t("delete")}
</DropdownItem>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
)}
</div>
</div>
</div>
</div>
<BuyNumberDialog
open={isBuyDialogOpen}
onOpenChange={setIsBuyDialogOpen}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
<ImportNumberDialog
open={isImportDialogOpen}
onOpenChange={setIsImportDialogOpen}
phoneNumberForm={phoneNumberActions.phoneNumberForm}
showAdvancedFields={showAdvancedFields}
setShowAdvancedFields={setShowAdvancedFields}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
{agentId && form && (
<TestPhoneCallDialog
open={isTestAgentDialogOpen}
onOpenChange={setIsTestAgentDialogOpen}
agentId={agentId}
teamId={teamId}
form={form}
/>
)}
{agentId && form && (
<WebCallDialog
open={isWebCallDialogOpen}
onOpenChange={setIsWebCallDialogOpen}
agentId={agentId}
teamId={teamId}
isOrganization={isOrganization}
form={form}
/>
)}
<ConfirmationDialogs
cancellingNumberId={phoneNumberActions.cancellingNumberId}
setCancellingNumberId={phoneNumberActions.setCancellingNumberId}
numberToDelete={phoneNumberActions.numberToDelete}
setNumberToDelete={phoneNumberActions.setNumberToDelete}
agentId={agentId}
/>
</>
);
}
return (
<>
<div className="border-subtle rounded-xl border p-8">
<div className="flex flex-col items-center space-y-6 text-center">
<div className="bg-muted flex h-16 w-16 items-center justify-center rounded-lg">
<Icon name="phone" className="text-subtle h-8 w-8" />
</div>
<div className="space-y-2">
<h3 className="text-emphasis text-lg font-semibold">{t("no_phone_numbers")}</h3>
<p className="text-subtle text-sm">{t("buy_a_phone_number_or_import_one_you_already_have")}</p>
</div>
<div className="flex gap-3">
<Button
onClick={() => {
if (readOnly) return;
setIsBuyDialogOpen(true);
}}
StartIcon="external-link"
className="px-6"
disabled={readOnly || buyNumberMutation.isPending}>
{t("buy")}
</Button>
<Button
onClick={() => {
if (readOnly) return;
setIsImportDialogOpen(true);
}}
color="secondary"
className="px-6"
disabled={readOnly || importNumberMutation.isPending}>
{t("import")}
</Button>
</div>
</div>
</div>
<BuyNumberDialog
open={isBuyDialogOpen}
onOpenChange={setIsBuyDialogOpen}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
<ImportNumberDialog
open={isImportDialogOpen}
onOpenChange={setIsImportDialogOpen}
phoneNumberForm={phoneNumberActions.phoneNumberForm}
showAdvancedFields={showAdvancedFields}
setShowAdvancedFields={setShowAdvancedFields}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
{agentId && form && (
<TestPhoneCallDialog
open={isTestAgentDialogOpen}
onOpenChange={setIsTestAgentDialogOpen}
agentId={agentId}
teamId={teamId}
form={form}
/>
)}
{agentId && form && (
<WebCallDialog
open={isWebCallDialogOpen}
onOpenChange={setIsWebCallDialogOpen}
agentId={agentId}
teamId={teamId}
isOrganization={isOrganization}
form={form}
/>
)}
<ConfirmationDialogs
cancellingNumberId={phoneNumberActions.cancellingNumberId}
setCancellingNumberId={phoneNumberActions.setCancellingNumberId}
numberToDelete={phoneNumberActions.numberToDelete}
setNumberToDelete={phoneNumberActions.setNumberToDelete}
agentId={agentId}
/>
</>
);
}
@@ -0,0 +1,74 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { AgentFormValues } from "../types/schemas";
import { agentSchema } from "../types/schemas";
import { cleanPromptForDisplay } from "../utils/promptUtils";
interface UseAgentFormsProps {
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
}
export function useAgentForms({ agentData, inboundAgentData }: UseAgentFormsProps) {
const outboundAgentForm = useForm<AgentFormValues>({
resolver: zodResolver(agentSchema),
defaultValues: {
generalPrompt: "",
beginMessage: "",
numberToCall: "",
language: "en-US",
voiceId: "",
generalTools: [],
},
});
const inboundAgentForm = useForm<AgentFormValues>({
resolver: zodResolver(agentSchema),
defaultValues: {
generalPrompt: "",
beginMessage: "",
numberToCall: "",
language: "en-US",
voiceId: "",
generalTools: [],
},
});
useEffect(() => {
if (agentData?.retellData) {
const retellData = agentData.retellData;
outboundAgentForm.reset({
generalPrompt: cleanPromptForDisplay(retellData.generalPrompt || ""),
beginMessage: retellData.beginMessage || "",
numberToCall: "",
language: retellData.language || "en-US",
voiceId: retellData.voiceId || "",
generalTools: retellData.generalTools || [],
});
}
}, [agentData, outboundAgentForm]);
useEffect(() => {
if (inboundAgentData?.retellData) {
const retellData = inboundAgentData.retellData;
inboundAgentForm.reset({
generalPrompt: cleanPromptForDisplay(retellData.generalPrompt || ""),
beginMessage: retellData.beginMessage || "",
numberToCall: "",
language: retellData.language || "en-US",
voiceId: retellData.voiceId || "",
generalTools: retellData.generalTools || [],
});
}
}, [inboundAgentData, inboundAgentForm]);
return {
outboundAgentForm,
inboundAgentForm,
};
}
@@ -0,0 +1,40 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useState } from "react";
import { useForm } from "react-hook-form";
import type { PhoneNumberFormValues } from "../types/schemas";
import { phoneNumberFormSchema } from "../types/schemas";
export function usePhoneNumberActions() {
const [cancellingNumberId, setCancellingNumberId] = useState<number | null>(null);
const [numberToDelete, setNumberToDelete] = useState<string | null>(null);
const phoneNumberForm = useForm<PhoneNumberFormValues>({
resolver: zodResolver(phoneNumberFormSchema),
defaultValues: {
phoneNumber: "",
terminationUri: "",
sipTrunkAuthUsername: "",
sipTrunkAuthPassword: "",
nickname: "",
},
});
const handleCancelSubscription = (phoneNumberId: number) => {
setCancellingNumberId(phoneNumberId);
};
const handleDeletePhoneNumber = (phoneNumber: string) => {
setNumberToDelete(phoneNumber);
};
return {
phoneNumberForm,
cancellingNumberId,
setCancellingNumberId,
numberToDelete,
setNumberToDelete,
handleCancelSubscription,
handleDeletePhoneNumber,
};
}
@@ -0,0 +1,45 @@
import { isValidPhoneNumber } from "libphonenumber-js";
import { z } from "zod";
export const agentSchema = z.object({
generalPrompt: z.string().min(1, "General prompt is required"),
beginMessage: z.string().min(1, "Begin message is required"),
numberToCall: z.string().optional(),
language: z.string().optional(),
voiceId: z.string().optional(),
generalTools: z
.array(
z.object({
type: z.string(),
name: z.string(),
description: z.string().nullish().default(null),
cal_api_key: z.string().nullish().default(null),
event_type_id: z.number().nullish().default(null),
timezone: z.string().nullish().default(null),
})
)
.optional(),
});
export const phoneNumberFormSchema = z.object({
phoneNumber: z.string().refine((val) => isValidPhoneNumber(val)),
terminationUri: z.string().min(1, "Termination URI is required"),
sipTrunkAuthUsername: z.string().optional(),
sipTrunkAuthPassword: z.string().optional(),
nickname: z.string().optional(),
});
export type AgentFormValues = z.infer<typeof agentSchema>;
export type PhoneNumberFormValues = z.infer<typeof phoneNumberFormSchema>;
// Commented types for future implementation
// type RetellData = RouterOutputs["viewer"]["ai"]["get"]["retellData"];
// type ToolDraft = {
// type: string;
// name: string;
// description: string | null;
// cal_api_key: string | null;
// event_type_id: number | null;
// timezone: string;
// };
@@ -0,0 +1,38 @@
export const LANGUAGE_OPTIONS = [
{ value: "en-US", label: "English (US)" },
{ value: "en-IN", label: "English (India)" },
{ value: "en-GB", label: "English (UK)" },
{ value: "en-AU", label: "English (Australia)" },
{ value: "en-NZ", label: "English (New Zealand)" },
{ value: "de-DE", label: "German" },
{ value: "es-ES", label: "Spanish (Spain)" },
{ value: "es-419", label: "Spanish (Latin America)" },
{ value: "hi-IN", label: "Hindi" },
{ value: "fr-FR", label: "French (France)" },
{ value: "fr-CA", label: "French (Canada)" },
{ value: "ja-JP", label: "Japanese" },
{ value: "pt-PT", label: "Portuguese (Portugal)" },
{ value: "pt-BR", label: "Portuguese (Brazil)" },
{ value: "zh-CN", label: "Chinese (Simplified)" },
{ value: "ru-RU", label: "Russian" },
{ value: "it-IT", label: "Italian" },
{ value: "ko-KR", label: "Korean" },
{ value: "nl-NL", label: "Dutch (Netherlands)" },
{ value: "nl-BE", label: "Dutch (Belgium)" },
{ value: "pl-PL", label: "Polish" },
{ value: "tr-TR", label: "Turkish" },
{ value: "th-TH", label: "Thai" },
{ value: "vi-VN", label: "Vietnamese" },
{ value: "ro-RO", label: "Romanian" },
{ value: "bg-BG", label: "Bulgarian" },
{ value: "ca-ES", label: "Catalan" },
{ value: "da-DK", label: "Danish" },
{ value: "fi-FI", label: "Finnish" },
{ value: "el-GR", label: "Greek" },
{ value: "hu-HU", label: "Hungarian" },
{ value: "id-ID", label: "Indonesian" },
{ value: "no-NO", label: "Norwegian" },
{ value: "sk-SK", label: "Slovak" },
{ value: "sv-SE", label: "Swedish" },
{ value: "multi", label: "Multilingual" },
];
@@ -0,0 +1,40 @@
// Utility functions for prompt display and restoration
import { RETELL_AI_TEST_MODE, RETELL_AI_TEST_EVENT_TYPE_MAP } from "@calcom/lib/constants";
export const cleanPromptForDisplay = (prompt: string): string => {
if (!prompt) return prompt;
const cleanedPrompt = prompt
.replace(/check_availability_\{\{eventTypeId\}\}/g, "check_availability")
.replace(/book_appointment_\{\{eventTypeId\}\}/g, "book_appointment")
.replace(/check_availability_\d+/g, "check_availability")
.replace(/book_appointment_\d+/g, "book_appointment");
return cleanedPrompt;
};
export const restorePromptComplexity = (prompt: string): string => {
if (!prompt) return prompt;
return prompt
.replace(/\bcheck_availability\b/g, "check_availability_{{eventTypeId}}")
.replace(/\bbook_appointment\b/g, "book_appointment_{{eventTypeId}}");
};
/**
* Replaces event type placeholders in a prompt with the actual event type ID
* Handles both numeric placeholders (check_availability_123) and template placeholders (check_availability_{{eventTypeId}})
*/
export const replaceEventTypePlaceholders = (prompt: string, eventTypeId: number): string => {
let eventTypeIdToUse = eventTypeId;
if (RETELL_AI_TEST_MODE && RETELL_AI_TEST_EVENT_TYPE_MAP) {
const mappedId = RETELL_AI_TEST_EVENT_TYPE_MAP[String(eventTypeId)];
eventTypeIdToUse = mappedId ? Number(mappedId) : eventTypeId;
}
return prompt
.replace(/check_availability_\d+/g, `check_availability_${eventTypeIdToUse}`)
.replace(/book_appointment_\d+/g, `book_appointment_${eventTypeIdToUse}`)
.replace(/check_availability_\{\{eventTypeId\}\}/g, `check_availability_${eventTypeIdToUse}`)
.replace(/book_appointment_\{\{eventTypeId\}\}/g, `book_appointment_${eventTypeIdToUse}`);
};
@@ -0,0 +1,107 @@
import { useMemo } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useWatch } from "react-hook-form";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import type { FormValues } from "../pages/workflow";
type AgentData = RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
interface AgentQuery {
data: AgentData | undefined;
isPending: boolean;
isLoading: boolean;
error: Error | null;
}
interface UseAgentsDataReturn {
outboundAgentQueries: AgentQuery[];
inboundAgentQueries: AgentQuery[];
}
const emptyQuery: AgentQuery = { data: undefined, isPending: false, isLoading: false, error: null };
/**
* Custom hook to fetch and manage agent data for workflow steps.
*
* @param form - React Hook Form instance for workflow form values
* @returns Object containing outbound and inbound agent queries with proper typing
*/
export function useAgentsData(form: UseFormReturn<FormValues>): UseAgentsDataReturn {
const watchedSteps = useWatch({
control: form.control,
name: "steps",
});
const allAgentIds = useMemo(() => {
const outboundAgentIds = (watchedSteps || []).map((step) => step?.agentId || null);
const inboundAgentIds = (watchedSteps || []).map((step) => step?.inboundAgentId || null);
return { outboundAgentIds, inboundAgentIds };
}, [watchedSteps]);
const uniqueAgentIds = useMemo((): string[] => {
const allIds = [...allAgentIds.outboundAgentIds, ...allAgentIds.inboundAgentIds];
const validIds: string[] = [];
for (const id of allIds) {
if (id && typeof id === "string") {
validIds.push(id);
}
}
return Array.from(new Set(validIds));
}, [allAgentIds]);
const uniqueAgentQueries = trpc.useQueries((t) =>
uniqueAgentIds.map((agentId) => {
return t.viewer.aiVoiceAgent.get(
{ id: agentId },
{
enabled: true,
staleTime: 5 * 60 * 1000,
}
);
})
);
const agentDataMap = useMemo(() => {
const map = new Map<string, AgentQuery>();
uniqueAgentIds.forEach((agentId, index) => {
const query = uniqueAgentQueries[index];
if (query) {
map.set(agentId, {
data: query.data,
isPending: query.isPending,
isLoading: query.isLoading,
error: query.error,
});
}
});
return map;
}, [uniqueAgentIds, uniqueAgentQueries]);
const outboundAgentQueries = useMemo((): AgentQuery[] => {
return allAgentIds.outboundAgentIds.map((agentId) => {
if (!agentId) {
return emptyQuery;
}
return agentDataMap.get(agentId) || emptyQuery;
});
}, [allAgentIds.outboundAgentIds, agentDataMap]);
const inboundAgentQueries = useMemo((): AgentQuery[] => {
return allAgentIds.inboundAgentIds.map((agentId) => {
if (!agentId) {
return emptyQuery;
}
return agentDataMap.get(agentId) || emptyQuery;
});
}, [allAgentIds.inboundAgentIds, agentDataMap]);
return {
outboundAgentQueries,
inboundAgentQueries,
};
}
@@ -38,7 +38,11 @@ import { getTranslatedText, translateVariablesToEnglish } from "../lib/variableT
export type FormValues = {
name: string;
activeOn: Option[];
steps: (WorkflowStep & { senderName: string | null; agentId?: string | null })[];
steps: (WorkflowStep & {
senderName: string | null;
agentId?: string | null;
inboundAgentId?: string | null;
})[];
trigger: WorkflowTriggerEvents;
time?: number;
timeUnit?: TimeUnit;