MessageInput.svelte 47 KB

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