MessageInput.svelte 56 KB

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