MessageInput.svelte 25 KB

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