MessageInput.svelte 39 KB

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