MessageInput.svelte 47 KB

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