MessageInput.svelte 25 KB

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