MessageInput.svelte 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { onMount, tick, getContext, createEventDispatcher } from 'svelte';
  4. const dispatch = createEventDispatcher();
  5. import {
  6. type Model,
  7. mobile,
  8. settings,
  9. showSidebar,
  10. models,
  11. config,
  12. showCallOverlay,
  13. tools,
  14. user as _user
  15. } from '$lib/stores';
  16. import { blobToFile, findWordIndices } from '$lib/utils';
  17. import { transcribeAudio } from '$lib/apis/audio';
  18. import { processDocToVectorDB } from '$lib/apis/rag';
  19. import { uploadFile } from '$lib/apis/files';
  20. import {
  21. SUPPORTED_FILE_TYPE,
  22. SUPPORTED_FILE_EXTENSIONS,
  23. WEBUI_BASE_URL,
  24. WEBUI_API_BASE_URL
  25. } from '$lib/constants';
  26. import Tooltip from '../common/Tooltip.svelte';
  27. import InputMenu from './MessageInput/InputMenu.svelte';
  28. import Headphone from '../icons/Headphone.svelte';
  29. import VoiceRecording from './MessageInput/VoiceRecording.svelte';
  30. import FileItem from '../common/FileItem.svelte';
  31. import FilesOverlay from './MessageInput/FilesOverlay.svelte';
  32. import Commands from './MessageInput/Commands.svelte';
  33. import XMark from '../icons/XMark.svelte';
  34. const i18n = getContext('i18n');
  35. export let transparentBackground = false;
  36. export let submitPrompt: Function;
  37. export let stopResponse: Function;
  38. export let autoScroll = false;
  39. export let atSelectedModel: Model | undefined;
  40. export let selectedModels: [''];
  41. let recording = false;
  42. let chatTextAreaElement: HTMLTextAreaElement;
  43. let filesInputElement;
  44. let commandsElement;
  45. let inputFiles;
  46. let dragged = false;
  47. let user = null;
  48. let chatInputPlaceholder = '';
  49. export let files = [];
  50. export let availableToolIds = [];
  51. export let selectedToolIds = [];
  52. export let webSearchEnabled = false;
  53. export let prompt = '';
  54. export let messages = [];
  55. let visionCapableModels = [];
  56. $: visionCapableModels = [...(atSelectedModel ? [atSelectedModel] : selectedModels)].filter(
  57. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.vision ?? true
  58. );
  59. $: if (prompt) {
  60. if (chatTextAreaElement) {
  61. chatTextAreaElement.style.height = '';
  62. chatTextAreaElement.style.height = Math.min(chatTextAreaElement.scrollHeight, 200) + 'px';
  63. }
  64. }
  65. const scrollToBottom = () => {
  66. const element = document.getElementById('messages-container');
  67. element.scrollTo({
  68. top: element.scrollHeight,
  69. behavior: 'smooth'
  70. });
  71. };
  72. const uploadFileHandler = async (file) => {
  73. console.log(file);
  74. // Check if the file is an audio file and transcribe/convert it to text file
  75. if (['audio/mpeg', 'audio/wav'].includes(file['type'])) {
  76. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  77. toast.error(error);
  78. return null;
  79. });
  80. if (res) {
  81. console.log(res);
  82. const blob = new Blob([res.text], { type: 'text/plain' });
  83. file = blobToFile(blob, `${file.name}.txt`);
  84. }
  85. }
  86. const fileItem = {
  87. type: 'file',
  88. file: '',
  89. id: null,
  90. url: '',
  91. name: file.name,
  92. collection_name: '',
  93. status: '',
  94. size: file.size,
  95. error: ''
  96. };
  97. files = [...files, fileItem];
  98. try {
  99. const uploadedFile = await uploadFile(localStorage.token, file);
  100. if (uploadedFile) {
  101. fileItem.status = 'uploaded';
  102. fileItem.file = uploadedFile;
  103. fileItem.id = uploadedFile.id;
  104. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  105. // TODO: Check if tools & functions have files support to skip this step to delegate file processing
  106. // Default Upload to VectorDB
  107. if (
  108. SUPPORTED_FILE_TYPE.includes(file['type']) ||
  109. SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
  110. ) {
  111. processFileItem(fileItem);
  112. } else {
  113. toast.error(
  114. $i18n.t(`Unknown file type '{{file_type}}'. Proceeding with the file upload anyway.`, {
  115. file_type: file['type']
  116. })
  117. );
  118. processFileItem(fileItem);
  119. }
  120. } else {
  121. files = files.filter((item) => item.status !== null);
  122. }
  123. } catch (e) {
  124. toast.error(e);
  125. files = files.filter((item) => item.status !== null);
  126. }
  127. };
  128. const processFileItem = async (fileItem) => {
  129. try {
  130. const res = await processDocToVectorDB(localStorage.token, fileItem.id);
  131. if (res) {
  132. fileItem.status = 'processed';
  133. fileItem.collection_name = res.collection_name;
  134. files = files;
  135. }
  136. } catch (e) {
  137. // Remove the failed doc from the files array
  138. // files = files.filter((f) => f.id !== fileItem.id);
  139. toast.error(e);
  140. fileItem.status = 'processed';
  141. files = files;
  142. }
  143. };
  144. const processFileCountLimit = async (querySettings, inputFiles) => {
  145. const maxFiles = querySettings.FILE_MAX_COUNT;
  146. const currentFilesCount = files.length;
  147. const inputFilesCount = inputFiles.length;
  148. const totalFilesCount = currentFilesCount + inputFilesCount;
  149. if (currentFilesCount >= maxFiles || totalFilesCount > maxFiles) {
  150. toast.error(`File count exceeds the limit of '${maxFiles}'. Please remove some files.`);
  151. if (currentFilesCount >= maxFiles) {
  152. return [false, null];
  153. }
  154. if (totalFilesCount > maxFiles) {
  155. inputFiles = inputFiles.slice(0, maxFiles - currentFilesCount);
  156. }
  157. }
  158. return [true, inputFiles];
  159. };
  160. const inputFilesHandler = async (inputFiles) => {
  161. inputFiles.forEach((file) => {
  162. if (['image/gif', 'image/webp', 'image/jpeg', 'image/png'].includes(file['type'])) {
  163. if (visionCapableModels.length === 0) {
  164. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  165. return;
  166. }
  167. let reader = new FileReader();
  168. reader.onload = (event) => {
  169. files = [
  170. ...files,
  171. {
  172. type: 'image',
  173. url: `${event.target.result}`
  174. }
  175. ];
  176. };
  177. reader.readAsDataURL(file);
  178. } else {
  179. uploadFileHandler(file);
  180. }
  181. });
  182. };
  183. onMount(() => {
  184. window.setTimeout(() => chatTextAreaElement?.focus(), 0);
  185. const dropZone = document.querySelector('body');
  186. const handleKeyDown = (event: KeyboardEvent) => {
  187. if (event.key === 'Escape') {
  188. console.log('Escape');
  189. dragged = false;
  190. }
  191. };
  192. const onDragOver = (e) => {
  193. e.preventDefault();
  194. dragged = true;
  195. };
  196. const onDragLeave = () => {
  197. dragged = false;
  198. };
  199. const onDrop = async (e) => {
  200. e.preventDefault();
  201. console.log(e);
  202. if (e.dataTransfer?.files) {
  203. const inputFiles = Array.from(e.dataTransfer?.files);
  204. console.log(file, file.name.split('.').at(-1));
  205. if (inputFiles && inputFiles.length > 0) {
  206. console.log(inputFiles);
  207. inputFilesHandler(inputFiles);
  208. } else {
  209. toast.error($i18n.t(`File not found.`));
  210. }
  211. }
  212. dragged = false;
  213. };
  214. window.addEventListener('keydown', handleKeyDown);
  215. dropZone?.addEventListener('dragover', onDragOver);
  216. dropZone?.addEventListener('drop', onDrop);
  217. dropZone?.addEventListener('dragleave', onDragLeave);
  218. return () => {
  219. window.removeEventListener('keydown', handleKeyDown);
  220. dropZone?.removeEventListener('dragover', onDragOver);
  221. dropZone?.removeEventListener('drop', onDrop);
  222. dropZone?.removeEventListener('dragleave', onDragLeave);
  223. };
  224. });
  225. </script>
  226. <FilesOverlay show={dragged} />
  227. <div class="w-full font-primary">
  228. <div class=" -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  229. <div class="flex flex-col max-w-6xl px-2.5 md:px-6 w-full">
  230. <div class="relative">
  231. {#if autoScroll === false && messages.length > 0}
  232. <div
  233. class=" absolute -top-12 left-0 right-0 flex justify-center z-30 pointer-events-none"
  234. >
  235. <button
  236. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full pointer-events-auto"
  237. on:click={() => {
  238. autoScroll = true;
  239. scrollToBottom();
  240. }}
  241. >
  242. <svg
  243. xmlns="http://www.w3.org/2000/svg"
  244. viewBox="0 0 20 20"
  245. fill="currentColor"
  246. class="w-5 h-5"
  247. >
  248. <path
  249. fill-rule="evenodd"
  250. 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"
  251. clip-rule="evenodd"
  252. />
  253. </svg>
  254. </button>
  255. </div>
  256. {/if}
  257. </div>
  258. <div class="w-full relative">
  259. {#if atSelectedModel !== undefined}
  260. <div
  261. class="px-3 py-2.5 text-left w-full flex justify-between items-center absolute bottom-0.5 left-0 right-0 bg-gradient-to-t from-50% from-white dark:from-gray-900 z-10"
  262. >
  263. <div class="flex items-center gap-2 text-sm dark:text-gray-500">
  264. <img
  265. crossorigin="anonymous"
  266. alt="model profile"
  267. class="size-5 max-w-[28px] object-cover rounded-full"
  268. src={$models.find((model) => model.id === atSelectedModel.id)?.info?.meta
  269. ?.profile_image_url ??
  270. ($i18n.language === 'dg-DG'
  271. ? `/doge.png`
  272. : `${WEBUI_BASE_URL}/static/favicon.png`)}
  273. />
  274. <div>
  275. Talking to <span class=" font-medium">{atSelectedModel.name}</span>
  276. </div>
  277. </div>
  278. <div>
  279. <button
  280. class="flex items-center"
  281. on:click={() => {
  282. atSelectedModel = undefined;
  283. }}
  284. >
  285. <XMark />
  286. </button>
  287. </div>
  288. </div>
  289. {/if}
  290. <Commands
  291. bind:this={commandsElement}
  292. bind:prompt
  293. bind:files
  294. on:select={(e) => {
  295. const data = e.detail;
  296. if (data?.type === 'model') {
  297. atSelectedModel = data.data;
  298. }
  299. chatTextAreaElement?.focus();
  300. }}
  301. />
  302. </div>
  303. </div>
  304. </div>
  305. <div class="{transparentBackground ? 'bg-transparent' : 'bg-white dark:bg-gray-900'} ">
  306. <div class="max-w-6xl px-2.5 md:px-6 mx-auto inset-x-0">
  307. <div class=" pb-2">
  308. <input
  309. bind:this={filesInputElement}
  310. bind:files={inputFiles}
  311. type="file"
  312. hidden
  313. multiple
  314. on:change={async () => {
  315. if (inputFiles && inputFiles.length > 0) {
  316. inputFilesHandler(inputFiles);
  317. } else {
  318. toast.error($i18n.t(`File not found.`));
  319. }
  320. filesInputElement.value = '';
  321. }}
  322. />
  323. {#if recording}
  324. <VoiceRecording
  325. bind:recording
  326. on:cancel={async () => {
  327. recording = false;
  328. await tick();
  329. document.getElementById('chat-textarea')?.focus();
  330. }}
  331. on:confirm={async (e) => {
  332. const response = e.detail;
  333. prompt = `${prompt}${response} `;
  334. recording = false;
  335. await tick();
  336. document.getElementById('chat-textarea')?.focus();
  337. if ($settings?.speechAutoSend ?? false) {
  338. submitPrompt(prompt);
  339. }
  340. }}
  341. />
  342. {:else}
  343. <form
  344. class="w-full flex gap-1.5"
  345. on:submit|preventDefault={() => {
  346. // check if selectedModels support image input
  347. submitPrompt(prompt);
  348. }}
  349. >
  350. <div
  351. class="flex-1 flex flex-col relative w-full rounded-3xl px-1.5 bg-gray-50 dark:bg-gray-850 dark:text-gray-100"
  352. dir={$settings?.chatDirection ?? 'LTR'}
  353. >
  354. {#if files.length > 0}
  355. <div class="mx-1 mt-2.5 mb-1 flex flex-wrap gap-2">
  356. {#each files as file, fileIdx}
  357. {#if file.type === 'image'}
  358. <div class=" relative group">
  359. <div class="relative">
  360. <img
  361. src={file.url}
  362. alt="input"
  363. class=" h-16 w-16 rounded-xl object-cover"
  364. />
  365. {#if atSelectedModel ? visionCapableModels.length === 0 : selectedModels.length !== visionCapableModels.length}
  366. <Tooltip
  367. className=" absolute top-1 left-1"
  368. content={$i18n.t('{{ models }}', {
  369. models: [...(atSelectedModel ? [atSelectedModel] : selectedModels)]
  370. .filter((id) => !visionCapableModels.includes(id))
  371. .join(', ')
  372. })}
  373. >
  374. <svg
  375. xmlns="http://www.w3.org/2000/svg"
  376. viewBox="0 0 24 24"
  377. fill="currentColor"
  378. class="size-4 fill-yellow-300"
  379. >
  380. <path
  381. fill-rule="evenodd"
  382. 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"
  383. clip-rule="evenodd"
  384. />
  385. </svg>
  386. </Tooltip>
  387. {/if}
  388. </div>
  389. <div class=" absolute -top-1 -right-1">
  390. <button
  391. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  392. type="button"
  393. on:click={() => {
  394. files.splice(fileIdx, 1);
  395. files = files;
  396. }}
  397. >
  398. <svg
  399. xmlns="http://www.w3.org/2000/svg"
  400. viewBox="0 0 20 20"
  401. fill="currentColor"
  402. class="w-4 h-4"
  403. >
  404. <path
  405. 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"
  406. />
  407. </svg>
  408. </button>
  409. </div>
  410. </div>
  411. {:else}
  412. <FileItem
  413. name={file.name}
  414. type={file.type}
  415. size={file?.size}
  416. status={file.status}
  417. dismissible={true}
  418. on:dismiss={() => {
  419. files.splice(fileIdx, 1);
  420. files = files;
  421. }}
  422. />
  423. {/if}
  424. {/each}
  425. </div>
  426. {/if}
  427. <div class=" flex">
  428. <div class=" ml-0.5 self-end mb-1.5 flex space-x-1">
  429. <InputMenu
  430. bind:webSearchEnabled
  431. bind:selectedToolIds
  432. tools={$tools.reduce((a, e, i, arr) => {
  433. if (availableToolIds.includes(e.id) || ($_user?.role ?? 'user') === 'admin') {
  434. a[e.id] = {
  435. name: e.name,
  436. description: e.meta.description,
  437. enabled: false
  438. };
  439. }
  440. return a;
  441. }, {})}
  442. uploadFilesHandler={() => {
  443. filesInputElement.click();
  444. }}
  445. onClose={async () => {
  446. await tick();
  447. chatTextAreaElement?.focus();
  448. }}
  449. >
  450. <button
  451. class="bg-gray-50 hover:bg-gray-100 text-gray-800 dark:bg-gray-850 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-2 outline-none focus:outline-none"
  452. type="button"
  453. >
  454. <svg
  455. xmlns="http://www.w3.org/2000/svg"
  456. viewBox="0 0 16 16"
  457. fill="currentColor"
  458. class="size-5"
  459. >
  460. <path
  461. d="M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z"
  462. />
  463. </svg>
  464. </button>
  465. </InputMenu>
  466. </div>
  467. <textarea
  468. id="chat-textarea"
  469. bind:this={chatTextAreaElement}
  470. class="scrollbar-hidden bg-gray-50 dark:bg-gray-850 dark:text-gray-100 outline-none w-full py-3 px-1 rounded-xl resize-none h-[48px]"
  471. placeholder={chatInputPlaceholder !== ''
  472. ? chatInputPlaceholder
  473. : $i18n.t('Send a Message')}
  474. bind:value={prompt}
  475. on:keypress={(e) => {
  476. if (
  477. !$mobile ||
  478. !(
  479. 'ontouchstart' in window ||
  480. navigator.maxTouchPoints > 0 ||
  481. navigator.msMaxTouchPoints > 0
  482. )
  483. ) {
  484. // Prevent Enter key from creating a new line
  485. if (e.key === 'Enter' && !e.shiftKey) {
  486. e.preventDefault();
  487. }
  488. // Submit the prompt when Enter key is pressed
  489. if (prompt !== '' && e.key === 'Enter' && !e.shiftKey) {
  490. submitPrompt(prompt);
  491. }
  492. }
  493. }}
  494. on:keydown={async (e) => {
  495. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  496. const commandsContainerElement = document.getElementById('commands-container');
  497. // Check if Ctrl + R is pressed
  498. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  499. e.preventDefault();
  500. console.log('regenerate');
  501. const regenerateButton = [
  502. ...document.getElementsByClassName('regenerate-response-button')
  503. ]?.at(-1);
  504. regenerateButton?.click();
  505. }
  506. if (prompt === '' && e.key == 'ArrowUp') {
  507. e.preventDefault();
  508. const userMessageElement = [
  509. ...document.getElementsByClassName('user-message')
  510. ]?.at(-1);
  511. const editButton = [
  512. ...document.getElementsByClassName('edit-user-message-button')
  513. ]?.at(-1);
  514. console.log(userMessageElement);
  515. userMessageElement.scrollIntoView({ block: 'center' });
  516. editButton?.click();
  517. }
  518. if (commandsContainerElement && e.key === 'ArrowUp') {
  519. e.preventDefault();
  520. commandsElement.selectUp();
  521. const commandOptionButton = [
  522. ...document.getElementsByClassName('selected-command-option-button')
  523. ]?.at(-1);
  524. commandOptionButton.scrollIntoView({ block: 'center' });
  525. }
  526. if (commandsContainerElement && e.key === 'ArrowDown') {
  527. e.preventDefault();
  528. commandsElement.selectDown();
  529. const commandOptionButton = [
  530. ...document.getElementsByClassName('selected-command-option-button')
  531. ]?.at(-1);
  532. commandOptionButton.scrollIntoView({ block: 'center' });
  533. }
  534. if (commandsContainerElement && e.key === 'Enter') {
  535. e.preventDefault();
  536. const commandOptionButton = [
  537. ...document.getElementsByClassName('selected-command-option-button')
  538. ]?.at(-1);
  539. if (e.shiftKey) {
  540. prompt = `${prompt}\n`;
  541. } else if (commandOptionButton) {
  542. commandOptionButton?.click();
  543. } else {
  544. document.getElementById('send-message-button')?.click();
  545. }
  546. }
  547. if (commandsContainerElement && e.key === 'Tab') {
  548. e.preventDefault();
  549. const commandOptionButton = [
  550. ...document.getElementsByClassName('selected-command-option-button')
  551. ]?.at(-1);
  552. commandOptionButton?.click();
  553. } else if (e.key === 'Tab') {
  554. const words = findWordIndices(prompt);
  555. if (words.length > 0) {
  556. const word = words.at(0);
  557. const fullPrompt = prompt;
  558. prompt = prompt.substring(0, word?.endIndex + 1);
  559. await tick();
  560. e.target.scrollTop = e.target.scrollHeight;
  561. prompt = fullPrompt;
  562. await tick();
  563. e.preventDefault();
  564. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  565. }
  566. e.target.style.height = '';
  567. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  568. }
  569. if (e.key === 'Escape') {
  570. console.log('Escape');
  571. atSelectedModel = undefined;
  572. }
  573. }}
  574. rows="1"
  575. on:input={async (e) => {
  576. e.target.style.height = '';
  577. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  578. user = null;
  579. }}
  580. on:focus={async (e) => {
  581. e.target.style.height = '';
  582. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  583. }}
  584. on:paste={async (e) => {
  585. const clipboardData = e.clipboardData || window.clipboardData;
  586. try {
  587. if (clipboardData && clipboardData.items) {
  588. const inputFiles = Array.from(clipboardData.items)
  589. .map((item) => item.getAsFile())
  590. .filter((file) => file);
  591. inputFilesHandler(inputFiles);
  592. } else {
  593. toast.error($i18n.t(`File not found.`));
  594. }
  595. } catch (error) {
  596. console.error('Error processing files:', error);
  597. toast.error($i18n.t(`An error occurred while processing files.`));
  598. }
  599. }}
  600. />
  601. <div class="self-end mb-2 flex space-x-1 mr-1">
  602. {#if messages.length == 0 || messages.at(-1).done == true}
  603. <Tooltip content={$i18n.t('Record voice')}>
  604. <button
  605. id="voice-input-button"
  606. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-1.5 mr-0.5 self-center"
  607. type="button"
  608. on:click={async () => {
  609. try {
  610. let stream = await navigator.mediaDevices
  611. .getUserMedia({ audio: true })
  612. .catch(function (err) {
  613. toast.error(
  614. $i18n.t(
  615. `Permission denied when accessing microphone: {{error}}`,
  616. {
  617. error: err
  618. }
  619. )
  620. );
  621. return null;
  622. });
  623. if (stream) {
  624. recording = true;
  625. const tracks = stream.getTracks();
  626. tracks.forEach((track) => track.stop());
  627. }
  628. stream = null;
  629. } catch {
  630. toast.error($i18n.t('Permission denied when accessing microphone'));
  631. }
  632. }}
  633. >
  634. <svg
  635. xmlns="http://www.w3.org/2000/svg"
  636. viewBox="0 0 20 20"
  637. fill="currentColor"
  638. class="w-5 h-5 translate-y-[0.5px]"
  639. >
  640. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  641. <path
  642. 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"
  643. />
  644. </svg>
  645. </button>
  646. </Tooltip>
  647. {/if}
  648. </div>
  649. </div>
  650. </div>
  651. <div class="flex items-end w-10">
  652. {#if messages.length == 0 || messages.at(-1).done == true}
  653. {#if prompt === ''}
  654. <div class=" flex items-center mb-1">
  655. <Tooltip content={$i18n.t('Call')}>
  656. <button
  657. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-2 self-center"
  658. type="button"
  659. on:click={async () => {
  660. if (selectedModels.length > 1) {
  661. toast.error($i18n.t('Select only one model to call'));
  662. return;
  663. }
  664. if ($config.audio.stt.engine === 'web') {
  665. toast.error(
  666. $i18n.t('Call feature is not supported when using Web STT engine')
  667. );
  668. return;
  669. }
  670. // check if user has access to getUserMedia
  671. try {
  672. let stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  673. // If the user grants the permission, proceed to show the call overlay
  674. if (stream) {
  675. const tracks = stream.getTracks();
  676. tracks.forEach((track) => track.stop());
  677. }
  678. stream = null;
  679. showCallOverlay.set(true);
  680. dispatch('call');
  681. } catch (err) {
  682. // If the user denies the permission or an error occurs, show an error message
  683. toast.error($i18n.t('Permission denied when accessing media devices'));
  684. }
  685. }}
  686. >
  687. <Headphone className="size-6" />
  688. </button>
  689. </Tooltip>
  690. </div>
  691. {:else}
  692. <div class=" flex items-center mb-1">
  693. <Tooltip content={$i18n.t('Send message')}>
  694. <button
  695. id="send-message-button"
  696. class="{prompt !== ''
  697. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  698. : 'text-white bg-gray-200 dark:text-gray-900 dark:bg-gray-700 disabled'} transition rounded-full p-1.5 m-0.5 self-center"
  699. type="submit"
  700. disabled={prompt === ''}
  701. >
  702. <svg
  703. xmlns="http://www.w3.org/2000/svg"
  704. viewBox="0 0 16 16"
  705. fill="currentColor"
  706. class="size-6"
  707. >
  708. <path
  709. fill-rule="evenodd"
  710. 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"
  711. clip-rule="evenodd"
  712. />
  713. </svg>
  714. </button>
  715. </Tooltip>
  716. </div>
  717. {/if}
  718. {:else}
  719. <div class=" flex items-center mb-1.5">
  720. <button
  721. 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"
  722. on:click={() => {
  723. stopResponse();
  724. }}
  725. >
  726. <svg
  727. xmlns="http://www.w3.org/2000/svg"
  728. viewBox="0 0 24 24"
  729. fill="currentColor"
  730. class="size-6"
  731. >
  732. <path
  733. fill-rule="evenodd"
  734. 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"
  735. clip-rule="evenodd"
  736. />
  737. </svg>
  738. </button>
  739. </div>
  740. {/if}
  741. </div>
  742. </form>
  743. {/if}
  744. <div class="mt-1.5 text-xs text-gray-500 text-center line-clamp-1">
  745. {$i18n.t('LLMs can make mistakes. Verify important information.')}
  746. </div>
  747. </div>
  748. </div>
  749. </div>
  750. </div>
  751. <style>
  752. .scrollbar-hidden:active::-webkit-scrollbar-thumb,
  753. .scrollbar-hidden:focus::-webkit-scrollbar-thumb,
  754. .scrollbar-hidden:hover::-webkit-scrollbar-thumb {
  755. visibility: visible;
  756. }
  757. .scrollbar-hidden::-webkit-scrollbar-thumb {
  758. visibility: hidden;
  759. }
  760. </style>