MessageInput.svelte 48 KB

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