MessageInput.svelte 56 KB

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