MessageInput.svelte 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { v4 as uuidv4 } from 'uuid';
  4. import { onMount, tick, getContext, createEventDispatcher, onDestroy } from 'svelte';
  5. const dispatch = createEventDispatcher();
  6. import {
  7. type Model,
  8. mobile,
  9. settings,
  10. showSidebar,
  11. models,
  12. config,
  13. showCallOverlay,
  14. tools,
  15. user as _user,
  16. showControls
  17. } from '$lib/stores';
  18. import { blobToFile, createMessagesList, findWordIndices } from '$lib/utils';
  19. import { transcribeAudio } from '$lib/apis/audio';
  20. import { uploadFile } from '$lib/apis/files';
  21. import { getTools } from '$lib/apis/tools';
  22. import { WEBUI_BASE_URL, WEBUI_API_BASE_URL, PASTED_TEXT_CHARACTER_LIMIT } from '$lib/constants';
  23. import Tooltip from '../common/Tooltip.svelte';
  24. import InputMenu from './MessageInput/InputMenu.svelte';
  25. import Headphone from '../icons/Headphone.svelte';
  26. import VoiceRecording from './MessageInput/VoiceRecording.svelte';
  27. import FileItem from '../common/FileItem.svelte';
  28. import FilesOverlay from './MessageInput/FilesOverlay.svelte';
  29. import Commands from './MessageInput/Commands.svelte';
  30. import XMark from '../icons/XMark.svelte';
  31. import RichTextInput from '../common/RichTextInput.svelte';
  32. import { generateAutoCompletion } from '$lib/apis';
  33. import { error, text } from '@sveltejs/kit';
  34. const i18n = getContext('i18n');
  35. export let transparentBackground = false;
  36. export let createMessagePair: Function;
  37. export let stopResponse: Function;
  38. export let autoScroll = false;
  39. export let atSelectedModel: Model | undefined;
  40. export let selectedModels: [''];
  41. let selectedModelIds = [];
  42. $: selectedModelIds = atSelectedModel !== undefined ? [atSelectedModel.id] : selectedModels;
  43. export let history;
  44. export let prompt = '';
  45. export let files = [];
  46. export let selectedToolIds = [];
  47. export let webSearchEnabled = false;
  48. let loaded = false;
  49. let recording = false;
  50. let chatInputContainerElement;
  51. let chatInputElement;
  52. let filesInputElement;
  53. let commandsElement;
  54. let inputFiles;
  55. let dragged = false;
  56. let user = null;
  57. export let placeholder = '';
  58. let visionCapableModels = [];
  59. $: visionCapableModels = [...(atSelectedModel ? [atSelectedModel] : selectedModels)].filter(
  60. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.vision ?? true
  61. );
  62. const scrollToBottom = () => {
  63. const element = document.getElementById('messages-container');
  64. element.scrollTo({
  65. top: element.scrollHeight,
  66. behavior: 'smooth'
  67. });
  68. };
  69. const uploadFileHandler = async (file, fullContext: boolean = false) => {
  70. if ($_user?.role !== 'admin' && !($_user?.permissions?.chat?.file_upload ?? true)) {
  71. toast.error($i18n.t('You do not have permission to upload files.'));
  72. return null;
  73. }
  74. console.log(file);
  75. const tempItemId = uuidv4();
  76. const fileItem = {
  77. type: 'file',
  78. file: '',
  79. id: null,
  80. url: '',
  81. name: file.name,
  82. collection_name: '',
  83. status: 'uploading',
  84. size: file.size,
  85. error: '',
  86. itemId: tempItemId,
  87. ...(fullContext ? { context: 'full' } : {})
  88. };
  89. if (fileItem.size == 0) {
  90. toast.error($i18n.t('You cannot upload an empty file.'));
  91. return null;
  92. }
  93. files = [...files, fileItem];
  94. // Check if the file is an audio file and transcribe/convert it to text file
  95. if (['audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/x-m4a'].includes(file['type'])) {
  96. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  97. toast.error(error);
  98. return null;
  99. });
  100. if (res) {
  101. console.log(res);
  102. const blob = new Blob([res.text], { type: 'text/plain' });
  103. file = blobToFile(blob, `${file.name}.txt`);
  104. fileItem.name = file.name;
  105. fileItem.size = file.size;
  106. }
  107. }
  108. try {
  109. // During the file upload, file content is automatically extracted.
  110. const uploadedFile = await uploadFile(localStorage.token, file);
  111. if (uploadedFile) {
  112. if (uploadedFile.error) {
  113. toast.warning(uploadedFile.error);
  114. }
  115. fileItem.status = 'uploaded';
  116. fileItem.file = uploadedFile;
  117. fileItem.id = uploadedFile.id;
  118. fileItem.collection_name = uploadedFile?.meta?.collection_name;
  119. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  120. files = files;
  121. } else {
  122. files = files.filter((item) => item?.itemId !== tempItemId);
  123. }
  124. } catch (e) {
  125. toast.error(e);
  126. files = files.filter((item) => item?.itemId !== tempItemId);
  127. }
  128. };
  129. const inputFilesHandler = async (inputFiles) => {
  130. inputFiles.forEach((file) => {
  131. console.log(file, file.name.split('.').at(-1));
  132. if (
  133. ($config?.file?.max_size ?? null) !== null &&
  134. file.size > ($config?.file?.max_size ?? 0) * 1024 * 1024
  135. ) {
  136. toast.error(
  137. $i18n.t(`File size should not exceed {{maxSize}} MB.`, {
  138. maxSize: $config?.file?.max_size
  139. })
  140. );
  141. return;
  142. }
  143. if (['image/gif', 'image/webp', 'image/jpeg', 'image/png'].includes(file['type'])) {
  144. if (visionCapableModels.length === 0) {
  145. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  146. return;
  147. }
  148. let reader = new FileReader();
  149. reader.onload = (event) => {
  150. files = [
  151. ...files,
  152. {
  153. type: 'image',
  154. url: `${event.target.result}`
  155. }
  156. ];
  157. };
  158. reader.readAsDataURL(file);
  159. } else {
  160. uploadFileHandler(file);
  161. }
  162. });
  163. };
  164. const handleKeyDown = (event: KeyboardEvent) => {
  165. if (event.key === 'Escape') {
  166. console.log('Escape');
  167. dragged = false;
  168. }
  169. };
  170. const onDragOver = (e) => {
  171. e.preventDefault();
  172. // Check if a file is being dragged.
  173. if (e.dataTransfer?.types?.includes('Files')) {
  174. dragged = true;
  175. } else {
  176. dragged = false;
  177. }
  178. };
  179. const onDragLeave = () => {
  180. dragged = false;
  181. };
  182. const onDrop = async (e) => {
  183. e.preventDefault();
  184. console.log(e);
  185. if (e.dataTransfer?.files) {
  186. const inputFiles = Array.from(e.dataTransfer?.files);
  187. if (inputFiles && inputFiles.length > 0) {
  188. console.log(inputFiles);
  189. inputFilesHandler(inputFiles);
  190. }
  191. }
  192. dragged = false;
  193. };
  194. onMount(async () => {
  195. loaded = true;
  196. window.setTimeout(() => {
  197. const chatInput = document.getElementById('chat-input');
  198. chatInput?.focus();
  199. }, 0);
  200. window.addEventListener('keydown', handleKeyDown);
  201. await tick();
  202. const dropzoneElement = document.getElementById('chat-container');
  203. dropzoneElement?.addEventListener('dragover', onDragOver);
  204. dropzoneElement?.addEventListener('drop', onDrop);
  205. dropzoneElement?.addEventListener('dragleave', onDragLeave);
  206. });
  207. onDestroy(() => {
  208. console.log('destroy');
  209. window.removeEventListener('keydown', handleKeyDown);
  210. const dropzoneElement = document.getElementById('chat-container');
  211. if (dropzoneElement) {
  212. dropzoneElement?.removeEventListener('dragover', onDragOver);
  213. dropzoneElement?.removeEventListener('drop', onDrop);
  214. dropzoneElement?.removeEventListener('dragleave', onDragLeave);
  215. }
  216. });
  217. </script>
  218. <FilesOverlay show={dragged} />
  219. {#if loaded}
  220. <div class="w-full font-primary">
  221. <div class=" -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  222. <div class="flex flex-col px-3 max-w-6xl w-full">
  223. <div class="relative">
  224. {#if autoScroll === false && history?.currentId}
  225. <div
  226. class=" absolute -top-12 left-0 right-0 flex justify-center z-30 pointer-events-none"
  227. >
  228. <button
  229. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full pointer-events-auto"
  230. on:click={() => {
  231. autoScroll = true;
  232. scrollToBottom();
  233. }}
  234. >
  235. <svg
  236. xmlns="http://www.w3.org/2000/svg"
  237. viewBox="0 0 20 20"
  238. fill="currentColor"
  239. class="w-5 h-5"
  240. >
  241. <path
  242. fill-rule="evenodd"
  243. 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"
  244. clip-rule="evenodd"
  245. />
  246. </svg>
  247. </button>
  248. </div>
  249. {/if}
  250. </div>
  251. <div class="w-full relative">
  252. {#if atSelectedModel !== undefined || selectedToolIds.length > 0 || webSearchEnabled}
  253. <div
  254. class="px-4 pb-0.5 pt-1.5 text-left w-full flex flex-col absolute bottom-0 left-0 right-0 bg-gradient-to-t from-white dark:from-gray-900 z-10"
  255. >
  256. {#if selectedToolIds.length > 0}
  257. <div class="flex items-center justify-between w-full">
  258. <div class="flex items-center gap-2.5 text-sm dark:text-gray-500">
  259. <div class="pl-1">
  260. <span class="relative flex size-2">
  261. <span
  262. class="animate-ping absolute inline-flex h-full w-full rounded-full bg-yellow-400 opacity-75"
  263. />
  264. <span class="relative inline-flex rounded-full size-2 bg-yellow-500" />
  265. </span>
  266. </div>
  267. <div class=" translate-y-[0.5px] text-ellipsis line-clamp-1 flex">
  268. {#each selectedToolIds.map((id) => {
  269. return $tools ? $tools.find((t) => t.id === id) : { id: id, name: id };
  270. }) as tool, toolIdx (toolIdx)}
  271. <Tooltip
  272. content={tool?.meta?.description ?? ''}
  273. className=" {toolIdx !== 0 ? 'pl-0.5' : ''} flex-shrink-0"
  274. placement="top"
  275. >
  276. {tool.name}
  277. </Tooltip>
  278. {#if toolIdx !== selectedToolIds.length - 1}
  279. <span>, </span>
  280. {/if}
  281. {/each}
  282. </div>
  283. </div>
  284. </div>
  285. {/if}
  286. {#if webSearchEnabled}
  287. <div class="flex items-center justify-between w-full">
  288. <div class="flex items-center gap-2.5 text-sm dark:text-gray-500">
  289. <div class="pl-1">
  290. <span class="relative flex size-2">
  291. <span
  292. class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"
  293. />
  294. <span class="relative inline-flex rounded-full size-2 bg-green-500" />
  295. </span>
  296. </div>
  297. <div class=" translate-y-[0.5px]">{$i18n.t('Search the web')}</div>
  298. </div>
  299. </div>
  300. {/if}
  301. {#if atSelectedModel !== undefined}
  302. <div class="flex items-center justify-between w-full">
  303. <div class="pl-[1px] flex items-center gap-2 text-sm dark:text-gray-500">
  304. <img
  305. crossorigin="anonymous"
  306. alt="model profile"
  307. class="size-3.5 max-w-[28px] object-cover rounded-full"
  308. src={$models.find((model) => model.id === atSelectedModel.id)?.info?.meta
  309. ?.profile_image_url ??
  310. ($i18n.language === 'dg-DG'
  311. ? `/doge.png`
  312. : `${WEBUI_BASE_URL}/static/favicon.png`)}
  313. />
  314. <div class="translate-y-[0.5px]">
  315. Talking to <span class=" font-medium">{atSelectedModel.name}</span>
  316. </div>
  317. </div>
  318. <div>
  319. <button
  320. class="flex items-center dark:text-gray-500"
  321. on:click={() => {
  322. atSelectedModel = undefined;
  323. }}
  324. >
  325. <XMark />
  326. </button>
  327. </div>
  328. </div>
  329. {/if}
  330. </div>
  331. {/if}
  332. <Commands
  333. bind:this={commandsElement}
  334. bind:prompt
  335. bind:files
  336. on:upload={(e) => {
  337. dispatch('upload', e.detail);
  338. }}
  339. on:select={(e) => {
  340. const data = e.detail;
  341. if (data?.type === 'model') {
  342. atSelectedModel = data.data;
  343. }
  344. const chatInputElement = document.getElementById('chat-input');
  345. chatInputElement?.focus();
  346. }}
  347. />
  348. </div>
  349. </div>
  350. </div>
  351. <div class="{transparentBackground ? 'bg-transparent' : 'bg-white dark:bg-gray-900'} ">
  352. <div class="max-w-6xl px-2.5 mx-auto inset-x-0">
  353. <div class="">
  354. <input
  355. bind:this={filesInputElement}
  356. bind:files={inputFiles}
  357. type="file"
  358. hidden
  359. multiple
  360. on:change={async () => {
  361. if (inputFiles && inputFiles.length > 0) {
  362. const _inputFiles = Array.from(inputFiles);
  363. inputFilesHandler(_inputFiles);
  364. } else {
  365. toast.error($i18n.t(`File not found.`));
  366. }
  367. filesInputElement.value = '';
  368. }}
  369. />
  370. {#if recording}
  371. <VoiceRecording
  372. bind:recording
  373. on:cancel={async () => {
  374. recording = false;
  375. await tick();
  376. document.getElementById('chat-input')?.focus();
  377. }}
  378. on:confirm={async (e) => {
  379. const { text, filename } = e.detail;
  380. prompt = `${prompt}${text} `;
  381. recording = false;
  382. await tick();
  383. document.getElementById('chat-input')?.focus();
  384. if ($settings?.speechAutoSend ?? false) {
  385. dispatch('submit', prompt);
  386. }
  387. }}
  388. />
  389. {:else}
  390. <form
  391. class="w-full flex gap-1.5"
  392. on:submit|preventDefault={() => {
  393. // check if selectedModels support image input
  394. dispatch('submit', prompt);
  395. }}
  396. >
  397. <div
  398. class="flex-1 flex flex-col relative w-full rounded-3xl px-1.5 bg-gray-50 dark:bg-gray-400/5 dark:text-gray-100"
  399. dir={$settings?.chatDirection ?? 'LTR'}
  400. >
  401. {#if files.length > 0}
  402. <div class="mx-1 mt-2.5 mb-1 flex flex-wrap gap-2">
  403. {#each files as file, fileIdx}
  404. {#if file.type === 'image'}
  405. <div class=" relative group">
  406. <div class="relative">
  407. <img
  408. src={file.url}
  409. alt="input"
  410. class=" h-16 w-16 rounded-xl object-cover"
  411. />
  412. {#if atSelectedModel ? visionCapableModels.length === 0 : selectedModels.length !== visionCapableModels.length}
  413. <Tooltip
  414. className=" absolute top-1 left-1"
  415. content={$i18n.t('{{ models }}', {
  416. models: [
  417. ...(atSelectedModel ? [atSelectedModel] : selectedModels)
  418. ]
  419. .filter((id) => !visionCapableModels.includes(id))
  420. .join(', ')
  421. })}
  422. >
  423. <svg
  424. xmlns="http://www.w3.org/2000/svg"
  425. viewBox="0 0 24 24"
  426. fill="currentColor"
  427. class="size-4 fill-yellow-300"
  428. >
  429. <path
  430. fill-rule="evenodd"
  431. 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"
  432. clip-rule="evenodd"
  433. />
  434. </svg>
  435. </Tooltip>
  436. {/if}
  437. </div>
  438. <div class=" absolute -top-1 -right-1">
  439. <button
  440. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  441. type="button"
  442. on:click={() => {
  443. files.splice(fileIdx, 1);
  444. files = files;
  445. }}
  446. >
  447. <svg
  448. xmlns="http://www.w3.org/2000/svg"
  449. viewBox="0 0 20 20"
  450. fill="currentColor"
  451. class="w-4 h-4"
  452. >
  453. <path
  454. 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"
  455. />
  456. </svg>
  457. </button>
  458. </div>
  459. </div>
  460. {:else}
  461. <FileItem
  462. item={file}
  463. name={file.name}
  464. type={file.type}
  465. size={file?.size}
  466. loading={file.status === 'uploading'}
  467. dismissible={true}
  468. edit={true}
  469. on:dismiss={() => {
  470. files.splice(fileIdx, 1);
  471. files = files;
  472. }}
  473. on:click={() => {
  474. console.log(file);
  475. }}
  476. />
  477. {/if}
  478. {/each}
  479. </div>
  480. {/if}
  481. <div class=" flex">
  482. <div class=" ml-0.5 self-end mb-1.5 flex space-x-1">
  483. <InputMenu
  484. bind:webSearchEnabled
  485. bind:selectedToolIds
  486. uploadFilesHandler={() => {
  487. filesInputElement.click();
  488. }}
  489. onClose={async () => {
  490. await tick();
  491. const chatInput = document.getElementById('chat-input');
  492. chatInput?.focus();
  493. }}
  494. >
  495. <button
  496. class="bg-transparent hover:bg-gray-100 text-gray-800 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-2 outline-none focus:outline-none"
  497. type="button"
  498. aria-label="More"
  499. >
  500. <svg
  501. xmlns="http://www.w3.org/2000/svg"
  502. viewBox="0 0 16 16"
  503. fill="currentColor"
  504. class="size-5"
  505. >
  506. <path
  507. d="M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z"
  508. />
  509. </svg>
  510. </button>
  511. </InputMenu>
  512. </div>
  513. {#if $settings?.richTextInput ?? true}
  514. <div
  515. class="scrollbar-hidden text-left bg-transparent dark:text-gray-100 outline-none w-full py-2.5 px-1 rounded-xl resize-none h-fit max-h-80 overflow-auto"
  516. >
  517. <RichTextInput
  518. bind:this={chatInputElement}
  519. bind:value={prompt}
  520. id="chat-input"
  521. messageInput={true}
  522. shiftEnter={!$mobile ||
  523. !(
  524. 'ontouchstart' in window ||
  525. navigator.maxTouchPoints > 0 ||
  526. navigator.msMaxTouchPoints > 0
  527. )}
  528. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  529. largeTextAsFile={$settings?.largeTextAsFile ?? false}
  530. autocomplete={true}
  531. generateAutoCompletion={async (text) => {
  532. if (selectedModelIds.length === 0 || !selectedModelIds.at(0)) {
  533. toast.error($i18n.t('Please select a model first.'));
  534. }
  535. const res = await generateAutoCompletion(
  536. localStorage.token,
  537. selectedModelIds.at(0),
  538. text,
  539. history?.currentId
  540. ? createMessagesList(history, history.currentId)
  541. : null
  542. ).catch((error) => {
  543. console.log(error);
  544. toast.error(error);
  545. return null;
  546. });
  547. console.log(res);
  548. return res;
  549. }}
  550. on:keydown={async (e) => {
  551. e = e.detail.event;
  552. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  553. const commandsContainerElement =
  554. document.getElementById('commands-container');
  555. // Command/Ctrl + Shift + Enter to submit a message pair
  556. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  557. e.preventDefault();
  558. createMessagePair(prompt);
  559. }
  560. // Check if Ctrl + R is pressed
  561. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  562. e.preventDefault();
  563. console.log('regenerate');
  564. const regenerateButton = [
  565. ...document.getElementsByClassName('regenerate-response-button')
  566. ]?.at(-1);
  567. regenerateButton?.click();
  568. }
  569. if (prompt === '' && e.key == 'ArrowUp') {
  570. e.preventDefault();
  571. const userMessageElement = [
  572. ...document.getElementsByClassName('user-message')
  573. ]?.at(-1);
  574. const editButton = [
  575. ...document.getElementsByClassName('edit-user-message-button')
  576. ]?.at(-1);
  577. console.log(userMessageElement);
  578. userMessageElement.scrollIntoView({ block: 'center' });
  579. editButton?.click();
  580. }
  581. if (commandsContainerElement) {
  582. if (commandsContainerElement && e.key === 'ArrowUp') {
  583. e.preventDefault();
  584. commandsElement.selectUp();
  585. const commandOptionButton = [
  586. ...document.getElementsByClassName('selected-command-option-button')
  587. ]?.at(-1);
  588. commandOptionButton.scrollIntoView({ block: 'center' });
  589. }
  590. if (commandsContainerElement && e.key === 'ArrowDown') {
  591. e.preventDefault();
  592. commandsElement.selectDown();
  593. const commandOptionButton = [
  594. ...document.getElementsByClassName('selected-command-option-button')
  595. ]?.at(-1);
  596. commandOptionButton.scrollIntoView({ block: 'center' });
  597. }
  598. if (commandsContainerElement && e.key === 'Tab') {
  599. e.preventDefault();
  600. const commandOptionButton = [
  601. ...document.getElementsByClassName('selected-command-option-button')
  602. ]?.at(-1);
  603. commandOptionButton?.click();
  604. }
  605. if (commandsContainerElement && e.key === 'Enter') {
  606. e.preventDefault();
  607. const commandOptionButton = [
  608. ...document.getElementsByClassName('selected-command-option-button')
  609. ]?.at(-1);
  610. if (commandOptionButton) {
  611. commandOptionButton?.click();
  612. } else {
  613. document.getElementById('send-message-button')?.click();
  614. }
  615. }
  616. } else {
  617. if (
  618. !$mobile ||
  619. !(
  620. 'ontouchstart' in window ||
  621. navigator.maxTouchPoints > 0 ||
  622. navigator.msMaxTouchPoints > 0
  623. )
  624. ) {
  625. // Prevent Enter key from creating a new line
  626. // Uses keyCode '13' for Enter key for chinese/japanese keyboards
  627. if (e.keyCode === 13 && !e.shiftKey) {
  628. e.preventDefault();
  629. }
  630. // Submit the prompt when Enter key is pressed
  631. if (prompt !== '' && e.keyCode === 13 && !e.shiftKey) {
  632. dispatch('submit', prompt);
  633. }
  634. }
  635. }
  636. if (e.key === 'Escape') {
  637. console.log('Escape');
  638. atSelectedModel = undefined;
  639. selectedToolIds = [];
  640. webSearchEnabled = false;
  641. }
  642. }}
  643. on:paste={async (e) => {
  644. e = e.detail.event;
  645. console.log(e);
  646. const clipboardData = e.clipboardData || window.clipboardData;
  647. if (clipboardData && clipboardData.items) {
  648. for (const item of clipboardData.items) {
  649. if (item.type.indexOf('image') !== -1) {
  650. const blob = item.getAsFile();
  651. const reader = new FileReader();
  652. reader.onload = function (e) {
  653. files = [
  654. ...files,
  655. {
  656. type: 'image',
  657. url: `${e.target.result}`
  658. }
  659. ];
  660. };
  661. reader.readAsDataURL(blob);
  662. } else if (item.type === 'text/plain') {
  663. if ($settings?.largeTextAsFile ?? false) {
  664. const text = clipboardData.getData('text/plain');
  665. if (text.length > PASTED_TEXT_CHARACTER_LIMIT) {
  666. e.preventDefault();
  667. const blob = new Blob([text], { type: 'text/plain' });
  668. const file = new File([blob], `Pasted_Text_${Date.now()}.txt`, {
  669. type: 'text/plain'
  670. });
  671. await uploadFileHandler(file, true);
  672. }
  673. }
  674. }
  675. }
  676. }
  677. }}
  678. />
  679. </div>
  680. {:else}
  681. <textarea
  682. id="chat-input"
  683. bind:this={chatInputElement}
  684. class="scrollbar-hidden bg-gray-50 dark:bg-gray-850 dark:text-gray-100 outline-none w-full py-3 px-1 rounded-xl resize-none h-[48px]"
  685. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  686. bind:value={prompt}
  687. on:keypress={(e) => {
  688. if (
  689. !$mobile ||
  690. !(
  691. 'ontouchstart' in window ||
  692. navigator.maxTouchPoints > 0 ||
  693. navigator.msMaxTouchPoints > 0
  694. )
  695. ) {
  696. // Prevent Enter key from creating a new line
  697. if (e.key === 'Enter' && !e.shiftKey) {
  698. e.preventDefault();
  699. }
  700. // Submit the prompt when Enter key is pressed
  701. if (prompt !== '' && e.key === 'Enter' && !e.shiftKey) {
  702. dispatch('submit', prompt);
  703. }
  704. }
  705. }}
  706. on:keydown={async (e) => {
  707. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  708. const commandsContainerElement =
  709. document.getElementById('commands-container');
  710. // Command/Ctrl + Shift + Enter to submit a message pair
  711. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  712. e.preventDefault();
  713. createMessagePair(prompt);
  714. }
  715. // Check if Ctrl + R is pressed
  716. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  717. e.preventDefault();
  718. console.log('regenerate');
  719. const regenerateButton = [
  720. ...document.getElementsByClassName('regenerate-response-button')
  721. ]?.at(-1);
  722. regenerateButton?.click();
  723. }
  724. if (prompt === '' && e.key == 'ArrowUp') {
  725. e.preventDefault();
  726. const userMessageElement = [
  727. ...document.getElementsByClassName('user-message')
  728. ]?.at(-1);
  729. const editButton = [
  730. ...document.getElementsByClassName('edit-user-message-button')
  731. ]?.at(-1);
  732. console.log(userMessageElement);
  733. userMessageElement.scrollIntoView({ block: 'center' });
  734. editButton?.click();
  735. }
  736. if (commandsContainerElement && e.key === 'ArrowUp') {
  737. e.preventDefault();
  738. commandsElement.selectUp();
  739. const commandOptionButton = [
  740. ...document.getElementsByClassName('selected-command-option-button')
  741. ]?.at(-1);
  742. commandOptionButton.scrollIntoView({ block: 'center' });
  743. }
  744. if (commandsContainerElement && e.key === 'ArrowDown') {
  745. e.preventDefault();
  746. commandsElement.selectDown();
  747. const commandOptionButton = [
  748. ...document.getElementsByClassName('selected-command-option-button')
  749. ]?.at(-1);
  750. commandOptionButton.scrollIntoView({ block: 'center' });
  751. }
  752. if (commandsContainerElement && e.key === 'Enter') {
  753. e.preventDefault();
  754. const commandOptionButton = [
  755. ...document.getElementsByClassName('selected-command-option-button')
  756. ]?.at(-1);
  757. if (e.shiftKey) {
  758. prompt = `${prompt}\n`;
  759. } else if (commandOptionButton) {
  760. commandOptionButton?.click();
  761. } else {
  762. document.getElementById('send-message-button')?.click();
  763. }
  764. }
  765. if (commandsContainerElement && e.key === 'Tab') {
  766. e.preventDefault();
  767. const commandOptionButton = [
  768. ...document.getElementsByClassName('selected-command-option-button')
  769. ]?.at(-1);
  770. commandOptionButton?.click();
  771. } else if (e.key === 'Tab') {
  772. const words = findWordIndices(prompt);
  773. if (words.length > 0) {
  774. const word = words.at(0);
  775. const fullPrompt = prompt;
  776. prompt = prompt.substring(0, word?.endIndex + 1);
  777. await tick();
  778. e.target.scrollTop = e.target.scrollHeight;
  779. prompt = fullPrompt;
  780. await tick();
  781. e.preventDefault();
  782. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  783. }
  784. e.target.style.height = '';
  785. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  786. }
  787. if (e.key === 'Escape') {
  788. console.log('Escape');
  789. atSelectedModel = undefined;
  790. selectedToolIds = [];
  791. webSearchEnabled = false;
  792. }
  793. }}
  794. rows="1"
  795. on:input={async (e) => {
  796. e.target.style.height = '';
  797. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  798. }}
  799. on:focus={async (e) => {
  800. e.target.style.height = '';
  801. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  802. }}
  803. on:paste={async (e) => {
  804. const clipboardData = e.clipboardData || window.clipboardData;
  805. if (clipboardData && clipboardData.items) {
  806. for (const item of clipboardData.items) {
  807. if (item.type.indexOf('image') !== -1) {
  808. const blob = item.getAsFile();
  809. const reader = new FileReader();
  810. reader.onload = function (e) {
  811. files = [
  812. ...files,
  813. {
  814. type: 'image',
  815. url: `${e.target.result}`
  816. }
  817. ];
  818. };
  819. reader.readAsDataURL(blob);
  820. } else if (item.type === 'text/plain') {
  821. if ($settings?.largeTextAsFile ?? false) {
  822. const text = clipboardData.getData('text/plain');
  823. if (text.length > PASTED_TEXT_CHARACTER_LIMIT) {
  824. e.preventDefault();
  825. const blob = new Blob([text], { type: 'text/plain' });
  826. const file = new File([blob], `Pasted_Text_${Date.now()}.txt`, {
  827. type: 'text/plain'
  828. });
  829. await uploadFileHandler(file, true);
  830. }
  831. }
  832. }
  833. }
  834. }
  835. }}
  836. />
  837. {/if}
  838. <div class="self-end mb-2 flex space-x-1 mr-1">
  839. {#if !history?.currentId || history.messages[history.currentId]?.done == true}
  840. <Tooltip content={$i18n.t('Record voice')}>
  841. <button
  842. id="voice-input-button"
  843. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-1.5 mr-0.5 self-center"
  844. type="button"
  845. on:click={async () => {
  846. try {
  847. let stream = await navigator.mediaDevices
  848. .getUserMedia({ audio: true })
  849. .catch(function (err) {
  850. toast.error(
  851. $i18n.t(
  852. `Permission denied when accessing microphone: {{error}}`,
  853. {
  854. error: err
  855. }
  856. )
  857. );
  858. return null;
  859. });
  860. if (stream) {
  861. recording = true;
  862. const tracks = stream.getTracks();
  863. tracks.forEach((track) => track.stop());
  864. }
  865. stream = null;
  866. } catch {
  867. toast.error($i18n.t('Permission denied when accessing microphone'));
  868. }
  869. }}
  870. aria-label="Voice Input"
  871. >
  872. <svg
  873. xmlns="http://www.w3.org/2000/svg"
  874. viewBox="0 0 20 20"
  875. fill="currentColor"
  876. class="w-5 h-5 translate-y-[0.5px]"
  877. >
  878. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  879. <path
  880. 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"
  881. />
  882. </svg>
  883. </button>
  884. </Tooltip>
  885. {/if}
  886. </div>
  887. </div>
  888. </div>
  889. <div class="flex items-end w-10">
  890. {#if !history.currentId || history.messages[history.currentId]?.done == true}
  891. {#if prompt === ''}
  892. <div class=" flex items-center mb-1">
  893. <Tooltip content={$i18n.t('Call')}>
  894. <button
  895. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-2 self-center"
  896. type="button"
  897. on:click={async () => {
  898. if (selectedModels.length > 1) {
  899. toast.error($i18n.t('Select only one model to call'));
  900. return;
  901. }
  902. if ($config.audio.stt.engine === 'web') {
  903. toast.error(
  904. $i18n.t('Call feature is not supported when using Web STT engine')
  905. );
  906. return;
  907. }
  908. // check if user has access to getUserMedia
  909. try {
  910. let stream = await navigator.mediaDevices.getUserMedia({
  911. audio: true
  912. });
  913. // If the user grants the permission, proceed to show the call overlay
  914. if (stream) {
  915. const tracks = stream.getTracks();
  916. tracks.forEach((track) => track.stop());
  917. }
  918. stream = null;
  919. showCallOverlay.set(true);
  920. showControls.set(true);
  921. } catch (err) {
  922. // If the user denies the permission or an error occurs, show an error message
  923. toast.error(
  924. $i18n.t('Permission denied when accessing media devices')
  925. );
  926. }
  927. }}
  928. aria-label="Call"
  929. >
  930. <Headphone className="size-6" />
  931. </button>
  932. </Tooltip>
  933. </div>
  934. {:else}
  935. <div class=" flex items-center mb-1">
  936. <Tooltip content={$i18n.t('Send message')}>
  937. <button
  938. id="send-message-button"
  939. class="{prompt !== ''
  940. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  941. : 'text-white bg-gray-200 dark:text-gray-900 dark:bg-gray-700 disabled'} transition rounded-full p-1.5 m-0.5 self-center"
  942. type="submit"
  943. disabled={prompt === ''}
  944. >
  945. <svg
  946. xmlns="http://www.w3.org/2000/svg"
  947. viewBox="0 0 16 16"
  948. fill="currentColor"
  949. class="size-6"
  950. >
  951. <path
  952. fill-rule="evenodd"
  953. 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"
  954. clip-rule="evenodd"
  955. />
  956. </svg>
  957. </button>
  958. </Tooltip>
  959. </div>
  960. {/if}
  961. {:else}
  962. <div class=" flex items-center mb-1.5">
  963. <Tooltip content={$i18n.t('Stop')}>
  964. <button
  965. 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"
  966. on:click={() => {
  967. stopResponse();
  968. }}
  969. >
  970. <svg
  971. xmlns="http://www.w3.org/2000/svg"
  972. viewBox="0 0 24 24"
  973. fill="currentColor"
  974. class="size-6"
  975. >
  976. <path
  977. fill-rule="evenodd"
  978. 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"
  979. clip-rule="evenodd"
  980. />
  981. </svg>
  982. </button>
  983. </Tooltip>
  984. </div>
  985. {/if}
  986. </div>
  987. </form>
  988. {/if}
  989. </div>
  990. </div>
  991. </div>
  992. </div>
  993. {/if}