MessageInput.svelte 39 KB

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