MessageInput.svelte 47 KB

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