MessageInput.svelte 64 KB

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