MessageInput.svelte 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { v4 as uuidv4 } from 'uuid';
  4. import { createPicker, getAuthToken } from '$lib/utils/google-drive-picker';
  5. import { pickAndDownloadFile } from '$lib/utils/onedrive-file-picker';
  6. import { onMount, tick, getContext, createEventDispatcher, onDestroy } from 'svelte';
  7. const dispatch = createEventDispatcher();
  8. import {
  9. type Model,
  10. mobile,
  11. settings,
  12. showSidebar,
  13. models,
  14. config,
  15. showCallOverlay,
  16. tools,
  17. user as _user,
  18. showControls,
  19. TTSWorker
  20. } from '$lib/stores';
  21. import {
  22. blobToFile,
  23. compressImage,
  24. createMessagesList,
  25. extractCurlyBraceWords
  26. } from '$lib/utils';
  27. import { transcribeAudio } from '$lib/apis/audio';
  28. import { uploadFile } from '$lib/apis/files';
  29. import { generateAutoCompletion } from '$lib/apis';
  30. import { deleteFileById } from '$lib/apis/files';
  31. import { WEBUI_BASE_URL, WEBUI_API_BASE_URL, PASTED_TEXT_CHARACTER_LIMIT } from '$lib/constants';
  32. import InputMenu from './MessageInput/InputMenu.svelte';
  33. import VoiceRecording from './MessageInput/VoiceRecording.svelte';
  34. import FilesOverlay from './MessageInput/FilesOverlay.svelte';
  35. import Commands from './MessageInput/Commands.svelte';
  36. import RichTextInput from '../common/RichTextInput.svelte';
  37. import Tooltip from '../common/Tooltip.svelte';
  38. import FileItem from '../common/FileItem.svelte';
  39. import Image from '../common/Image.svelte';
  40. import XMark from '../icons/XMark.svelte';
  41. import Headphone from '../icons/Headphone.svelte';
  42. import GlobeAlt from '../icons/GlobeAlt.svelte';
  43. import PhotoSolid from '../icons/PhotoSolid.svelte';
  44. import Photo from '../icons/Photo.svelte';
  45. import CommandLine from '../icons/CommandLine.svelte';
  46. import { KokoroWorker } from '$lib/workers/KokoroWorker';
  47. import ToolServersModal from './ToolServersModal.svelte';
  48. import Wrench from '../icons/Wrench.svelte';
  49. const i18n = getContext('i18n');
  50. export let transparentBackground = false;
  51. export let onChange: Function = () => {};
  52. export let createMessagePair: Function;
  53. export let stopResponse: Function;
  54. export let autoScroll = false;
  55. export let atSelectedModel: Model | undefined = undefined;
  56. export let selectedModels: [''];
  57. let selectedModelIds = [];
  58. $: selectedModelIds = atSelectedModel !== undefined ? [atSelectedModel.id] : selectedModels;
  59. export let history;
  60. export let taskIds = null;
  61. export let prompt = '';
  62. export let files = [];
  63. export let toolServers = [];
  64. export let selectedToolIds = [];
  65. export let imageGenerationEnabled = false;
  66. export let webSearchEnabled = false;
  67. export let codeInterpreterEnabled = false;
  68. $: onChange({
  69. prompt,
  70. files,
  71. selectedToolIds,
  72. imageGenerationEnabled,
  73. webSearchEnabled
  74. });
  75. let showTools = false;
  76. let loaded = false;
  77. let recording = false;
  78. let isComposing = false;
  79. let chatInputContainerElement;
  80. let chatInputElement;
  81. let filesInputElement;
  82. let commandsElement;
  83. let inputFiles;
  84. let dragged = false;
  85. let user = null;
  86. export let placeholder = '';
  87. let visionCapableModels = [];
  88. $: visionCapableModels = [...(atSelectedModel ? [atSelectedModel] : selectedModels)].filter(
  89. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.vision ?? true
  90. );
  91. const scrollToBottom = () => {
  92. const element = document.getElementById('messages-container');
  93. element.scrollTo({
  94. top: element.scrollHeight,
  95. behavior: 'smooth'
  96. });
  97. };
  98. const screenCaptureHandler = async () => {
  99. try {
  100. // Request screen media
  101. const mediaStream = await navigator.mediaDevices.getDisplayMedia({
  102. video: { cursor: 'never' },
  103. audio: false
  104. });
  105. // Once the user selects a screen, temporarily create a video element
  106. const video = document.createElement('video');
  107. video.srcObject = mediaStream;
  108. // Ensure the video loads without affecting user experience or tab switching
  109. await video.play();
  110. // Set up the canvas to match the video dimensions
  111. const canvas = document.createElement('canvas');
  112. canvas.width = video.videoWidth;
  113. canvas.height = video.videoHeight;
  114. // Grab a single frame from the video stream using the canvas
  115. const context = canvas.getContext('2d');
  116. context.drawImage(video, 0, 0, canvas.width, canvas.height);
  117. // Stop all video tracks (stop screen sharing) after capturing the image
  118. mediaStream.getTracks().forEach((track) => track.stop());
  119. // bring back focus to this current tab, so that the user can see the screen capture
  120. window.focus();
  121. // Convert the canvas to a Base64 image URL
  122. const imageUrl = canvas.toDataURL('image/png');
  123. // Add the captured image to the files array to render it
  124. files = [...files, { type: 'image', url: imageUrl }];
  125. // Clean memory: Clear video srcObject
  126. video.srcObject = null;
  127. } catch (error) {
  128. // Handle any errors (e.g., user cancels screen sharing)
  129. console.error('Error capturing screen:', error);
  130. }
  131. };
  132. const uploadFileHandler = async (file, fullContext: boolean = false) => {
  133. if ($_user?.role !== 'admin' && !($_user?.permissions?.chat?.file_upload ?? true)) {
  134. toast.error($i18n.t('You do not have permission to upload files.'));
  135. return null;
  136. }
  137. const tempItemId = uuidv4();
  138. const fileItem = {
  139. type: 'file',
  140. file: '',
  141. id: null,
  142. url: '',
  143. name: file.name,
  144. collection_name: '',
  145. status: 'uploading',
  146. size: file.size,
  147. error: '',
  148. itemId: tempItemId,
  149. ...(fullContext ? { context: 'full' } : {})
  150. };
  151. if (fileItem.size == 0) {
  152. toast.error($i18n.t('You cannot upload an empty file.'));
  153. return null;
  154. }
  155. files = [...files, fileItem];
  156. try {
  157. // During the file upload, file content is automatically extracted.
  158. const uploadedFile = await uploadFile(localStorage.token, file);
  159. if (uploadedFile) {
  160. console.log('File upload completed:', {
  161. id: uploadedFile.id,
  162. name: fileItem.name,
  163. collection: uploadedFile?.meta?.collection_name
  164. });
  165. if (uploadedFile.error) {
  166. console.warn('File upload warning:', uploadedFile.error);
  167. toast.warning(uploadedFile.error);
  168. }
  169. fileItem.status = 'uploaded';
  170. fileItem.file = uploadedFile;
  171. fileItem.id = uploadedFile.id;
  172. fileItem.collection_name =
  173. uploadedFile?.meta?.collection_name || uploadedFile?.collection_name;
  174. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  175. files = files;
  176. } else {
  177. files = files.filter((item) => item?.itemId !== tempItemId);
  178. }
  179. } catch (e) {
  180. toast.error(`${e}`);
  181. files = files.filter((item) => item?.itemId !== tempItemId);
  182. }
  183. };
  184. const inputFilesHandler = async (inputFiles) => {
  185. console.log('Input files handler called with:', inputFiles);
  186. inputFiles.forEach((file) => {
  187. console.log('Processing file:', {
  188. name: file.name,
  189. type: file.type,
  190. size: file.size,
  191. extension: file.name.split('.').at(-1)
  192. });
  193. if (
  194. ($config?.file?.max_size ?? null) !== null &&
  195. file.size > ($config?.file?.max_size ?? 0) * 1024 * 1024
  196. ) {
  197. console.log('File exceeds max size limit:', {
  198. fileSize: file.size,
  199. maxSize: ($config?.file?.max_size ?? 0) * 1024 * 1024
  200. });
  201. toast.error(
  202. $i18n.t(`File size should not exceed {{maxSize}} MB.`, {
  203. maxSize: $config?.file?.max_size
  204. })
  205. );
  206. return;
  207. }
  208. if (
  209. ['image/gif', 'image/webp', 'image/jpeg', 'image/png', 'image/avif'].includes(file['type'])
  210. ) {
  211. if (visionCapableModels.length === 0) {
  212. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  213. return;
  214. }
  215. let reader = new FileReader();
  216. reader.onload = async (event) => {
  217. let imageUrl = event.target.result;
  218. if ($settings?.imageCompression ?? false) {
  219. const width = $settings?.imageCompressionSize?.width ?? null;
  220. const height = $settings?.imageCompressionSize?.height ?? null;
  221. if (width || height) {
  222. imageUrl = await compressImage(imageUrl, width, height);
  223. }
  224. }
  225. files = [
  226. ...files,
  227. {
  228. type: 'image',
  229. url: `${imageUrl}`
  230. }
  231. ];
  232. };
  233. reader.readAsDataURL(file);
  234. } else {
  235. uploadFileHandler(file);
  236. }
  237. });
  238. };
  239. const handleKeyDown = (event: KeyboardEvent) => {
  240. if (event.key === 'Escape') {
  241. console.log('Escape');
  242. dragged = false;
  243. }
  244. };
  245. const onDragOver = (e) => {
  246. e.preventDefault();
  247. // Check if a file is being dragged.
  248. if (e.dataTransfer?.types?.includes('Files')) {
  249. dragged = true;
  250. } else {
  251. dragged = false;
  252. }
  253. };
  254. const onDragLeave = () => {
  255. dragged = false;
  256. };
  257. const onDrop = async (e) => {
  258. e.preventDefault();
  259. console.log(e);
  260. if (e.dataTransfer?.files) {
  261. const inputFiles = Array.from(e.dataTransfer?.files);
  262. if (inputFiles && inputFiles.length > 0) {
  263. console.log(inputFiles);
  264. inputFilesHandler(inputFiles);
  265. }
  266. }
  267. dragged = false;
  268. };
  269. onMount(async () => {
  270. loaded = true;
  271. window.setTimeout(() => {
  272. const chatInput = document.getElementById('chat-input');
  273. chatInput?.focus();
  274. }, 0);
  275. window.addEventListener('keydown', handleKeyDown);
  276. await tick();
  277. const dropzoneElement = document.getElementById('chat-container');
  278. dropzoneElement?.addEventListener('dragover', onDragOver);
  279. dropzoneElement?.addEventListener('drop', onDrop);
  280. dropzoneElement?.addEventListener('dragleave', onDragLeave);
  281. });
  282. onDestroy(() => {
  283. console.log('destroy');
  284. window.removeEventListener('keydown', handleKeyDown);
  285. const dropzoneElement = document.getElementById('chat-container');
  286. if (dropzoneElement) {
  287. dropzoneElement?.removeEventListener('dragover', onDragOver);
  288. dropzoneElement?.removeEventListener('drop', onDrop);
  289. dropzoneElement?.removeEventListener('dragleave', onDragLeave);
  290. }
  291. });
  292. </script>
  293. <FilesOverlay show={dragged} />
  294. <ToolServersModal bind:show={showTools} {selectedToolIds} />
  295. {#if loaded}
  296. <div class="w-full font-primary">
  297. <div class=" mx-auto inset-x-0 bg-transparent flex justify-center">
  298. <div
  299. class="flex flex-col px-3 {($settings?.widescreenMode ?? null)
  300. ? 'max-w-full'
  301. : 'max-w-6xl'} w-full"
  302. >
  303. <div class="relative">
  304. {#if autoScroll === false && history?.currentId}
  305. <div
  306. class=" absolute -top-12 left-0 right-0 flex justify-center z-30 pointer-events-none"
  307. >
  308. <button
  309. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full pointer-events-auto"
  310. on:click={() => {
  311. autoScroll = true;
  312. scrollToBottom();
  313. }}
  314. >
  315. <svg
  316. xmlns="http://www.w3.org/2000/svg"
  317. viewBox="0 0 20 20"
  318. fill="currentColor"
  319. class="w-5 h-5"
  320. >
  321. <path
  322. fill-rule="evenodd"
  323. d="M10 3a.75.75 0 01.75.75v10.638l3.96-4.158a.75.75 0 111.08 1.04l-5.25 5.5a.75.75 0 01-1.08 0l-5.25-5.5a.75.75 0 111.08-1.04l3.96 4.158V3.75A.75.75 0 0110 3z"
  324. clip-rule="evenodd"
  325. />
  326. </svg>
  327. </button>
  328. </div>
  329. {/if}
  330. </div>
  331. <div class="w-full relative">
  332. {#if atSelectedModel !== undefined || selectedToolIds.length > 0 || webSearchEnabled || ($settings?.webSearch ?? false) === 'always' || imageGenerationEnabled || codeInterpreterEnabled}
  333. <div
  334. class="px-3 pb-0.5 pt-1.5 text-left w-full flex flex-col absolute bottom-0 left-0 right-0 bg-linear-to-t from-white dark:from-gray-900 z-10"
  335. >
  336. {#if atSelectedModel !== undefined}
  337. <div class="flex items-center justify-between w-full">
  338. <div class="pl-[1px] flex items-center gap-2 text-sm dark:text-gray-500">
  339. <img
  340. crossorigin="anonymous"
  341. alt="model profile"
  342. class="size-3.5 max-w-[28px] object-cover rounded-full"
  343. src={$models.find((model) => model.id === atSelectedModel.id)?.info?.meta
  344. ?.profile_image_url ??
  345. ($i18n.language === 'dg-DG'
  346. ? `/doge.png`
  347. : `${WEBUI_BASE_URL}/static/favicon.png`)}
  348. />
  349. <div class="translate-y-[0.5px]">
  350. Talking to <span class=" font-medium">{atSelectedModel.name}</span>
  351. </div>
  352. </div>
  353. <div>
  354. <button
  355. class="flex items-center dark:text-gray-500"
  356. on:click={() => {
  357. atSelectedModel = undefined;
  358. }}
  359. >
  360. <XMark />
  361. </button>
  362. </div>
  363. </div>
  364. {/if}
  365. </div>
  366. {/if}
  367. <Commands
  368. bind:this={commandsElement}
  369. bind:prompt
  370. bind:files
  371. on:upload={(e) => {
  372. dispatch('upload', e.detail);
  373. }}
  374. on:select={(e) => {
  375. const data = e.detail;
  376. if (data?.type === 'model') {
  377. atSelectedModel = data.data;
  378. }
  379. const chatInputElement = document.getElementById('chat-input');
  380. chatInputElement?.focus();
  381. }}
  382. />
  383. </div>
  384. </div>
  385. </div>
  386. <div class="{transparentBackground ? 'bg-transparent' : 'bg-white dark:bg-gray-900'} ">
  387. <div
  388. class="{($settings?.widescreenMode ?? null)
  389. ? 'max-w-full'
  390. : 'max-w-6xl'} px-2.5 mx-auto inset-x-0"
  391. >
  392. <div class="">
  393. <input
  394. bind:this={filesInputElement}
  395. bind:files={inputFiles}
  396. type="file"
  397. hidden
  398. multiple
  399. on:change={async () => {
  400. if (inputFiles && inputFiles.length > 0) {
  401. const _inputFiles = Array.from(inputFiles);
  402. inputFilesHandler(_inputFiles);
  403. } else {
  404. toast.error($i18n.t(`File not found.`));
  405. }
  406. filesInputElement.value = '';
  407. }}
  408. />
  409. {#if recording}
  410. <VoiceRecording
  411. bind:recording
  412. on:cancel={async () => {
  413. recording = false;
  414. await tick();
  415. document.getElementById('chat-input')?.focus();
  416. }}
  417. on:confirm={async (e) => {
  418. const { text, filename } = e.detail;
  419. prompt = `${prompt}${text} `;
  420. recording = false;
  421. await tick();
  422. document.getElementById('chat-input')?.focus();
  423. if ($settings?.speechAutoSend ?? false) {
  424. dispatch('submit', prompt);
  425. }
  426. }}
  427. />
  428. {:else}
  429. <form
  430. class="w-full flex gap-1.5"
  431. on:submit|preventDefault={() => {
  432. // check if selectedModels support image input
  433. dispatch('submit', prompt);
  434. }}
  435. >
  436. <div
  437. class="flex-1 flex flex-col relative w-full shadow-lg rounded-3xl border border-gray-50 dark:border-gray-850 hover:border-gray-100 focus-within:border-gray-100 hover:dark:border-gray-800 focus-within:dark:border-gray-800 transition px-1 bg-white/90 dark:bg-gray-400/5 dark:text-gray-100"
  438. dir={$settings?.chatDirection ?? 'auto'}
  439. >
  440. {#if files.length > 0}
  441. <div class="mx-2 mt-2.5 -mb-1 flex items-center flex-wrap gap-2">
  442. {#each files as file, fileIdx}
  443. {#if file.type === 'image'}
  444. <div class=" relative group">
  445. <div class="relative flex items-center">
  446. <Image
  447. src={file.url}
  448. alt="input"
  449. imageClassName=" size-14 rounded-xl object-cover"
  450. />
  451. {#if atSelectedModel ? visionCapableModels.length === 0 : selectedModels.length !== visionCapableModels.length}
  452. <Tooltip
  453. className=" absolute top-1 left-1"
  454. content={$i18n.t('{{ models }}', {
  455. models: [
  456. ...(atSelectedModel ? [atSelectedModel] : selectedModels)
  457. ]
  458. .filter((id) => !visionCapableModels.includes(id))
  459. .join(', ')
  460. })}
  461. >
  462. <svg
  463. xmlns="http://www.w3.org/2000/svg"
  464. viewBox="0 0 24 24"
  465. fill="currentColor"
  466. class="size-4 fill-yellow-300"
  467. >
  468. <path
  469. fill-rule="evenodd"
  470. d="M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z"
  471. clip-rule="evenodd"
  472. />
  473. </svg>
  474. </Tooltip>
  475. {/if}
  476. </div>
  477. <div class=" absolute -top-1 -right-1">
  478. <button
  479. class=" bg-white text-black border border-white rounded-full group-hover:visible invisible transition"
  480. type="button"
  481. on:click={() => {
  482. files.splice(fileIdx, 1);
  483. files = files;
  484. }}
  485. >
  486. <svg
  487. xmlns="http://www.w3.org/2000/svg"
  488. viewBox="0 0 20 20"
  489. fill="currentColor"
  490. class="size-4"
  491. >
  492. <path
  493. d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
  494. />
  495. </svg>
  496. </button>
  497. </div>
  498. </div>
  499. {:else}
  500. <FileItem
  501. item={file}
  502. name={file.name}
  503. type={file.type}
  504. size={file?.size}
  505. loading={file.status === 'uploading'}
  506. dismissible={true}
  507. edit={true}
  508. on:dismiss={async () => {
  509. if (file.type !== 'collection' && !file?.collection) {
  510. if (file.id) {
  511. // This will handle both file deletion and Chroma cleanup
  512. await deleteFileById(localStorage.token, file.id);
  513. }
  514. }
  515. // Remove from UI state
  516. files.splice(fileIdx, 1);
  517. files = files;
  518. }}
  519. on:click={() => {
  520. console.log(file);
  521. }}
  522. />
  523. {/if}
  524. {/each}
  525. </div>
  526. {/if}
  527. <div class="px-2.5">
  528. {#if $settings?.richTextInput ?? true}
  529. <div
  530. class="scrollbar-hidden text-left bg-transparent dark:text-gray-100 outline-hidden w-full pt-3 px-1 resize-none h-fit max-h-80 overflow-auto"
  531. id="chat-input-container"
  532. >
  533. <RichTextInput
  534. bind:this={chatInputElement}
  535. bind:value={prompt}
  536. id="chat-input"
  537. messageInput={true}
  538. shiftEnter={!($settings?.ctrlEnterToSend ?? false) &&
  539. (!$mobile ||
  540. !(
  541. 'ontouchstart' in window ||
  542. navigator.maxTouchPoints > 0 ||
  543. navigator.msMaxTouchPoints > 0
  544. ))}
  545. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  546. largeTextAsFile={$settings?.largeTextAsFile ?? false}
  547. autocomplete={$config?.features?.enable_autocomplete_generation &&
  548. ($settings?.promptAutocomplete ?? false)}
  549. generateAutoCompletion={async (text) => {
  550. if (selectedModelIds.length === 0 || !selectedModelIds.at(0)) {
  551. toast.error($i18n.t('Please select a model first.'));
  552. }
  553. const res = await generateAutoCompletion(
  554. localStorage.token,
  555. selectedModelIds.at(0),
  556. text,
  557. history?.currentId
  558. ? createMessagesList(history, history.currentId)
  559. : null
  560. ).catch((error) => {
  561. console.log(error);
  562. return null;
  563. });
  564. console.log(res);
  565. return res;
  566. }}
  567. oncompositionstart={() => (isComposing = true)}
  568. oncompositionend={() => (isComposing = false)}
  569. on:keydown={async (e) => {
  570. e = e.detail.event;
  571. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  572. const commandsContainerElement =
  573. document.getElementById('commands-container');
  574. if (e.key === 'Escape') {
  575. stopResponse();
  576. }
  577. // Command/Ctrl + Shift + Enter to submit a message pair
  578. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  579. e.preventDefault();
  580. createMessagePair(prompt);
  581. }
  582. // Check if Ctrl + R is pressed
  583. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  584. e.preventDefault();
  585. console.log('regenerate');
  586. const regenerateButton = [
  587. ...document.getElementsByClassName('regenerate-response-button')
  588. ]?.at(-1);
  589. regenerateButton?.click();
  590. }
  591. if (prompt === '' && e.key == 'ArrowUp') {
  592. e.preventDefault();
  593. const userMessageElement = [
  594. ...document.getElementsByClassName('user-message')
  595. ]?.at(-1);
  596. if (userMessageElement) {
  597. userMessageElement.scrollIntoView({ block: 'center' });
  598. const editButton = [
  599. ...document.getElementsByClassName('edit-user-message-button')
  600. ]?.at(-1);
  601. editButton?.click();
  602. }
  603. }
  604. if (commandsContainerElement) {
  605. if (commandsContainerElement && e.key === 'ArrowUp') {
  606. e.preventDefault();
  607. commandsElement.selectUp();
  608. const commandOptionButton = [
  609. ...document.getElementsByClassName('selected-command-option-button')
  610. ]?.at(-1);
  611. commandOptionButton.scrollIntoView({ block: 'center' });
  612. }
  613. if (commandsContainerElement && e.key === 'ArrowDown') {
  614. e.preventDefault();
  615. commandsElement.selectDown();
  616. const commandOptionButton = [
  617. ...document.getElementsByClassName('selected-command-option-button')
  618. ]?.at(-1);
  619. commandOptionButton.scrollIntoView({ block: 'center' });
  620. }
  621. if (commandsContainerElement && e.key === 'Tab') {
  622. e.preventDefault();
  623. const commandOptionButton = [
  624. ...document.getElementsByClassName('selected-command-option-button')
  625. ]?.at(-1);
  626. commandOptionButton?.click();
  627. }
  628. if (commandsContainerElement && e.key === 'Enter') {
  629. e.preventDefault();
  630. const commandOptionButton = [
  631. ...document.getElementsByClassName('selected-command-option-button')
  632. ]?.at(-1);
  633. if (commandOptionButton) {
  634. commandOptionButton?.click();
  635. } else {
  636. document.getElementById('send-message-button')?.click();
  637. }
  638. }
  639. } else {
  640. if (
  641. !$mobile ||
  642. !(
  643. 'ontouchstart' in window ||
  644. navigator.maxTouchPoints > 0 ||
  645. navigator.msMaxTouchPoints > 0
  646. )
  647. ) {
  648. if (isComposing) {
  649. return;
  650. }
  651. // Uses keyCode '13' for Enter key for chinese/japanese keyboards.
  652. //
  653. // Depending on the user's settings, it will send the message
  654. // either when Enter is pressed or when Ctrl+Enter is pressed.
  655. const enterPressed =
  656. ($settings?.ctrlEnterToSend ?? false)
  657. ? (e.key === 'Enter' || e.keyCode === 13) && isCtrlPressed
  658. : (e.key === 'Enter' || e.keyCode === 13) && !e.shiftKey;
  659. if (enterPressed) {
  660. e.preventDefault();
  661. if (prompt !== '' || files.length > 0) {
  662. dispatch('submit', prompt);
  663. }
  664. }
  665. }
  666. }
  667. if (e.key === 'Escape') {
  668. console.log('Escape');
  669. atSelectedModel = undefined;
  670. selectedToolIds = [];
  671. webSearchEnabled = false;
  672. imageGenerationEnabled = false;
  673. }
  674. }}
  675. on:paste={async (e) => {
  676. e = e.detail.event;
  677. console.log(e);
  678. const clipboardData = e.clipboardData || window.clipboardData;
  679. if (clipboardData && clipboardData.items) {
  680. for (const item of clipboardData.items) {
  681. if (item.type.indexOf('image') !== -1) {
  682. const blob = item.getAsFile();
  683. const reader = new FileReader();
  684. reader.onload = function (e) {
  685. files = [
  686. ...files,
  687. {
  688. type: 'image',
  689. url: `${e.target.result}`
  690. }
  691. ];
  692. };
  693. reader.readAsDataURL(blob);
  694. } else if (item.type === 'text/plain') {
  695. if ($settings?.largeTextAsFile ?? false) {
  696. const text = clipboardData.getData('text/plain');
  697. if (text.length > PASTED_TEXT_CHARACTER_LIMIT) {
  698. e.preventDefault();
  699. const blob = new Blob([text], { type: 'text/plain' });
  700. const file = new File([blob], `Pasted_Text_${Date.now()}.txt`, {
  701. type: 'text/plain'
  702. });
  703. await uploadFileHandler(file, true);
  704. }
  705. }
  706. }
  707. }
  708. }
  709. }}
  710. />
  711. </div>
  712. {:else}
  713. <textarea
  714. id="chat-input"
  715. dir="auto"
  716. bind:this={chatInputElement}
  717. class="scrollbar-hidden bg-transparent dark:text-gray-100 outline-hidden w-full pt-3 px-1 resize-none"
  718. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  719. bind:value={prompt}
  720. on:compositionstart={() => (isComposing = true)}
  721. on:compositionend={() => (isComposing = false)}
  722. on:keydown={async (e) => {
  723. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  724. const commandsContainerElement =
  725. document.getElementById('commands-container');
  726. if (e.key === 'Escape') {
  727. stopResponse();
  728. }
  729. // Command/Ctrl + Shift + Enter to submit a message pair
  730. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  731. e.preventDefault();
  732. createMessagePair(prompt);
  733. }
  734. // Check if Ctrl + R is pressed
  735. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  736. e.preventDefault();
  737. console.log('regenerate');
  738. const regenerateButton = [
  739. ...document.getElementsByClassName('regenerate-response-button')
  740. ]?.at(-1);
  741. regenerateButton?.click();
  742. }
  743. if (prompt === '' && e.key == 'ArrowUp') {
  744. e.preventDefault();
  745. const userMessageElement = [
  746. ...document.getElementsByClassName('user-message')
  747. ]?.at(-1);
  748. const editButton = [
  749. ...document.getElementsByClassName('edit-user-message-button')
  750. ]?.at(-1);
  751. console.log(userMessageElement);
  752. userMessageElement.scrollIntoView({ block: 'center' });
  753. editButton?.click();
  754. }
  755. if (commandsContainerElement) {
  756. if (commandsContainerElement && e.key === 'ArrowUp') {
  757. e.preventDefault();
  758. commandsElement.selectUp();
  759. const commandOptionButton = [
  760. ...document.getElementsByClassName('selected-command-option-button')
  761. ]?.at(-1);
  762. commandOptionButton.scrollIntoView({ block: 'center' });
  763. }
  764. if (commandsContainerElement && e.key === 'ArrowDown') {
  765. e.preventDefault();
  766. commandsElement.selectDown();
  767. const commandOptionButton = [
  768. ...document.getElementsByClassName('selected-command-option-button')
  769. ]?.at(-1);
  770. commandOptionButton.scrollIntoView({ block: 'center' });
  771. }
  772. if (commandsContainerElement && e.key === 'Enter') {
  773. e.preventDefault();
  774. const commandOptionButton = [
  775. ...document.getElementsByClassName('selected-command-option-button')
  776. ]?.at(-1);
  777. if (e.shiftKey) {
  778. prompt = `${prompt}\n`;
  779. } else if (commandOptionButton) {
  780. commandOptionButton?.click();
  781. } else {
  782. document.getElementById('send-message-button')?.click();
  783. }
  784. }
  785. if (commandsContainerElement && e.key === 'Tab') {
  786. e.preventDefault();
  787. const commandOptionButton = [
  788. ...document.getElementsByClassName('selected-command-option-button')
  789. ]?.at(-1);
  790. commandOptionButton?.click();
  791. }
  792. } else {
  793. if (
  794. !$mobile ||
  795. !(
  796. 'ontouchstart' in window ||
  797. navigator.maxTouchPoints > 0 ||
  798. navigator.msMaxTouchPoints > 0
  799. )
  800. ) {
  801. if (isComposing) {
  802. return;
  803. }
  804. // Prevent Enter key from creating a new line
  805. const isCtrlPressed = e.ctrlKey || e.metaKey;
  806. const enterPressed =
  807. ($settings?.ctrlEnterToSend ?? false)
  808. ? (e.key === 'Enter' || e.keyCode === 13) && isCtrlPressed
  809. : (e.key === 'Enter' || e.keyCode === 13) && !e.shiftKey;
  810. console.log('Enter pressed:', enterPressed);
  811. if (enterPressed) {
  812. e.preventDefault();
  813. }
  814. // Submit the prompt when Enter key is pressed
  815. if ((prompt !== '' || files.length > 0) && enterPressed) {
  816. dispatch('submit', prompt);
  817. }
  818. }
  819. }
  820. if (e.key === 'Tab') {
  821. const words = extractCurlyBraceWords(prompt);
  822. if (words.length > 0) {
  823. const word = words.at(0);
  824. const fullPrompt = prompt;
  825. prompt = prompt.substring(0, word?.endIndex + 1);
  826. await tick();
  827. e.target.scrollTop = e.target.scrollHeight;
  828. prompt = fullPrompt;
  829. await tick();
  830. e.preventDefault();
  831. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  832. }
  833. e.target.style.height = '';
  834. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  835. }
  836. if (e.key === 'Escape') {
  837. console.log('Escape');
  838. atSelectedModel = undefined;
  839. selectedToolIds = [];
  840. webSearchEnabled = false;
  841. imageGenerationEnabled = false;
  842. }
  843. }}
  844. rows="1"
  845. on:input={async (e) => {
  846. e.target.style.height = '';
  847. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  848. }}
  849. on:focus={async (e) => {
  850. e.target.style.height = '';
  851. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  852. }}
  853. on:paste={async (e) => {
  854. const clipboardData = e.clipboardData || window.clipboardData;
  855. if (clipboardData && clipboardData.items) {
  856. for (const item of clipboardData.items) {
  857. if (item.type.indexOf('image') !== -1) {
  858. const blob = item.getAsFile();
  859. const reader = new FileReader();
  860. reader.onload = function (e) {
  861. files = [
  862. ...files,
  863. {
  864. type: 'image',
  865. url: `${e.target.result}`
  866. }
  867. ];
  868. };
  869. reader.readAsDataURL(blob);
  870. } else if (item.type === 'text/plain') {
  871. if ($settings?.largeTextAsFile ?? false) {
  872. const text = clipboardData.getData('text/plain');
  873. if (text.length > PASTED_TEXT_CHARACTER_LIMIT) {
  874. e.preventDefault();
  875. const blob = new Blob([text], { type: 'text/plain' });
  876. const file = new File([blob], `Pasted_Text_${Date.now()}.txt`, {
  877. type: 'text/plain'
  878. });
  879. await uploadFileHandler(file, true);
  880. }
  881. }
  882. }
  883. }
  884. }
  885. }}
  886. />
  887. {/if}
  888. </div>
  889. <div class=" flex justify-between mt-1 mb-2.5 mx-0.5 max-w-full" dir="ltr">
  890. <div class="ml-1 self-end flex items-center flex-1 max-w-[80%] gap-0.5">
  891. <InputMenu
  892. bind:selectedToolIds
  893. {screenCaptureHandler}
  894. {inputFilesHandler}
  895. uploadFilesHandler={() => {
  896. filesInputElement.click();
  897. }}
  898. uploadGoogleDriveHandler={async () => {
  899. try {
  900. const fileData = await createPicker();
  901. if (fileData) {
  902. const file = new File([fileData.blob], fileData.name, {
  903. type: fileData.blob.type
  904. });
  905. await uploadFileHandler(file);
  906. } else {
  907. console.log('No file was selected from Google Drive');
  908. }
  909. } catch (error) {
  910. console.error('Google Drive Error:', error);
  911. toast.error(
  912. $i18n.t('Error accessing Google Drive: {{error}}', {
  913. error: error.message
  914. })
  915. );
  916. }
  917. }}
  918. uploadOneDriveHandler={async (authorityType) => {
  919. try {
  920. const fileData = await pickAndDownloadFile(authorityType);
  921. if (fileData) {
  922. const file = new File([fileData.blob], fileData.name, {
  923. type: fileData.blob.type || 'application/octet-stream'
  924. });
  925. await uploadFileHandler(file);
  926. } else {
  927. console.log('No file was selected from OneDrive');
  928. }
  929. } catch (error) {
  930. console.error('OneDrive Error:', error);
  931. }
  932. }}
  933. onClose={async () => {
  934. await tick();
  935. const chatInput = document.getElementById('chat-input');
  936. chatInput?.focus();
  937. }}
  938. >
  939. <button
  940. class="bg-transparent hover:bg-gray-100 text-gray-800 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-1.5 outline-hidden focus:outline-hidden"
  941. type="button"
  942. aria-label="More"
  943. >
  944. <svg
  945. xmlns="http://www.w3.org/2000/svg"
  946. viewBox="0 0 20 20"
  947. fill="currentColor"
  948. class="size-5"
  949. >
  950. <path
  951. d="M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z"
  952. />
  953. </svg>
  954. </button>
  955. </InputMenu>
  956. <div class="flex gap-1 items-center overflow-x-auto scrollbar-none flex-1">
  957. {#if toolServers.length + selectedToolIds.length > 0}
  958. <Tooltip
  959. content={$i18n.t('{{COUNT}} Available Tools', {
  960. COUNT: toolServers.length + selectedToolIds.length
  961. })}
  962. >
  963. <button
  964. class="translate-y-[0.5px] flex gap-1 items-center text-gray-600 dark:text-gray-300 hover:text-gray-700 dark:hover:text-gray-200 rounded-lg p-1 self-center transition"
  965. aria-label="Available Tools"
  966. type="button"
  967. on:click={() => {
  968. showTools = !showTools;
  969. }}
  970. >
  971. <Wrench className="size-4" strokeWidth="1.75" />
  972. <span class="text-sm font-medium text-gray-600 dark:text-gray-300">
  973. {toolServers.length + selectedToolIds.length}
  974. </span>
  975. </button>
  976. </Tooltip>
  977. {/if}
  978. {#if $_user}
  979. {#if $config?.features?.enable_web_search && ($_user.role === 'admin' || $_user?.permissions?.features?.web_search)}
  980. <Tooltip content={$i18n.t('Search the internet')} placement="top">
  981. <button
  982. on:click|preventDefault={() => (webSearchEnabled = !webSearchEnabled)}
  983. type="button"
  984. class="px-1.5 @xl:px-2.5 py-1.5 flex gap-1.5 items-center text-sm rounded-full font-medium transition-colors duration-300 focus:outline-hidden max-w-full overflow-hidden border {webSearchEnabled ||
  985. ($settings?.webSearch ?? false) === 'always'
  986. ? 'bg-blue-100 dark:bg-blue-500/20 border-blue-400/20 text-blue-500 dark:text-blue-400'
  987. : 'bg-transparent border-transparent text-gray-600 dark:text-gray-300 border-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800'}"
  988. >
  989. <GlobeAlt className="size-5" strokeWidth="1.75" />
  990. <span
  991. class="hidden @xl:block whitespace-nowrap overflow-hidden text-ellipsis translate-y-[0.5px]"
  992. >{$i18n.t('Web Search')}</span
  993. >
  994. </button>
  995. </Tooltip>
  996. {/if}
  997. {#if $config?.features?.enable_image_generation && ($_user.role === 'admin' || $_user?.permissions?.features?.image_generation)}
  998. <Tooltip content={$i18n.t('Generate an image')} placement="top">
  999. <button
  1000. on:click|preventDefault={() =>
  1001. (imageGenerationEnabled = !imageGenerationEnabled)}
  1002. type="button"
  1003. class="px-1.5 @xl:px-2.5 py-1.5 flex gap-1.5 items-center text-sm rounded-full font-medium transition-colors duration-300 focus:outline-hidden max-w-full overflow-hidden border {imageGenerationEnabled
  1004. ? 'bg-gray-50 dark:bg-gray-400/10 border-gray-100 dark:border-gray-700 text-gray-600 dark:text-gray-400'
  1005. : 'bg-transparent border-transparent text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 '}"
  1006. >
  1007. <Photo className="size-5" strokeWidth="1.75" />
  1008. <span
  1009. class="hidden @xl:block whitespace-nowrap overflow-hidden text-ellipsis translate-y-[0.5px]"
  1010. >{$i18n.t('Image')}</span
  1011. >
  1012. </button>
  1013. </Tooltip>
  1014. {/if}
  1015. {#if $config?.features?.enable_code_interpreter && ($_user.role === 'admin' || $_user?.permissions?.features?.code_interpreter)}
  1016. <Tooltip content={$i18n.t('Execute code for analysis')} placement="top">
  1017. <button
  1018. on:click|preventDefault={() =>
  1019. (codeInterpreterEnabled = !codeInterpreterEnabled)}
  1020. type="button"
  1021. class="px-1.5 @xl:px-2.5 py-1.5 flex gap-1.5 items-center text-sm rounded-full font-medium transition-colors duration-300 focus:outline-hidden max-w-full overflow-hidden border {codeInterpreterEnabled
  1022. ? 'bg-gray-50 dark:bg-gray-400/10 border-gray-100 dark:border-gray-700 text-gray-600 dark:text-gray-400 '
  1023. : 'bg-transparent border-transparent text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 '}"
  1024. >
  1025. <CommandLine className="size-5" strokeWidth="1.75" />
  1026. <span
  1027. class="hidden @xl:block whitespace-nowrap overflow-hidden text-ellipsis translate-y-[0.5px]"
  1028. >{$i18n.t('Code Interpreter')}</span
  1029. >
  1030. </button>
  1031. </Tooltip>
  1032. {/if}
  1033. {/if}
  1034. </div>
  1035. </div>
  1036. <div class="self-end flex space-x-1 mr-1 shrink-0">
  1037. {#if (!history?.currentId || history.messages[history.currentId]?.done == true) && ($_user?.role === 'admin' || ($_user?.permissions?.chat?.stt ?? true))}
  1038. <Tooltip content={$i18n.t('Record voice')}>
  1039. <button
  1040. id="voice-input-button"
  1041. class=" text-gray-600 dark:text-gray-300 hover:text-gray-700 dark:hover:text-gray-200 transition rounded-full p-1.5 mr-0.5 self-center"
  1042. type="button"
  1043. on:click={async () => {
  1044. try {
  1045. let stream = await navigator.mediaDevices
  1046. .getUserMedia({ audio: true })
  1047. .catch(function (err) {
  1048. toast.error(
  1049. $i18n.t(
  1050. `Permission denied when accessing microphone: {{error}}`,
  1051. {
  1052. error: err
  1053. }
  1054. )
  1055. );
  1056. return null;
  1057. });
  1058. if (stream) {
  1059. recording = true;
  1060. const tracks = stream.getTracks();
  1061. tracks.forEach((track) => track.stop());
  1062. }
  1063. stream = null;
  1064. } catch {
  1065. toast.error($i18n.t('Permission denied when accessing microphone'));
  1066. }
  1067. }}
  1068. aria-label="Voice Input"
  1069. >
  1070. <svg
  1071. xmlns="http://www.w3.org/2000/svg"
  1072. viewBox="0 0 20 20"
  1073. fill="currentColor"
  1074. class="w-5 h-5 translate-y-[0.5px]"
  1075. >
  1076. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  1077. <path
  1078. d="M5.5 9.643a.75.75 0 00-1.5 0V10c0 3.06 2.29 5.585 5.25 5.954V17.5h-1.5a.75.75 0 000 1.5h4.5a.75.75 0 000-1.5h-1.5v-1.546A6.001 6.001 0 0016 10v-.357a.75.75 0 00-1.5 0V10a4.5 4.5 0 01-9 0v-.357z"
  1079. />
  1080. </svg>
  1081. </button>
  1082. </Tooltip>
  1083. {/if}
  1084. {#if (taskIds && taskIds.length > 0) || (history.currentId && history.messages[history.currentId]?.done != true)}
  1085. <div class=" flex items-center">
  1086. <Tooltip content={$i18n.t('Stop')}>
  1087. <button
  1088. class="bg-white hover:bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-1.5"
  1089. on:click={() => {
  1090. stopResponse();
  1091. }}
  1092. >
  1093. <svg
  1094. xmlns="http://www.w3.org/2000/svg"
  1095. viewBox="0 0 24 24"
  1096. fill="currentColor"
  1097. class="size-5"
  1098. >
  1099. <path
  1100. fill-rule="evenodd"
  1101. d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm6-2.438c0-.724.588-1.312 1.313-1.312h4.874c.725 0 1.313.588 1.313 1.313v4.874c0 .725-.588 1.313-1.313 1.313H9.564a1.312 1.312 0 01-1.313-1.313V9.564z"
  1102. clip-rule="evenodd"
  1103. />
  1104. </svg>
  1105. </button>
  1106. </Tooltip>
  1107. </div>
  1108. {:else if prompt === '' && files.length === 0 && ($_user?.role === 'admin' || ($_user?.permissions?.chat?.call ?? true))}
  1109. <div class=" flex items-center">
  1110. <Tooltip content={$i18n.t('Call')}>
  1111. <button
  1112. class=" bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 transition rounded-full p-1.5 self-center"
  1113. type="button"
  1114. on:click={async () => {
  1115. if (selectedModels.length > 1) {
  1116. toast.error($i18n.t('Select only one model to call'));
  1117. return;
  1118. }
  1119. if ($config.audio.stt.engine === 'web') {
  1120. toast.error(
  1121. $i18n.t('Call feature is not supported when using Web STT engine')
  1122. );
  1123. return;
  1124. }
  1125. // check if user has access to getUserMedia
  1126. try {
  1127. let stream = await navigator.mediaDevices.getUserMedia({
  1128. audio: true
  1129. });
  1130. // If the user grants the permission, proceed to show the call overlay
  1131. if (stream) {
  1132. const tracks = stream.getTracks();
  1133. tracks.forEach((track) => track.stop());
  1134. }
  1135. stream = null;
  1136. if ($settings.audio?.tts?.engine === 'browser-kokoro') {
  1137. // If the user has not initialized the TTS worker, initialize it
  1138. if (!$TTSWorker) {
  1139. await TTSWorker.set(
  1140. new KokoroWorker({
  1141. dtype: $settings.audio?.tts?.engineConfig?.dtype ?? 'fp32'
  1142. })
  1143. );
  1144. await $TTSWorker.init();
  1145. }
  1146. }
  1147. showCallOverlay.set(true);
  1148. showControls.set(true);
  1149. } catch (err) {
  1150. // If the user denies the permission or an error occurs, show an error message
  1151. toast.error(
  1152. $i18n.t('Permission denied when accessing media devices')
  1153. );
  1154. }
  1155. }}
  1156. aria-label="Call"
  1157. >
  1158. <Headphone className="size-5" />
  1159. </button>
  1160. </Tooltip>
  1161. </div>
  1162. {:else}
  1163. <div class=" flex items-center">
  1164. <Tooltip content={$i18n.t('Send message')}>
  1165. <button
  1166. id="send-message-button"
  1167. class="{!(prompt === '' && files.length === 0)
  1168. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  1169. : 'text-white bg-gray-200 dark:text-gray-900 dark:bg-gray-700 disabled'} transition rounded-full p-1.5 self-center"
  1170. type="submit"
  1171. disabled={prompt === '' && files.length === 0}
  1172. >
  1173. <svg
  1174. xmlns="http://www.w3.org/2000/svg"
  1175. viewBox="0 0 16 16"
  1176. fill="currentColor"
  1177. class="size-5"
  1178. >
  1179. <path
  1180. fill-rule="evenodd"
  1181. d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
  1182. clip-rule="evenodd"
  1183. />
  1184. </svg>
  1185. </button>
  1186. </Tooltip>
  1187. </div>
  1188. {/if}
  1189. </div>
  1190. </div>
  1191. </div>
  1192. </form>
  1193. {/if}
  1194. </div>
  1195. </div>
  1196. </div>
  1197. </div>
  1198. {/if}