1
0

MessageInput.svelte 42 KB

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