MessageInput.svelte 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  1. <script lang="ts">
  2. import DOMPurify from 'dompurify';
  3. import { marked } from 'marked';
  4. import heic2any from 'heic2any';
  5. import { toast } from 'svelte-sonner';
  6. import { v4 as uuidv4 } from 'uuid';
  7. import { createPicker, getAuthToken } from '$lib/utils/google-drive-picker';
  8. import { pickAndDownloadFile } from '$lib/utils/onedrive-file-picker';
  9. import { onMount, tick, getContext, createEventDispatcher, onDestroy } from 'svelte';
  10. const dispatch = createEventDispatcher();
  11. import {
  12. type Model,
  13. mobile,
  14. settings,
  15. showSidebar,
  16. models,
  17. config,
  18. showCallOverlay,
  19. tools,
  20. user as _user,
  21. showControls,
  22. TTSWorker,
  23. temporaryChatEnabled
  24. } from '$lib/stores';
  25. import {
  26. blobToFile,
  27. compressImage,
  28. createMessagesList,
  29. extractContentFromFile,
  30. extractCurlyBraceWords,
  31. extractInputVariables,
  32. getAge,
  33. getCurrentDateTime,
  34. getFormattedDate,
  35. getFormattedTime,
  36. getUserPosition,
  37. getUserTimezone,
  38. getWeekday
  39. } from '$lib/utils';
  40. import { uploadFile } from '$lib/apis/files';
  41. import { generateAutoCompletion } from '$lib/apis';
  42. import { deleteFileById } from '$lib/apis/files';
  43. import { WEBUI_BASE_URL, WEBUI_API_BASE_URL, PASTED_TEXT_CHARACTER_LIMIT } from '$lib/constants';
  44. import InputMenu from './MessageInput/InputMenu.svelte';
  45. import VoiceRecording from './MessageInput/VoiceRecording.svelte';
  46. import FilesOverlay from './MessageInput/FilesOverlay.svelte';
  47. import Commands from './MessageInput/Commands.svelte';
  48. import ToolServersModal from './ToolServersModal.svelte';
  49. import RichTextInput from '../common/RichTextInput.svelte';
  50. import Tooltip from '../common/Tooltip.svelte';
  51. import FileItem from '../common/FileItem.svelte';
  52. import Image from '../common/Image.svelte';
  53. import XMark from '../icons/XMark.svelte';
  54. import Headphone from '../icons/Headphone.svelte';
  55. import GlobeAlt from '../icons/GlobeAlt.svelte';
  56. import Photo from '../icons/Photo.svelte';
  57. import Wrench from '../icons/Wrench.svelte';
  58. import CommandLine from '../icons/CommandLine.svelte';
  59. import Sparkles from '../icons/Sparkles.svelte';
  60. import { KokoroWorker } from '$lib/workers/KokoroWorker';
  61. import InputVariablesModal from './MessageInput/InputVariablesModal.svelte';
  62. import Voice from '../icons/Voice.svelte';
  63. import { getSessionUser } from '$lib/apis/auths';
  64. const i18n = getContext('i18n');
  65. export let onChange: Function = () => {};
  66. export let createMessagePair: Function;
  67. export let stopResponse: Function;
  68. export let autoScroll = false;
  69. export let generating = false;
  70. export let atSelectedModel: Model | undefined = undefined;
  71. export let selectedModels: [''];
  72. let selectedModelIds = [];
  73. $: selectedModelIds = atSelectedModel !== undefined ? [atSelectedModel.id] : selectedModels;
  74. export let history;
  75. export let taskIds = null;
  76. export let prompt = '';
  77. export let files = [];
  78. export let toolServers = [];
  79. export let selectedToolIds = [];
  80. export let selectedFilterIds = [];
  81. export let imageGenerationEnabled = false;
  82. export let webSearchEnabled = false;
  83. export let codeInterpreterEnabled = false;
  84. let showInputVariablesModal = false;
  85. let inputVariables = {};
  86. let inputVariableValues = {};
  87. $: onChange({
  88. prompt,
  89. files: files
  90. .filter((file) => file.type !== 'image')
  91. .map((file) => {
  92. return {
  93. ...file,
  94. user: undefined,
  95. access_control: undefined
  96. };
  97. }),
  98. selectedToolIds,
  99. selectedFilterIds,
  100. imageGenerationEnabled,
  101. webSearchEnabled,
  102. codeInterpreterEnabled
  103. });
  104. const inputVariableHandler = async (text: string) => {
  105. inputVariables = extractInputVariables(text);
  106. if (Object.keys(inputVariables).length > 0) {
  107. showInputVariablesModal = true;
  108. }
  109. };
  110. const textVariableHandler = async (text: string) => {
  111. if (text.includes('{{CLIPBOARD}}')) {
  112. const clipboardText = await navigator.clipboard.readText().catch((err) => {
  113. toast.error($i18n.t('Failed to read clipboard contents'));
  114. return '{{CLIPBOARD}}';
  115. });
  116. const clipboardItems = await navigator.clipboard.read();
  117. let imageUrl = null;
  118. for (const item of clipboardItems) {
  119. // Check for known image types
  120. for (const type of item.types) {
  121. if (type.startsWith('image/')) {
  122. const blob = await item.getType(type);
  123. imageUrl = URL.createObjectURL(blob);
  124. }
  125. }
  126. }
  127. if (imageUrl) {
  128. files = [
  129. ...files,
  130. {
  131. type: 'image',
  132. url: imageUrl
  133. }
  134. ];
  135. }
  136. text = text.replaceAll('{{CLIPBOARD}}', clipboardText);
  137. }
  138. if (text.includes('{{USER_LOCATION}}')) {
  139. let location;
  140. try {
  141. location = await getUserPosition();
  142. } catch (error) {
  143. toast.error($i18n.t('Location access not allowed'));
  144. location = 'LOCATION_UNKNOWN';
  145. }
  146. text = text.replaceAll('{{USER_LOCATION}}', String(location));
  147. }
  148. const sessionUser = await getSessionUser(localStorage.token);
  149. if (text.includes('{{USER_NAME}}')) {
  150. const name = sessionUser?.name || 'User';
  151. text = text.replaceAll('{{USER_NAME}}', name);
  152. }
  153. if (text.includes('{{USER_BIO}}')) {
  154. const bio = sessionUser?.bio || '';
  155. if (bio) {
  156. text = text.replaceAll('{{USER_BIO}}', bio);
  157. }
  158. }
  159. if (text.includes('{{USER_GENDER}}')) {
  160. const gender = sessionUser?.gender || '';
  161. if (gender) {
  162. text = text.replaceAll('{{USER_GENDER}}', gender);
  163. }
  164. }
  165. if (text.includes('{{USER_BIRTH_DATE}}')) {
  166. const birthDate = sessionUser?.date_of_birth || '';
  167. if (birthDate) {
  168. text = text.replaceAll('{{USER_BIRTH_DATE}}', birthDate);
  169. }
  170. }
  171. if (text.includes('{{USER_AGE}}')) {
  172. const birthDate = sessionUser?.date_of_birth || '';
  173. if (birthDate) {
  174. // calculate age using date
  175. const age = getAge(birthDate);
  176. text = text.replaceAll('{{USER_AGE}}', age);
  177. }
  178. }
  179. if (text.includes('{{USER_LANGUAGE}}')) {
  180. const language = localStorage.getItem('locale') || 'en-US';
  181. text = text.replaceAll('{{USER_LANGUAGE}}', language);
  182. }
  183. if (text.includes('{{CURRENT_DATE}}')) {
  184. const date = getFormattedDate();
  185. text = text.replaceAll('{{CURRENT_DATE}}', date);
  186. }
  187. if (text.includes('{{CURRENT_TIME}}')) {
  188. const time = getFormattedTime();
  189. text = text.replaceAll('{{CURRENT_TIME}}', time);
  190. }
  191. if (text.includes('{{CURRENT_DATETIME}}')) {
  192. const dateTime = getCurrentDateTime();
  193. text = text.replaceAll('{{CURRENT_DATETIME}}', dateTime);
  194. }
  195. if (text.includes('{{CURRENT_TIMEZONE}}')) {
  196. const timezone = getUserTimezone();
  197. text = text.replaceAll('{{CURRENT_TIMEZONE}}', timezone);
  198. }
  199. if (text.includes('{{CURRENT_WEEKDAY}}')) {
  200. const weekday = getWeekday();
  201. text = text.replaceAll('{{CURRENT_WEEKDAY}}', weekday);
  202. }
  203. inputVariableHandler(text);
  204. return text;
  205. };
  206. const replaceVariables = (variables: Record<string, any>) => {
  207. console.log('Replacing variables:', variables);
  208. const chatInput = document.getElementById('chat-input');
  209. if (chatInput) {
  210. if ($settings?.richTextInput ?? true) {
  211. chatInputElement.replaceVariables(variables);
  212. chatInputElement.focus();
  213. } else {
  214. // Get current value from the input element
  215. let currentValue = chatInput.value || '';
  216. // Replace template variables using regex
  217. const updatedValue = currentValue.replace(
  218. /{{\s*([^|}]+)(?:\|[^}]*)?\s*}}/g,
  219. (match, varName) => {
  220. const trimmedVarName = varName.trim();
  221. return variables.hasOwnProperty(trimmedVarName)
  222. ? String(variables[trimmedVarName])
  223. : match;
  224. }
  225. );
  226. // Update the input value
  227. chatInput.value = updatedValue;
  228. chatInput.focus();
  229. chatInput.dispatchEvent(new Event('input', { bubbles: true }));
  230. }
  231. }
  232. };
  233. export const setText = async (text?: string) => {
  234. const chatInput = document.getElementById('chat-input');
  235. if (chatInput) {
  236. text = await textVariableHandler(text || '');
  237. if ($settings?.richTextInput ?? true) {
  238. chatInputElement?.setText(text);
  239. chatInputElement?.focus();
  240. } else {
  241. chatInput.value = text;
  242. prompt = text;
  243. chatInput.focus();
  244. chatInput.dispatchEvent(new Event('input'));
  245. }
  246. }
  247. };
  248. const getCommand = () => {
  249. const getWordAtCursor = (text, cursor) => {
  250. if (typeof text !== 'string' || cursor == null) return '';
  251. const left = text.slice(0, cursor);
  252. const right = text.slice(cursor);
  253. const leftWord = left.match(/(?:^|\s)([^\s]*)$/)?.[1] || '';
  254. const rightWord = right.match(/^([^\s]*)/)?.[1] || '';
  255. return leftWord + rightWord;
  256. };
  257. const chatInput = document.getElementById('chat-input');
  258. let word = '';
  259. if (chatInput) {
  260. if ($settings?.richTextInput ?? true) {
  261. word = chatInputElement?.getWordAtDocPos();
  262. } else {
  263. const cursor = chatInput ? chatInput.selectionStart : prompt.length;
  264. word = getWordAtCursor(prompt, cursor);
  265. }
  266. }
  267. return word;
  268. };
  269. const replaceCommandWithText = (text) => {
  270. const getWordBoundsAtCursor = (text, cursor) => {
  271. let start = cursor,
  272. end = cursor;
  273. while (start > 0 && !/\s/.test(text[start - 1])) --start;
  274. while (end < text.length && !/\s/.test(text[end])) ++end;
  275. return { start, end };
  276. };
  277. const chatInput = document.getElementById('chat-input');
  278. if (!chatInput) return;
  279. if ($settings?.richTextInput ?? true) {
  280. chatInputElement?.replaceCommandWithText(text);
  281. } else {
  282. const cursor = chatInput.selectionStart;
  283. const { start, end } = getWordBoundsAtCursor(prompt, cursor);
  284. prompt = prompt.slice(0, start) + text + prompt.slice(end);
  285. chatInput.focus();
  286. chatInput.setSelectionRange(start + text.length, start + text.length);
  287. }
  288. };
  289. const insertTextAtCursor = async (text: string) => {
  290. const chatInput = document.getElementById('chat-input');
  291. if (!chatInput) return;
  292. text = await textVariableHandler(text);
  293. if (command) {
  294. replaceCommandWithText(text);
  295. } else {
  296. if ($settings?.richTextInput ?? true) {
  297. chatInputElement?.insertContent(text);
  298. } else {
  299. const cursor = chatInput.selectionStart;
  300. prompt = prompt.slice(0, cursor) + text + prompt.slice(cursor);
  301. chatInput.focus();
  302. chatInput.setSelectionRange(cursor + text.length, cursor + text.length);
  303. }
  304. }
  305. await tick();
  306. const chatInputContainer = document.getElementById('chat-input-container');
  307. if (chatInputContainer) {
  308. chatInputContainer.scrollTop = chatInputContainer.scrollHeight;
  309. }
  310. await tick();
  311. if (chatInput) {
  312. chatInput.focus();
  313. chatInput.dispatchEvent(new Event('input'));
  314. const words = extractCurlyBraceWords(prompt);
  315. if (words.length > 0) {
  316. const word = words.at(0);
  317. await tick();
  318. if (!($settings?.richTextInput ?? true)) {
  319. // Move scroll to the first word
  320. chatInput.setSelectionRange(word.startIndex, word.endIndex + 1);
  321. chatInput.focus();
  322. const selectionRow =
  323. (word?.startIndex - (word?.startIndex % chatInput.cols)) / chatInput.cols;
  324. const lineHeight = chatInput.clientHeight / chatInput.rows;
  325. chatInput.scrollTop = lineHeight * selectionRow;
  326. }
  327. } else {
  328. chatInput.scrollTop = chatInput.scrollHeight;
  329. }
  330. }
  331. };
  332. let command = '';
  333. export let showCommands = false;
  334. $: showCommands = ['/', '#', '@'].includes(command?.charAt(0)) || '\\#' === command?.slice(0, 2);
  335. let showTools = false;
  336. let loaded = false;
  337. let recording = false;
  338. let isComposing = false;
  339. // Safari has a bug where compositionend is not triggered correctly #16615
  340. // when using the virtual keyboard on iOS.
  341. let compositionEndedAt = -2e8;
  342. const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  343. function inOrNearComposition(event: Event) {
  344. if (isComposing) {
  345. return true;
  346. }
  347. // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
  348. // On Japanese input method editors (IMEs), the Enter key is used to confirm character
  349. // selection. On Safari, when Enter is pressed, compositionend and keydown events are
  350. // emitted. The keydown event triggers newline insertion, which we don't want.
  351. // This method returns true if the keydown event should be ignored.
  352. // We only ignore it once, as pressing Enter a second time *should* insert a newline.
  353. // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.
  354. // This guards against the case where compositionend is triggered without the keyboard
  355. // (e.g. character confirmation may be done with the mouse), and keydown is triggered
  356. // afterwards- we wouldn't want to ignore the keydown event in this case.
  357. if (isSafari && Math.abs(event.timeStamp - compositionEndedAt) < 500) {
  358. compositionEndedAt = -2e8;
  359. return true;
  360. }
  361. return false;
  362. }
  363. let chatInputContainerElement;
  364. let chatInputElement;
  365. let filesInputElement;
  366. let commandsElement;
  367. let inputFiles;
  368. let dragged = false;
  369. let shiftKey = false;
  370. let user = null;
  371. export let placeholder = '';
  372. let visionCapableModels = [];
  373. $: visionCapableModels = (atSelectedModel?.id ? [atSelectedModel.id] : selectedModels).filter(
  374. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.vision ?? true
  375. );
  376. let fileUploadCapableModels = [];
  377. $: fileUploadCapableModels = (atSelectedModel?.id ? [atSelectedModel.id] : selectedModels).filter(
  378. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.file_upload ?? true
  379. );
  380. let webSearchCapableModels = [];
  381. $: webSearchCapableModels = (atSelectedModel?.id ? [atSelectedModel.id] : selectedModels).filter(
  382. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.web_search ?? true
  383. );
  384. let imageGenerationCapableModels = [];
  385. $: imageGenerationCapableModels = (
  386. atSelectedModel?.id ? [atSelectedModel.id] : selectedModels
  387. ).filter(
  388. (model) =>
  389. $models.find((m) => m.id === model)?.info?.meta?.capabilities?.image_generation ?? true
  390. );
  391. let codeInterpreterCapableModels = [];
  392. $: codeInterpreterCapableModels = (
  393. atSelectedModel?.id ? [atSelectedModel.id] : selectedModels
  394. ).filter(
  395. (model) =>
  396. $models.find((m) => m.id === model)?.info?.meta?.capabilities?.code_interpreter ?? true
  397. );
  398. let toggleFilters = [];
  399. $: toggleFilters = (atSelectedModel?.id ? [atSelectedModel.id] : selectedModels)
  400. .map((id) => ($models.find((model) => model.id === id) || {})?.filters ?? [])
  401. .reduce((acc, filters) => acc.filter((f1) => filters.some((f2) => f2.id === f1.id)));
  402. let showToolsButton = false;
  403. $: showToolsButton = toolServers.length + selectedToolIds.length > 0;
  404. let showWebSearchButton = false;
  405. $: showWebSearchButton =
  406. (atSelectedModel?.id ? [atSelectedModel.id] : selectedModels).length ===
  407. webSearchCapableModels.length &&
  408. $config?.features?.enable_web_search &&
  409. ($_user.role === 'admin' || $_user?.permissions?.features?.web_search);
  410. let showImageGenerationButton = false;
  411. $: showImageGenerationButton =
  412. (atSelectedModel?.id ? [atSelectedModel.id] : selectedModels).length ===
  413. imageGenerationCapableModels.length &&
  414. $config?.features?.enable_image_generation &&
  415. ($_user.role === 'admin' || $_user?.permissions?.features?.image_generation);
  416. let showCodeInterpreterButton = false;
  417. $: showCodeInterpreterButton =
  418. (atSelectedModel?.id ? [atSelectedModel.id] : selectedModels).length ===
  419. codeInterpreterCapableModels.length &&
  420. $config?.features?.enable_code_interpreter &&
  421. ($_user.role === 'admin' || $_user?.permissions?.features?.code_interpreter);
  422. const scrollToBottom = () => {
  423. const element = document.getElementById('messages-container');
  424. element.scrollTo({
  425. top: element.scrollHeight,
  426. behavior: 'smooth'
  427. });
  428. };
  429. const screenCaptureHandler = async () => {
  430. try {
  431. // Request screen media
  432. const mediaStream = await navigator.mediaDevices.getDisplayMedia({
  433. video: { cursor: 'never' },
  434. audio: false
  435. });
  436. // Once the user selects a screen, temporarily create a video element
  437. const video = document.createElement('video');
  438. video.srcObject = mediaStream;
  439. // Ensure the video loads without affecting user experience or tab switching
  440. await video.play();
  441. // Set up the canvas to match the video dimensions
  442. const canvas = document.createElement('canvas');
  443. canvas.width = video.videoWidth;
  444. canvas.height = video.videoHeight;
  445. // Grab a single frame from the video stream using the canvas
  446. const context = canvas.getContext('2d');
  447. context.drawImage(video, 0, 0, canvas.width, canvas.height);
  448. // Stop all video tracks (stop screen sharing) after capturing the image
  449. mediaStream.getTracks().forEach((track) => track.stop());
  450. // bring back focus to this current tab, so that the user can see the screen capture
  451. window.focus();
  452. // Convert the canvas to a Base64 image URL
  453. const imageUrl = canvas.toDataURL('image/png');
  454. // Add the captured image to the files array to render it
  455. files = [...files, { type: 'image', url: imageUrl }];
  456. // Clean memory: Clear video srcObject
  457. video.srcObject = null;
  458. } catch (error) {
  459. // Handle any errors (e.g., user cancels screen sharing)
  460. console.error('Error capturing screen:', error);
  461. }
  462. };
  463. const uploadFileHandler = async (file, fullContext: boolean = false) => {
  464. if ($_user?.role !== 'admin' && !($_user?.permissions?.chat?.file_upload ?? true)) {
  465. toast.error($i18n.t('You do not have permission to upload files.'));
  466. return null;
  467. }
  468. if (fileUploadCapableModels.length !== selectedModels.length) {
  469. toast.error($i18n.t('Model(s) do not support file upload'));
  470. return null;
  471. }
  472. const tempItemId = uuidv4();
  473. const fileItem = {
  474. type: 'file',
  475. file: '',
  476. id: null,
  477. url: '',
  478. name: file.name,
  479. collection_name: '',
  480. status: 'uploading',
  481. size: file.size,
  482. error: '',
  483. itemId: tempItemId,
  484. ...(fullContext ? { context: 'full' } : {})
  485. };
  486. if (fileItem.size == 0) {
  487. toast.error($i18n.t('You cannot upload an empty file.'));
  488. return null;
  489. }
  490. files = [...files, fileItem];
  491. if (!$temporaryChatEnabled) {
  492. try {
  493. // If the file is an audio file, provide the language for STT.
  494. let metadata = null;
  495. if (
  496. (file.type.startsWith('audio/') || file.type.startsWith('video/')) &&
  497. $settings?.audio?.stt?.language
  498. ) {
  499. metadata = {
  500. language: $settings?.audio?.stt?.language
  501. };
  502. }
  503. // During the file upload, file content is automatically extracted.
  504. const uploadedFile = await uploadFile(localStorage.token, file, metadata);
  505. if (uploadedFile) {
  506. console.log('File upload completed:', {
  507. id: uploadedFile.id,
  508. name: fileItem.name,
  509. collection: uploadedFile?.meta?.collection_name
  510. });
  511. if (uploadedFile.error) {
  512. console.warn('File upload warning:', uploadedFile.error);
  513. toast.warning(uploadedFile.error);
  514. }
  515. fileItem.status = 'uploaded';
  516. fileItem.file = uploadedFile;
  517. fileItem.id = uploadedFile.id;
  518. fileItem.collection_name =
  519. uploadedFile?.meta?.collection_name || uploadedFile?.collection_name;
  520. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  521. files = files;
  522. } else {
  523. files = files.filter((item) => item?.itemId !== tempItemId);
  524. }
  525. } catch (e) {
  526. toast.error(`${e}`);
  527. files = files.filter((item) => item?.itemId !== tempItemId);
  528. }
  529. } else {
  530. // If temporary chat is enabled, we just add the file to the list without uploading it.
  531. const content = await extractContentFromFile(file).catch((error) => {
  532. toast.error(
  533. $i18n.t('Failed to extract content from the file: {{error}}', { error: error })
  534. );
  535. return null;
  536. });
  537. if (content === null) {
  538. toast.error($i18n.t('Failed to extract content from the file.'));
  539. files = files.filter((item) => item?.itemId !== tempItemId);
  540. return null;
  541. } else {
  542. console.log('Extracted content from file:', {
  543. name: file.name,
  544. size: file.size,
  545. content: content
  546. });
  547. fileItem.status = 'uploaded';
  548. fileItem.type = 'text';
  549. fileItem.content = content;
  550. fileItem.id = uuidv4(); // Temporary ID for the file
  551. files = files;
  552. }
  553. }
  554. };
  555. const inputFilesHandler = async (inputFiles) => {
  556. console.log('Input files handler called with:', inputFiles);
  557. if (
  558. ($config?.file?.max_count ?? null) !== null &&
  559. files.length + inputFiles.length > $config?.file?.max_count
  560. ) {
  561. toast.error(
  562. $i18n.t(`You can only chat with a maximum of {{maxCount}} file(s) at a time.`, {
  563. maxCount: $config?.file?.max_count
  564. })
  565. );
  566. return;
  567. }
  568. inputFiles.forEach(async (file) => {
  569. console.log('Processing file:', {
  570. name: file.name,
  571. type: file.type,
  572. size: file.size,
  573. extension: file.name.split('.').at(-1)
  574. });
  575. if (
  576. ($config?.file?.max_size ?? null) !== null &&
  577. file.size > ($config?.file?.max_size ?? 0) * 1024 * 1024
  578. ) {
  579. console.log('File exceeds max size limit:', {
  580. fileSize: file.size,
  581. maxSize: ($config?.file?.max_size ?? 0) * 1024 * 1024
  582. });
  583. toast.error(
  584. $i18n.t(`File size should not exceed {{maxSize}} MB.`, {
  585. maxSize: $config?.file?.max_size
  586. })
  587. );
  588. return;
  589. }
  590. if (file['type'].startsWith('image/')) {
  591. if (visionCapableModels.length === 0) {
  592. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  593. return;
  594. }
  595. const compressImageHandler = async (imageUrl, settings = {}, config = {}) => {
  596. // Quick shortcut so we don’t do unnecessary work.
  597. const settingsCompression = settings?.imageCompression ?? false;
  598. const configWidth = config?.file?.image_compression?.width ?? null;
  599. const configHeight = config?.file?.image_compression?.height ?? null;
  600. // If neither settings nor config wants compression, return original URL.
  601. if (!settingsCompression && !configWidth && !configHeight) {
  602. return imageUrl;
  603. }
  604. // Default to null (no compression unless set)
  605. let width = null;
  606. let height = null;
  607. // If user/settings want compression, pick their preferred size.
  608. if (settingsCompression) {
  609. width = settings?.imageCompressionSize?.width ?? null;
  610. height = settings?.imageCompressionSize?.height ?? null;
  611. }
  612. // Apply config limits as an upper bound if any
  613. if (configWidth && (width === null || width > configWidth)) {
  614. width = configWidth;
  615. }
  616. if (configHeight && (height === null || height > configHeight)) {
  617. height = configHeight;
  618. }
  619. // Do the compression if required
  620. if (width || height) {
  621. return await compressImage(imageUrl, width, height);
  622. }
  623. return imageUrl;
  624. };
  625. let reader = new FileReader();
  626. reader.onload = async (event) => {
  627. let imageUrl = event.target.result;
  628. imageUrl = await compressImageHandler(imageUrl, $settings, $config);
  629. files = [
  630. ...files,
  631. {
  632. type: 'image',
  633. url: `${imageUrl}`
  634. }
  635. ];
  636. };
  637. reader.readAsDataURL(
  638. file['type'] === 'image/heic'
  639. ? await heic2any({ blob: file, toType: 'image/jpeg' })
  640. : file
  641. );
  642. } else {
  643. uploadFileHandler(file);
  644. }
  645. });
  646. };
  647. const onDragOver = (e) => {
  648. e.preventDefault();
  649. // Check if a file is being dragged.
  650. if (e.dataTransfer?.types?.includes('Files')) {
  651. dragged = true;
  652. } else {
  653. dragged = false;
  654. }
  655. };
  656. const onDragLeave = () => {
  657. dragged = false;
  658. };
  659. const onDrop = async (e) => {
  660. e.preventDefault();
  661. console.log(e);
  662. if (e.dataTransfer?.files) {
  663. const inputFiles = Array.from(e.dataTransfer?.files);
  664. if (inputFiles && inputFiles.length > 0) {
  665. console.log(inputFiles);
  666. inputFilesHandler(inputFiles);
  667. }
  668. }
  669. dragged = false;
  670. };
  671. const onKeyDown = (e) => {
  672. if (e.key === 'Shift') {
  673. shiftKey = true;
  674. }
  675. if (e.key === 'Escape') {
  676. console.log('Escape');
  677. dragged = false;
  678. }
  679. };
  680. const onKeyUp = (e) => {
  681. if (e.key === 'Shift') {
  682. shiftKey = false;
  683. }
  684. };
  685. const onFocus = () => {};
  686. const onBlur = () => {
  687. shiftKey = false;
  688. };
  689. onMount(async () => {
  690. loaded = true;
  691. window.setTimeout(() => {
  692. const chatInput = document.getElementById('chat-input');
  693. chatInput?.focus();
  694. }, 0);
  695. window.addEventListener('keydown', onKeyDown);
  696. window.addEventListener('keyup', onKeyUp);
  697. window.addEventListener('focus', onFocus);
  698. window.addEventListener('blur', onBlur);
  699. await tick();
  700. const dropzoneElement = document.getElementById('chat-container');
  701. dropzoneElement?.addEventListener('dragover', onDragOver);
  702. dropzoneElement?.addEventListener('drop', onDrop);
  703. dropzoneElement?.addEventListener('dragleave', onDragLeave);
  704. });
  705. onDestroy(() => {
  706. console.log('destroy');
  707. window.removeEventListener('keydown', onKeyDown);
  708. window.removeEventListener('keyup', onKeyUp);
  709. window.removeEventListener('focus', onFocus);
  710. window.removeEventListener('blur', onBlur);
  711. const dropzoneElement = document.getElementById('chat-container');
  712. if (dropzoneElement) {
  713. dropzoneElement?.removeEventListener('dragover', onDragOver);
  714. dropzoneElement?.removeEventListener('drop', onDrop);
  715. dropzoneElement?.removeEventListener('dragleave', onDragLeave);
  716. }
  717. });
  718. </script>
  719. <FilesOverlay show={dragged} />
  720. <ToolServersModal bind:show={showTools} {selectedToolIds} />
  721. <InputVariablesModal
  722. bind:show={showInputVariablesModal}
  723. variables={inputVariables}
  724. onSave={(variableValues) => {
  725. inputVariableValues = { ...inputVariableValues, ...variableValues };
  726. replaceVariables(inputVariableValues);
  727. }}
  728. />
  729. {#if loaded}
  730. <div class="w-full font-primary">
  731. <div class=" mx-auto inset-x-0 bg-transparent flex justify-center">
  732. <div
  733. class="flex flex-col px-3 {($settings?.widescreenMode ?? null)
  734. ? 'max-w-full'
  735. : 'max-w-6xl'} w-full"
  736. >
  737. <div class="relative">
  738. {#if autoScroll === false && history?.currentId}
  739. <div
  740. class=" absolute -top-12 left-0 right-0 flex justify-center z-30 pointer-events-none"
  741. >
  742. <button
  743. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full pointer-events-auto"
  744. on:click={() => {
  745. autoScroll = true;
  746. scrollToBottom();
  747. }}
  748. >
  749. <svg
  750. xmlns="http://www.w3.org/2000/svg"
  751. viewBox="0 0 20 20"
  752. fill="currentColor"
  753. class="w-5 h-5"
  754. >
  755. <path
  756. fill-rule="evenodd"
  757. 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"
  758. clip-rule="evenodd"
  759. />
  760. </svg>
  761. </button>
  762. </div>
  763. {/if}
  764. </div>
  765. <div class="w-full relative">
  766. {#if atSelectedModel !== undefined}
  767. <div
  768. 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"
  769. >
  770. <div class="flex items-center justify-between w-full">
  771. <div class="pl-[1px] flex items-center gap-2 text-sm dark:text-gray-500">
  772. <img
  773. crossorigin="anonymous"
  774. alt="model profile"
  775. class="size-3.5 max-w-[28px] object-cover rounded-full"
  776. src={$models.find((model) => model.id === atSelectedModel.id)?.info?.meta
  777. ?.profile_image_url ??
  778. ($i18n.language === 'dg-DG'
  779. ? `${WEBUI_BASE_URL}/doge.png`
  780. : `${WEBUI_BASE_URL}/static/favicon.png`)}
  781. />
  782. <div class="translate-y-[0.5px]">
  783. {$i18n.t('Talk to model')}:
  784. <span class=" font-medium">{atSelectedModel.name}</span>
  785. </div>
  786. </div>
  787. <div>
  788. <button
  789. class="flex items-center dark:text-gray-500"
  790. on:click={() => {
  791. atSelectedModel = undefined;
  792. }}
  793. >
  794. <XMark />
  795. </button>
  796. </div>
  797. </div>
  798. </div>
  799. {/if}
  800. <Commands
  801. bind:this={commandsElement}
  802. bind:files
  803. show={showCommands}
  804. {command}
  805. insertTextHandler={insertTextAtCursor}
  806. onUpload={(e) => {
  807. const { type, data } = e;
  808. if (type === 'file') {
  809. if (files.find((f) => f.id === data.id)) {
  810. return;
  811. }
  812. files = [
  813. ...files,
  814. {
  815. ...data,
  816. status: 'processed'
  817. }
  818. ];
  819. } else {
  820. dispatch('upload', e);
  821. }
  822. }}
  823. onSelect={(e) => {
  824. const { type, data } = e;
  825. if (type === 'model') {
  826. atSelectedModel = data;
  827. }
  828. document.getElementById('chat-input')?.focus();
  829. }}
  830. />
  831. </div>
  832. </div>
  833. </div>
  834. <div class="bg-transparent">
  835. <div
  836. class="{($settings?.widescreenMode ?? null)
  837. ? 'max-w-full'
  838. : 'max-w-6xl'} px-2.5 mx-auto inset-x-0"
  839. >
  840. <div class="">
  841. <input
  842. bind:this={filesInputElement}
  843. bind:files={inputFiles}
  844. type="file"
  845. hidden
  846. multiple
  847. on:change={async () => {
  848. if (inputFiles && inputFiles.length > 0) {
  849. const _inputFiles = Array.from(inputFiles);
  850. inputFilesHandler(_inputFiles);
  851. } else {
  852. toast.error($i18n.t(`File not found.`));
  853. }
  854. filesInputElement.value = '';
  855. }}
  856. />
  857. {#if recording}
  858. <VoiceRecording
  859. bind:recording
  860. onCancel={async () => {
  861. recording = false;
  862. await tick();
  863. document.getElementById('chat-input')?.focus();
  864. }}
  865. onConfirm={async (data) => {
  866. const { text, filename } = data;
  867. recording = false;
  868. await tick();
  869. insertTextAtCursor(text);
  870. await tick();
  871. document.getElementById('chat-input')?.focus();
  872. if ($settings?.speechAutoSend ?? false) {
  873. dispatch('submit', prompt);
  874. }
  875. }}
  876. />
  877. {:else}
  878. <form
  879. class="w-full flex flex-col gap-1.5"
  880. on:submit|preventDefault={() => {
  881. // check if selectedModels support image input
  882. dispatch('submit', prompt);
  883. }}
  884. >
  885. <div
  886. 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"
  887. dir={$settings?.chatDirection ?? 'auto'}
  888. >
  889. {#if files.length > 0}
  890. <div class="mx-2 mt-2.5 -mb-1 flex items-center flex-wrap gap-2">
  891. {#each files as file, fileIdx}
  892. {#if file.type === 'image'}
  893. <div class=" relative group">
  894. <div class="relative flex items-center">
  895. <Image
  896. src={file.url}
  897. alt=""
  898. imageClassName=" size-14 rounded-xl object-cover"
  899. />
  900. {#if atSelectedModel ? visionCapableModels.length === 0 : selectedModels.length !== visionCapableModels.length}
  901. <Tooltip
  902. className=" absolute top-1 left-1"
  903. content={$i18n.t('{{ models }}', {
  904. models: [
  905. ...(atSelectedModel ? [atSelectedModel] : selectedModels)
  906. ]
  907. .filter((id) => !visionCapableModels.includes(id))
  908. .join(', ')
  909. })}
  910. >
  911. <svg
  912. xmlns="http://www.w3.org/2000/svg"
  913. viewBox="0 0 24 24"
  914. fill="currentColor"
  915. aria-hidden="true"
  916. class="size-4 fill-yellow-300"
  917. >
  918. <path
  919. fill-rule="evenodd"
  920. 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"
  921. clip-rule="evenodd"
  922. />
  923. </svg>
  924. </Tooltip>
  925. {/if}
  926. </div>
  927. <div class=" absolute -top-1 -right-1">
  928. <button
  929. class=" bg-white text-black border border-white rounded-full {($settings?.highContrastMode ??
  930. false)
  931. ? ''
  932. : 'outline-hidden focus:outline-hidden group-hover:visible invisible transition'}"
  933. type="button"
  934. aria-label={$i18n.t('Remove file')}
  935. on:click={() => {
  936. files.splice(fileIdx, 1);
  937. files = files;
  938. }}
  939. >
  940. <svg
  941. xmlns="http://www.w3.org/2000/svg"
  942. viewBox="0 0 20 20"
  943. fill="currentColor"
  944. aria-hidden="true"
  945. class="size-4"
  946. >
  947. <path
  948. 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"
  949. />
  950. </svg>
  951. </button>
  952. </div>
  953. </div>
  954. {:else}
  955. <FileItem
  956. item={file}
  957. name={file.name}
  958. type={file.type}
  959. size={file?.size}
  960. loading={file.status === 'uploading'}
  961. dismissible={true}
  962. edit={true}
  963. modal={['file', 'collection'].includes(file?.type)}
  964. on:dismiss={async () => {
  965. // Remove from UI state
  966. files.splice(fileIdx, 1);
  967. files = files;
  968. }}
  969. on:click={() => {
  970. console.log(file);
  971. }}
  972. />
  973. {/if}
  974. {/each}
  975. </div>
  976. {/if}
  977. <div class="px-2.5">
  978. {#if $settings?.richTextInput ?? true}
  979. <div
  980. class="scrollbar-hidden rtl:text-right ltr:text-left bg-transparent dark:text-gray-100 outline-hidden w-full pt-2.5 pb-[5px] px-1 resize-none h-fit max-h-80 overflow-auto"
  981. id="chat-input-container"
  982. >
  983. {#key $settings?.showFormattingToolbar ?? false}
  984. <RichTextInput
  985. bind:this={chatInputElement}
  986. id="chat-input"
  987. onChange={(e) => {
  988. prompt = e.md;
  989. command = getCommand();
  990. }}
  991. json={true}
  992. messageInput={true}
  993. showFormattingToolbar={$settings?.showFormattingToolbar ?? false}
  994. floatingMenuPlacement={'top-start'}
  995. insertPromptAsRichText={$settings?.insertPromptAsRichText ?? false}
  996. shiftEnter={!($settings?.ctrlEnterToSend ?? false) &&
  997. (!$mobile ||
  998. !(
  999. 'ontouchstart' in window ||
  1000. navigator.maxTouchPoints > 0 ||
  1001. navigator.msMaxTouchPoints > 0
  1002. ))}
  1003. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  1004. largeTextAsFile={($settings?.largeTextAsFile ?? false) && !shiftKey}
  1005. autocomplete={$config?.features?.enable_autocomplete_generation &&
  1006. ($settings?.promptAutocomplete ?? false)}
  1007. generateAutoCompletion={async (text) => {
  1008. if (selectedModelIds.length === 0 || !selectedModelIds.at(0)) {
  1009. toast.error($i18n.t('Please select a model first.'));
  1010. }
  1011. const res = await generateAutoCompletion(
  1012. localStorage.token,
  1013. selectedModelIds.at(0),
  1014. text,
  1015. history?.currentId
  1016. ? createMessagesList(history, history.currentId)
  1017. : null
  1018. ).catch((error) => {
  1019. console.log(error);
  1020. return null;
  1021. });
  1022. console.log(res);
  1023. return res;
  1024. }}
  1025. oncompositionstart={() => (isComposing = true)}
  1026. oncompositionend={(e) => {
  1027. compositionEndedAt = e.timeStamp;
  1028. isComposing = false;
  1029. }}
  1030. on:keydown={async (e) => {
  1031. e = e.detail.event;
  1032. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  1033. const commandsContainerElement =
  1034. document.getElementById('commands-container');
  1035. if (e.key === 'Escape') {
  1036. stopResponse();
  1037. }
  1038. // Command/Ctrl + Shift + Enter to submit a message pair
  1039. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  1040. e.preventDefault();
  1041. createMessagePair(prompt);
  1042. }
  1043. // Check if Ctrl + R is pressed
  1044. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  1045. e.preventDefault();
  1046. console.log('regenerate');
  1047. const regenerateButton = [
  1048. ...document.getElementsByClassName('regenerate-response-button')
  1049. ]?.at(-1);
  1050. regenerateButton?.click();
  1051. }
  1052. if (prompt === '' && e.key == 'ArrowUp') {
  1053. e.preventDefault();
  1054. const userMessageElement = [
  1055. ...document.getElementsByClassName('user-message')
  1056. ]?.at(-1);
  1057. if (userMessageElement) {
  1058. userMessageElement.scrollIntoView({ block: 'center' });
  1059. const editButton = [
  1060. ...document.getElementsByClassName('edit-user-message-button')
  1061. ]?.at(-1);
  1062. editButton?.click();
  1063. }
  1064. }
  1065. if (commandsContainerElement) {
  1066. if (commandsContainerElement && e.key === 'ArrowUp') {
  1067. e.preventDefault();
  1068. commandsElement.selectUp();
  1069. const commandOptionButton = [
  1070. ...document.getElementsByClassName(
  1071. 'selected-command-option-button'
  1072. )
  1073. ]?.at(-1);
  1074. commandOptionButton.scrollIntoView({ block: 'center' });
  1075. }
  1076. if (commandsContainerElement && e.key === 'ArrowDown') {
  1077. e.preventDefault();
  1078. commandsElement.selectDown();
  1079. const commandOptionButton = [
  1080. ...document.getElementsByClassName(
  1081. 'selected-command-option-button'
  1082. )
  1083. ]?.at(-1);
  1084. commandOptionButton.scrollIntoView({ block: 'center' });
  1085. }
  1086. if (commandsContainerElement && e.key === 'Tab') {
  1087. e.preventDefault();
  1088. const commandOptionButton = [
  1089. ...document.getElementsByClassName(
  1090. 'selected-command-option-button'
  1091. )
  1092. ]?.at(-1);
  1093. commandOptionButton?.click();
  1094. }
  1095. if (commandsContainerElement && e.key === 'Enter') {
  1096. e.preventDefault();
  1097. const commandOptionButton = [
  1098. ...document.getElementsByClassName(
  1099. 'selected-command-option-button'
  1100. )
  1101. ]?.at(-1);
  1102. if (commandOptionButton) {
  1103. commandOptionButton?.click();
  1104. } else {
  1105. document.getElementById('send-message-button')?.click();
  1106. }
  1107. }
  1108. } else {
  1109. if (
  1110. !$mobile ||
  1111. !(
  1112. 'ontouchstart' in window ||
  1113. navigator.maxTouchPoints > 0 ||
  1114. navigator.msMaxTouchPoints > 0
  1115. )
  1116. ) {
  1117. if (inOrNearComposition(e)) {
  1118. return;
  1119. }
  1120. // Uses keyCode '13' for Enter key for chinese/japanese keyboards.
  1121. //
  1122. // Depending on the user's settings, it will send the message
  1123. // either when Enter is pressed or when Ctrl+Enter is pressed.
  1124. const enterPressed =
  1125. ($settings?.ctrlEnterToSend ?? false)
  1126. ? (e.key === 'Enter' || e.keyCode === 13) && isCtrlPressed
  1127. : (e.key === 'Enter' || e.keyCode === 13) && !e.shiftKey;
  1128. if (enterPressed) {
  1129. e.preventDefault();
  1130. if (prompt !== '' || files.length > 0) {
  1131. dispatch('submit', prompt);
  1132. }
  1133. }
  1134. }
  1135. }
  1136. if (e.key === 'Escape') {
  1137. console.log('Escape');
  1138. atSelectedModel = undefined;
  1139. selectedToolIds = [];
  1140. selectedFilterIds = [];
  1141. webSearchEnabled = false;
  1142. imageGenerationEnabled = false;
  1143. codeInterpreterEnabled = false;
  1144. }
  1145. }}
  1146. on:paste={async (e) => {
  1147. e = e.detail.event;
  1148. console.log(e);
  1149. const clipboardData = e.clipboardData || window.clipboardData;
  1150. if (clipboardData && clipboardData.items) {
  1151. for (const item of clipboardData.items) {
  1152. if (item.type.indexOf('image') !== -1) {
  1153. const blob = item.getAsFile();
  1154. const reader = new FileReader();
  1155. reader.onload = function (e) {
  1156. files = [
  1157. ...files,
  1158. {
  1159. type: 'image',
  1160. url: `${e.target.result}`
  1161. }
  1162. ];
  1163. };
  1164. reader.readAsDataURL(blob);
  1165. } else if (item?.kind === 'file') {
  1166. const file = item.getAsFile();
  1167. if (file) {
  1168. const _files = [file];
  1169. await inputFilesHandler(_files);
  1170. e.preventDefault();
  1171. }
  1172. } else if (item.type === 'text/plain') {
  1173. if (($settings?.largeTextAsFile ?? false) && !shiftKey) {
  1174. const text = clipboardData.getData('text/plain');
  1175. if (text.length > PASTED_TEXT_CHARACTER_LIMIT) {
  1176. e.preventDefault();
  1177. const blob = new Blob([text], { type: 'text/plain' });
  1178. const file = new File(
  1179. [blob],
  1180. `Pasted_Text_${Date.now()}.txt`,
  1181. {
  1182. type: 'text/plain'
  1183. }
  1184. );
  1185. await uploadFileHandler(file, true);
  1186. }
  1187. }
  1188. }
  1189. }
  1190. }
  1191. }}
  1192. />
  1193. {/key}
  1194. </div>
  1195. {:else}
  1196. <textarea
  1197. id="chat-input"
  1198. dir={$settings?.chatDirection ?? 'auto'}
  1199. bind:this={chatInputElement}
  1200. class="scrollbar-hidden bg-transparent dark:text-gray-200 outline-hidden w-full pt-4 pb-1 px-1 resize-none"
  1201. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  1202. bind:value={prompt}
  1203. on:input={() => {
  1204. command = getCommand();
  1205. }}
  1206. on:click={() => {
  1207. command = getCommand();
  1208. }}
  1209. on:compositionstart={() => (isComposing = true)}
  1210. on:compositionend={(e) => {
  1211. compositionEndedAt = e.timeStamp;
  1212. isComposing = false;
  1213. }}
  1214. on:keydown={async (e) => {
  1215. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  1216. const commandsContainerElement =
  1217. document.getElementById('commands-container');
  1218. if (e.key === 'Escape') {
  1219. stopResponse();
  1220. }
  1221. // Command/Ctrl + Shift + Enter to submit a message pair
  1222. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  1223. e.preventDefault();
  1224. createMessagePair(prompt);
  1225. }
  1226. // Check if Ctrl + R is pressed
  1227. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  1228. e.preventDefault();
  1229. console.log('regenerate');
  1230. const regenerateButton = [
  1231. ...document.getElementsByClassName('regenerate-response-button')
  1232. ]?.at(-1);
  1233. regenerateButton?.click();
  1234. }
  1235. if (prompt === '' && e.key == 'ArrowUp') {
  1236. e.preventDefault();
  1237. const userMessageElement = [
  1238. ...document.getElementsByClassName('user-message')
  1239. ]?.at(-1);
  1240. const editButton = [
  1241. ...document.getElementsByClassName('edit-user-message-button')
  1242. ]?.at(-1);
  1243. console.log(userMessageElement);
  1244. userMessageElement?.scrollIntoView({ block: 'center' });
  1245. editButton?.click();
  1246. }
  1247. if (commandsContainerElement) {
  1248. if (commandsContainerElement && e.key === 'ArrowUp') {
  1249. e.preventDefault();
  1250. commandsElement.selectUp();
  1251. const container = document.getElementById('command-options-container');
  1252. const commandOptionButton = [
  1253. ...document.getElementsByClassName('selected-command-option-button')
  1254. ]?.at(-1);
  1255. if (commandOptionButton && container) {
  1256. const elTop = commandOptionButton.offsetTop;
  1257. const elHeight = commandOptionButton.offsetHeight;
  1258. const containerHeight = container.clientHeight;
  1259. // Center the selected button in the container
  1260. container.scrollTop = elTop - containerHeight / 2 + elHeight / 2;
  1261. }
  1262. }
  1263. if (commandsContainerElement && e.key === 'ArrowDown') {
  1264. e.preventDefault();
  1265. commandsElement.selectDown();
  1266. const container = document.getElementById('command-options-container');
  1267. const commandOptionButton = [
  1268. ...document.getElementsByClassName('selected-command-option-button')
  1269. ]?.at(-1);
  1270. if (commandOptionButton && container) {
  1271. const elTop = commandOptionButton.offsetTop;
  1272. const elHeight = commandOptionButton.offsetHeight;
  1273. const containerHeight = container.clientHeight;
  1274. // Center the selected button in the container
  1275. container.scrollTop = elTop - containerHeight / 2 + elHeight / 2;
  1276. }
  1277. }
  1278. if (commandsContainerElement && e.key === 'Enter') {
  1279. e.preventDefault();
  1280. const commandOptionButton = [
  1281. ...document.getElementsByClassName('selected-command-option-button')
  1282. ]?.at(-1);
  1283. if (e.shiftKey) {
  1284. prompt = `${prompt}\n`;
  1285. } else if (commandOptionButton) {
  1286. commandOptionButton?.click();
  1287. } else {
  1288. document.getElementById('send-message-button')?.click();
  1289. }
  1290. }
  1291. if (commandsContainerElement && e.key === 'Tab') {
  1292. e.preventDefault();
  1293. const commandOptionButton = [
  1294. ...document.getElementsByClassName('selected-command-option-button')
  1295. ]?.at(-1);
  1296. commandOptionButton?.click();
  1297. }
  1298. } else {
  1299. if (
  1300. !$mobile ||
  1301. !(
  1302. 'ontouchstart' in window ||
  1303. navigator.maxTouchPoints > 0 ||
  1304. navigator.msMaxTouchPoints > 0
  1305. )
  1306. ) {
  1307. if (inOrNearComposition(e)) {
  1308. return;
  1309. }
  1310. // Prevent Enter key from creating a new line
  1311. const isCtrlPressed = e.ctrlKey || e.metaKey;
  1312. const enterPressed =
  1313. ($settings?.ctrlEnterToSend ?? false)
  1314. ? (e.key === 'Enter' || e.keyCode === 13) && isCtrlPressed
  1315. : (e.key === 'Enter' || e.keyCode === 13) && !e.shiftKey;
  1316. if (enterPressed) {
  1317. e.preventDefault();
  1318. }
  1319. // Submit the prompt when Enter key is pressed
  1320. if ((prompt !== '' || files.length > 0) && enterPressed) {
  1321. dispatch('submit', prompt);
  1322. }
  1323. }
  1324. }
  1325. if (e.key === 'Tab') {
  1326. const words = extractCurlyBraceWords(prompt);
  1327. if (words.length > 0) {
  1328. const word = words.at(0);
  1329. if (word && e.target instanceof HTMLTextAreaElement) {
  1330. // Prevent default tab behavior
  1331. e.preventDefault();
  1332. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  1333. e.target.focus();
  1334. const selectionRow =
  1335. (word?.startIndex - (word?.startIndex % e.target.cols)) /
  1336. e.target.cols;
  1337. const lineHeight = e.target.clientHeight / e.target.rows;
  1338. e.target.scrollTop = lineHeight * selectionRow;
  1339. }
  1340. }
  1341. e.target.style.height = '';
  1342. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  1343. }
  1344. if (e.key === 'Escape') {
  1345. console.log('Escape');
  1346. atSelectedModel = undefined;
  1347. selectedToolIds = [];
  1348. selectedFilterIds = [];
  1349. webSearchEnabled = false;
  1350. imageGenerationEnabled = false;
  1351. codeInterpreterEnabled = false;
  1352. }
  1353. }}
  1354. rows="1"
  1355. on:input={async (e) => {
  1356. e.target.style.height = '';
  1357. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  1358. }}
  1359. on:focus={async (e) => {
  1360. e.target.style.height = '';
  1361. e.target.style.height = Math.min(e.target.scrollHeight, 320) + 'px';
  1362. }}
  1363. on:paste={async (e) => {
  1364. const clipboardData = e.clipboardData || window.clipboardData;
  1365. if (clipboardData && clipboardData.items) {
  1366. for (const item of clipboardData.items) {
  1367. console.log(item);
  1368. if (item.type.indexOf('image') !== -1) {
  1369. const blob = item.getAsFile();
  1370. const reader = new FileReader();
  1371. reader.onload = function (e) {
  1372. files = [
  1373. ...files,
  1374. {
  1375. type: 'image',
  1376. url: `${e.target.result}`
  1377. }
  1378. ];
  1379. };
  1380. reader.readAsDataURL(blob);
  1381. } else if (item?.kind === 'file') {
  1382. const file = item.getAsFile();
  1383. if (file) {
  1384. const _files = [file];
  1385. await inputFilesHandler(_files);
  1386. e.preventDefault();
  1387. }
  1388. } else if (item.type === 'text/plain') {
  1389. if (($settings?.largeTextAsFile ?? false) && !shiftKey) {
  1390. const text = clipboardData.getData('text/plain');
  1391. if (text.length > PASTED_TEXT_CHARACTER_LIMIT) {
  1392. e.preventDefault();
  1393. const blob = new Blob([text], { type: 'text/plain' });
  1394. const file = new File([blob], `Pasted_Text_${Date.now()}.txt`, {
  1395. type: 'text/plain'
  1396. });
  1397. await uploadFileHandler(file, true);
  1398. }
  1399. }
  1400. }
  1401. }
  1402. }
  1403. }}
  1404. />
  1405. {/if}
  1406. </div>
  1407. <div class=" flex justify-between mt-0.5 mb-2.5 mx-0.5 max-w-full" dir="ltr">
  1408. <div class="ml-1 self-end flex items-center flex-1 max-w-[80%]">
  1409. <InputMenu
  1410. bind:selectedToolIds
  1411. selectedModels={atSelectedModel ? [atSelectedModel.id] : selectedModels}
  1412. {fileUploadCapableModels}
  1413. {screenCaptureHandler}
  1414. {inputFilesHandler}
  1415. uploadFilesHandler={() => {
  1416. filesInputElement.click();
  1417. }}
  1418. uploadGoogleDriveHandler={async () => {
  1419. try {
  1420. const fileData = await createPicker();
  1421. if (fileData) {
  1422. const file = new File([fileData.blob], fileData.name, {
  1423. type: fileData.blob.type
  1424. });
  1425. await uploadFileHandler(file);
  1426. } else {
  1427. console.log('No file was selected from Google Drive');
  1428. }
  1429. } catch (error) {
  1430. console.error('Google Drive Error:', error);
  1431. toast.error(
  1432. $i18n.t('Error accessing Google Drive: {{error}}', {
  1433. error: error.message
  1434. })
  1435. );
  1436. }
  1437. }}
  1438. uploadOneDriveHandler={async (authorityType) => {
  1439. try {
  1440. const fileData = await pickAndDownloadFile(authorityType);
  1441. if (fileData) {
  1442. const file = new File([fileData.blob], fileData.name, {
  1443. type: fileData.blob.type || 'application/octet-stream'
  1444. });
  1445. await uploadFileHandler(file);
  1446. } else {
  1447. console.log('No file was selected from OneDrive');
  1448. }
  1449. } catch (error) {
  1450. console.error('OneDrive Error:', error);
  1451. }
  1452. }}
  1453. onClose={async () => {
  1454. await tick();
  1455. const chatInput = document.getElementById('chat-input');
  1456. chatInput?.focus();
  1457. }}
  1458. >
  1459. <div
  1460. class="bg-transparent hover:bg-gray-100 text-gray-800 dark:text-white dark:hover:bg-gray-800 rounded-full p-1.5 outline-hidden focus:outline-hidden"
  1461. >
  1462. <svg
  1463. xmlns="http://www.w3.org/2000/svg"
  1464. viewBox="0 0 20 20"
  1465. aria-hidden="true"
  1466. fill="currentColor"
  1467. class="size-5"
  1468. >
  1469. <path
  1470. 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"
  1471. />
  1472. </svg>
  1473. </div>
  1474. </InputMenu>
  1475. {#if $_user && (showToolsButton || (toggleFilters && toggleFilters.length > 0) || showWebSearchButton || showImageGenerationButton || showCodeInterpreterButton)}
  1476. <div
  1477. class="flex self-center w-[1px] h-4 mx-1.5 bg-gray-50 dark:bg-gray-800"
  1478. />
  1479. <div class="flex gap-1 items-center overflow-x-auto scrollbar-none flex-1">
  1480. {#if showToolsButton}
  1481. <Tooltip
  1482. content={$i18n.t('{{COUNT}} Available Tools', {
  1483. COUNT: toolServers.length + selectedToolIds.length
  1484. })}
  1485. >
  1486. <button
  1487. 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"
  1488. aria-label="Available Tools"
  1489. type="button"
  1490. on:click={() => {
  1491. showTools = !showTools;
  1492. }}
  1493. >
  1494. <Wrench className="size-4" strokeWidth="1.75" />
  1495. <span class="text-sm font-medium text-gray-600 dark:text-gray-300">
  1496. {toolServers.length + selectedToolIds.length}
  1497. </span>
  1498. </button>
  1499. </Tooltip>
  1500. {/if}
  1501. {#each toggleFilters as filter, filterIdx (filter.id)}
  1502. <Tooltip content={filter?.description} placement="top">
  1503. <button
  1504. on:click|preventDefault={() => {
  1505. if (selectedFilterIds.includes(filter.id)) {
  1506. selectedFilterIds = selectedFilterIds.filter(
  1507. (id) => id !== filter.id
  1508. );
  1509. } else {
  1510. selectedFilterIds = [...selectedFilterIds, filter.id];
  1511. }
  1512. }}
  1513. type="button"
  1514. class="px-2 @xl:px-2.5 py-2 flex gap-1.5 items-center text-sm rounded-full transition-colors duration-300 focus:outline-hidden max-w-full overflow-hidden hover:bg-gray-50 dark:hover:bg-gray-800 {selectedFilterIds.includes(
  1515. filter.id
  1516. )
  1517. ? 'text-sky-500 dark:text-sky-300 bg-sky-50 dark:bg-sky-200/5'
  1518. : 'bg-transparent text-gray-600 dark:text-gray-300 '} capitalize"
  1519. >
  1520. {#if filter?.icon}
  1521. <div class="size-4 items-center flex justify-center">
  1522. <img
  1523. src={filter.icon}
  1524. class="size-3.5 {filter.icon.includes('svg')
  1525. ? 'dark:invert-[80%]'
  1526. : ''}"
  1527. style="fill: currentColor;"
  1528. alt={filter.name}
  1529. />
  1530. </div>
  1531. {:else}
  1532. <Sparkles className="size-4" strokeWidth="1.75" />
  1533. {/if}
  1534. <span
  1535. class="hidden @xl:block whitespace-nowrap text-ellipsis leading-none normal-case pr-0.5"
  1536. >{filter?.name}</span
  1537. >
  1538. </button>
  1539. </Tooltip>
  1540. {/each}
  1541. {#if showWebSearchButton}
  1542. <Tooltip content={$i18n.t('Search the internet')} placement="top">
  1543. <button
  1544. on:click|preventDefault={() => (webSearchEnabled = !webSearchEnabled)}
  1545. type="button"
  1546. class="px-2 @xl:px-2.5 py-2 flex gap-1.5 items-center text-sm rounded-full transition-colors duration-300 focus:outline-hidden max-w-full overflow-hidden hover:bg-gray-50 dark:hover:bg-gray-800 {webSearchEnabled ||
  1547. ($settings?.webSearch ?? false) === 'always'
  1548. ? ' text-sky-500 dark:text-sky-300 bg-sky-50 dark:bg-sky-200/5'
  1549. : 'bg-transparent text-gray-600 dark:text-gray-300 '}"
  1550. >
  1551. <GlobeAlt className="size-4" strokeWidth="1.75" />
  1552. <span
  1553. class="hidden @xl:block whitespace-nowrap text-ellipsis leading-none normal-case pr-0.5"
  1554. >{$i18n.t('Web Search')}</span
  1555. >
  1556. </button>
  1557. </Tooltip>
  1558. {/if}
  1559. {#if showImageGenerationButton}
  1560. <Tooltip content={$i18n.t('Generate an image')} placement="top">
  1561. <button
  1562. on:click|preventDefault={() =>
  1563. (imageGenerationEnabled = !imageGenerationEnabled)}
  1564. type="button"
  1565. class="px-2 @xl:px-2.5 py-2 flex gap-1.5 items-center text-sm rounded-full transition-colors duration-300 focus:outline-hidden max-w-full overflow-hidden hover:bg-gray-50 dark:hover:bg-gray-800 {imageGenerationEnabled
  1566. ? ' text-sky-500 dark:text-sky-300 bg-sky-50 dark:bg-sky-200/5'
  1567. : 'bg-transparent text-gray-600 dark:text-gray-300 '}"
  1568. >
  1569. <Photo className="size-4" strokeWidth="1.75" />
  1570. <span
  1571. class="hidden @xl:block whitespace-nowrap text-ellipsis leading-none normal-case pr-0.5"
  1572. >{$i18n.t('Image')}</span
  1573. >
  1574. </button>
  1575. </Tooltip>
  1576. {/if}
  1577. {#if showCodeInterpreterButton}
  1578. <Tooltip content={$i18n.t('Execute code for analysis')} placement="top">
  1579. <button
  1580. aria-label={codeInterpreterEnabled
  1581. ? $i18n.t('Disable Code Interpreter')
  1582. : $i18n.t('Enable Code Interpreter')}
  1583. aria-pressed={codeInterpreterEnabled}
  1584. on:click|preventDefault={() =>
  1585. (codeInterpreterEnabled = !codeInterpreterEnabled)}
  1586. type="button"
  1587. class="px-2 @xl:px-2.5 py-2 flex gap-1.5 items-center text-sm transition-colors duration-300 max-w-full overflow-hidden hover:bg-gray-50 dark:hover:bg-gray-800 {codeInterpreterEnabled
  1588. ? ' text-sky-500 dark:text-sky-300 bg-sky-50 dark:bg-sky-200/5'
  1589. : 'bg-transparent text-gray-600 dark:text-gray-300 '} {($settings?.highContrastMode ??
  1590. false)
  1591. ? 'm-1'
  1592. : 'focus:outline-hidden rounded-full'}"
  1593. >
  1594. <CommandLine className="size-4" strokeWidth="1.75" />
  1595. <span
  1596. class="hidden @xl:block whitespace-nowrap text-ellipsis leading-none normal-case pr-0.5"
  1597. >{$i18n.t('Code Interpreter')}</span
  1598. >
  1599. </button>
  1600. </Tooltip>
  1601. {/if}
  1602. </div>
  1603. {/if}
  1604. </div>
  1605. <div class="self-end flex space-x-1 mr-1 shrink-0">
  1606. {#if (!history?.currentId || history.messages[history.currentId]?.done == true) && ($_user?.role === 'admin' || ($_user?.permissions?.chat?.stt ?? true))}
  1607. <!-- {$i18n.t('Record voice')} -->
  1608. <Tooltip content={$i18n.t('Dictate')}>
  1609. <button
  1610. id="voice-input-button"
  1611. 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"
  1612. type="button"
  1613. on:click={async () => {
  1614. try {
  1615. let stream = await navigator.mediaDevices
  1616. .getUserMedia({ audio: true })
  1617. .catch(function (err) {
  1618. toast.error(
  1619. $i18n.t(
  1620. `Permission denied when accessing microphone: {{error}}`,
  1621. {
  1622. error: err
  1623. }
  1624. )
  1625. );
  1626. return null;
  1627. });
  1628. if (stream) {
  1629. recording = true;
  1630. const tracks = stream.getTracks();
  1631. tracks.forEach((track) => track.stop());
  1632. }
  1633. stream = null;
  1634. } catch {
  1635. toast.error($i18n.t('Permission denied when accessing microphone'));
  1636. }
  1637. }}
  1638. aria-label="Voice Input"
  1639. >
  1640. <svg
  1641. xmlns="http://www.w3.org/2000/svg"
  1642. viewBox="0 0 20 20"
  1643. fill="currentColor"
  1644. class="w-5 h-5 translate-y-[0.5px]"
  1645. >
  1646. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  1647. <path
  1648. 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"
  1649. />
  1650. </svg>
  1651. </button>
  1652. </Tooltip>
  1653. {/if}
  1654. {#if (taskIds && taskIds.length > 0) || (history.currentId && history.messages[history.currentId]?.done != true) || generating}
  1655. <div class=" flex items-center">
  1656. <Tooltip content={$i18n.t('Stop')}>
  1657. <button
  1658. 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"
  1659. on:click={() => {
  1660. stopResponse();
  1661. }}
  1662. >
  1663. <svg
  1664. xmlns="http://www.w3.org/2000/svg"
  1665. viewBox="0 0 24 24"
  1666. fill="currentColor"
  1667. class="size-5"
  1668. >
  1669. <path
  1670. fill-rule="evenodd"
  1671. 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"
  1672. clip-rule="evenodd"
  1673. />
  1674. </svg>
  1675. </button>
  1676. </Tooltip>
  1677. </div>
  1678. {:else if prompt === '' && files.length === 0 && ($_user?.role === 'admin' || ($_user?.permissions?.chat?.call ?? true))}
  1679. <div class=" flex items-center">
  1680. <!-- {$i18n.t('Call')} -->
  1681. <Tooltip content={$i18n.t('Voice mode')}>
  1682. <button
  1683. 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"
  1684. type="button"
  1685. on:click={async () => {
  1686. if (selectedModels.length > 1) {
  1687. toast.error($i18n.t('Select only one model to call'));
  1688. return;
  1689. }
  1690. if ($config.audio.stt.engine === 'web') {
  1691. toast.error(
  1692. $i18n.t('Call feature is not supported when using Web STT engine')
  1693. );
  1694. return;
  1695. }
  1696. // check if user has access to getUserMedia
  1697. try {
  1698. let stream = await navigator.mediaDevices.getUserMedia({
  1699. audio: true
  1700. });
  1701. // If the user grants the permission, proceed to show the call overlay
  1702. if (stream) {
  1703. const tracks = stream.getTracks();
  1704. tracks.forEach((track) => track.stop());
  1705. }
  1706. stream = null;
  1707. if ($settings.audio?.tts?.engine === 'browser-kokoro') {
  1708. // If the user has not initialized the TTS worker, initialize it
  1709. if (!$TTSWorker) {
  1710. await TTSWorker.set(
  1711. new KokoroWorker({
  1712. dtype: $settings.audio?.tts?.engineConfig?.dtype ?? 'fp32'
  1713. })
  1714. );
  1715. await $TTSWorker.init();
  1716. }
  1717. }
  1718. showCallOverlay.set(true);
  1719. showControls.set(true);
  1720. } catch (err) {
  1721. // If the user denies the permission or an error occurs, show an error message
  1722. toast.error(
  1723. $i18n.t('Permission denied when accessing media devices')
  1724. );
  1725. }
  1726. }}
  1727. aria-label={$i18n.t('Voice mode')}
  1728. >
  1729. <Voice className="size-5" strokeWidth="2.5" />
  1730. </button>
  1731. </Tooltip>
  1732. </div>
  1733. {:else}
  1734. <div class=" flex items-center">
  1735. <Tooltip content={$i18n.t('Send message')}>
  1736. <button
  1737. id="send-message-button"
  1738. class="{!(prompt === '' && files.length === 0)
  1739. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  1740. : 'text-white bg-gray-200 dark:text-gray-900 dark:bg-gray-700 disabled'} transition rounded-full p-1.5 self-center"
  1741. type="submit"
  1742. disabled={prompt === '' && files.length === 0}
  1743. >
  1744. <svg
  1745. xmlns="http://www.w3.org/2000/svg"
  1746. viewBox="0 0 16 16"
  1747. fill="currentColor"
  1748. class="size-5"
  1749. >
  1750. <path
  1751. fill-rule="evenodd"
  1752. 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"
  1753. clip-rule="evenodd"
  1754. />
  1755. </svg>
  1756. </button>
  1757. </Tooltip>
  1758. </div>
  1759. {/if}
  1760. </div>
  1761. </div>
  1762. </div>
  1763. {#if $config?.license_metadata?.input_footer}
  1764. <div class=" text-xs text-gray-500 text-center line-clamp-1 marked">
  1765. {@html DOMPurify.sanitize(marked($config?.license_metadata?.input_footer))}
  1766. </div>
  1767. {:else}
  1768. <div class="mb-1" />
  1769. {/if}
  1770. </form>
  1771. {/if}
  1772. </div>
  1773. </div>
  1774. </div>
  1775. </div>
  1776. {/if}