MessageInput.svelte 37 KB

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