+layout.svelte 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. <script>
  2. import { io } from 'socket.io-client';
  3. import { spring } from 'svelte/motion';
  4. import PyodideWorker from '$lib/workers/pyodide.worker?worker';
  5. let loadingProgress = spring(0, {
  6. stiffness: 0.05
  7. });
  8. import { onMount, tick, setContext } from 'svelte';
  9. import {
  10. config,
  11. user,
  12. settings,
  13. theme,
  14. WEBUI_NAME,
  15. mobile,
  16. socket,
  17. activeUserIds,
  18. USAGE_POOL,
  19. chatId,
  20. chats,
  21. currentChatPage,
  22. tags,
  23. temporaryChatEnabled,
  24. isLastActiveTab,
  25. isApp,
  26. appInfo
  27. } from '$lib/stores';
  28. import { goto } from '$app/navigation';
  29. import { page } from '$app/stores';
  30. import { Toaster, toast } from 'svelte-sonner';
  31. import { getBackendConfig } from '$lib/apis';
  32. import { getSessionUser } from '$lib/apis/auths';
  33. import '../tailwind.css';
  34. import '../app.css';
  35. import 'tippy.js/dist/tippy.css';
  36. import { WEBUI_BASE_URL, WEBUI_HOSTNAME } from '$lib/constants';
  37. import i18n, { initI18n, getLanguages } from '$lib/i18n';
  38. import { bestMatchingLanguage } from '$lib/utils';
  39. import { getAllTags, getChatList } from '$lib/apis/chats';
  40. import NotificationToast from '$lib/components/NotificationToast.svelte';
  41. import AppSidebar from '$lib/components/app/AppSidebar.svelte';
  42. import { chatCompletion } from '$lib/apis/openai';
  43. setContext('i18n', i18n);
  44. const bc = new BroadcastChannel('active-tab-channel');
  45. let loaded = false;
  46. const BREAKPOINT = 768;
  47. const setupSocket = async (enableWebsocket) => {
  48. const _socket = io(`${WEBUI_BASE_URL}` || undefined, {
  49. reconnection: true,
  50. reconnectionDelay: 1000,
  51. reconnectionDelayMax: 5000,
  52. randomizationFactor: 0.5,
  53. path: '/ws/socket.io',
  54. transports: enableWebsocket ? ['websocket'] : ['polling', 'websocket'],
  55. auth: { token: localStorage.token }
  56. });
  57. await socket.set(_socket);
  58. _socket.on('connect_error', (err) => {
  59. console.log('connect_error', err);
  60. });
  61. _socket.on('connect', () => {
  62. console.log('connected', _socket.id);
  63. });
  64. _socket.on('reconnect_attempt', (attempt) => {
  65. console.log('reconnect_attempt', attempt);
  66. });
  67. _socket.on('reconnect_failed', () => {
  68. console.log('reconnect_failed');
  69. });
  70. _socket.on('disconnect', (reason, details) => {
  71. console.log(`Socket ${_socket.id} disconnected due to ${reason}`);
  72. if (details) {
  73. console.log('Additional details:', details);
  74. }
  75. });
  76. _socket.on('user-list', (data) => {
  77. console.log('user-list', data);
  78. activeUserIds.set(data.user_ids);
  79. });
  80. _socket.on('usage', (data) => {
  81. console.log('usage', data);
  82. USAGE_POOL.set(data['models']);
  83. });
  84. };
  85. const executePythonAsWorker = async (id, code, cb) => {
  86. let result = null;
  87. let stdout = null;
  88. let stderr = null;
  89. let executing = true;
  90. let packages = [
  91. code.includes('requests') ? 'requests' : null,
  92. code.includes('bs4') ? 'beautifulsoup4' : null,
  93. code.includes('numpy') ? 'numpy' : null,
  94. code.includes('pandas') ? 'pandas' : null,
  95. code.includes('matplotlib') ? 'matplotlib' : null,
  96. code.includes('sklearn') ? 'scikit-learn' : null,
  97. code.includes('scipy') ? 'scipy' : null,
  98. code.includes('re') ? 'regex' : null,
  99. code.includes('seaborn') ? 'seaborn' : null,
  100. code.includes('sympy') ? 'sympy' : null,
  101. code.includes('tiktoken') ? 'tiktoken' : null,
  102. code.includes('pytz') ? 'pytz' : null
  103. ].filter(Boolean);
  104. const pyodideWorker = new PyodideWorker();
  105. pyodideWorker.postMessage({
  106. id: id,
  107. code: code,
  108. packages: packages
  109. });
  110. setTimeout(() => {
  111. if (executing) {
  112. executing = false;
  113. stderr = 'Execution Time Limit Exceeded';
  114. pyodideWorker.terminate();
  115. if (cb) {
  116. cb(
  117. JSON.parse(
  118. JSON.stringify(
  119. {
  120. stdout: stdout,
  121. stderr: stderr,
  122. result: result
  123. },
  124. (_key, value) => (typeof value === 'bigint' ? value.toString() : value)
  125. )
  126. )
  127. );
  128. }
  129. }
  130. }, 60000);
  131. pyodideWorker.onmessage = (event) => {
  132. console.log('pyodideWorker.onmessage', event);
  133. const { id, ...data } = event.data;
  134. console.log(id, data);
  135. data['stdout'] && (stdout = data['stdout']);
  136. data['stderr'] && (stderr = data['stderr']);
  137. data['result'] && (result = data['result']);
  138. if (cb) {
  139. cb(
  140. JSON.parse(
  141. JSON.stringify(
  142. {
  143. stdout: stdout,
  144. stderr: stderr,
  145. result: result
  146. },
  147. (_key, value) => (typeof value === 'bigint' ? value.toString() : value)
  148. )
  149. )
  150. );
  151. }
  152. executing = false;
  153. };
  154. pyodideWorker.onerror = (event) => {
  155. console.log('pyodideWorker.onerror', event);
  156. if (cb) {
  157. cb(
  158. JSON.parse(
  159. JSON.stringify(
  160. {
  161. stdout: stdout,
  162. stderr: stderr,
  163. result: result
  164. },
  165. (_key, value) => (typeof value === 'bigint' ? value.toString() : value)
  166. )
  167. )
  168. );
  169. }
  170. executing = false;
  171. };
  172. };
  173. const chatEventHandler = async (event, cb) => {
  174. const chat = $page.url.pathname.includes(`/c/${event.chat_id}`);
  175. let isFocused = document.visibilityState !== 'visible';
  176. if (window.electronAPI) {
  177. const res = await window.electronAPI.send({
  178. type: 'window:isFocused'
  179. });
  180. if (res) {
  181. isFocused = res.isFocused;
  182. }
  183. }
  184. await tick();
  185. const type = event?.data?.type ?? null;
  186. const data = event?.data?.data ?? null;
  187. if ((event.chat_id !== $chatId && !$temporaryChatEnabled) || isFocused) {
  188. if (type === 'chat:completion') {
  189. const { done, content, title } = data;
  190. if (done) {
  191. if ($isLastActiveTab) {
  192. if ($settings?.notificationEnabled ?? false) {
  193. new Notification(`${title} | Open WebUI`, {
  194. body: content,
  195. icon: `${WEBUI_BASE_URL}/static/favicon.png`
  196. });
  197. }
  198. }
  199. toast.custom(NotificationToast, {
  200. componentProps: {
  201. onClick: () => {
  202. goto(`/c/${event.chat_id}`);
  203. },
  204. content: content,
  205. title: title
  206. },
  207. duration: 15000,
  208. unstyled: true
  209. });
  210. }
  211. } else if (type === 'chat:title') {
  212. currentChatPage.set(1);
  213. await chats.set(await getChatList(localStorage.token, $currentChatPage));
  214. } else if (type === 'chat:tags') {
  215. tags.set(await getAllTags(localStorage.token));
  216. }
  217. } else if (data?.session_id === $socket.id) {
  218. if (type === 'execute:python') {
  219. console.log('execute:python', data);
  220. executePythonAsWorker(data.id, data.code, cb);
  221. } else if (type === 'request:chat:completion') {
  222. console.log(data, $socket.id);
  223. const { session_id, channel, form_data, model } = data;
  224. try {
  225. const directConnections = $settings?.directConnections ?? {};
  226. if (directConnections) {
  227. const urlIdx = model?.urlIdx;
  228. const OPENAI_API_URL = directConnections.OPENAI_API_BASE_URLS[urlIdx];
  229. const OPENAI_API_KEY = directConnections.OPENAI_API_KEYS[urlIdx];
  230. const API_CONFIG = directConnections.OPENAI_API_CONFIGS[urlIdx];
  231. try {
  232. if (API_CONFIG?.prefix_id) {
  233. const prefixId = API_CONFIG.prefix_id;
  234. form_data['model'] = form_data['model'].replace(`${prefixId}.`, ``);
  235. }
  236. const [res, controller] = await chatCompletion(
  237. OPENAI_API_KEY,
  238. form_data,
  239. OPENAI_API_URL
  240. );
  241. if (res) {
  242. // raise if the response is not ok
  243. if (!res.ok) {
  244. throw await res.json();
  245. }
  246. if (form_data?.stream ?? false) {
  247. cb({
  248. status: true
  249. });
  250. console.log({ status: true });
  251. // res will either be SSE or JSON
  252. const reader = res.body.getReader();
  253. const decoder = new TextDecoder();
  254. const processStream = async () => {
  255. while (true) {
  256. // Read data chunks from the response stream
  257. const { done, value } = await reader.read();
  258. if (done) {
  259. break;
  260. }
  261. // Decode the received chunk
  262. const chunk = decoder.decode(value, { stream: true });
  263. // Process lines within the chunk
  264. const lines = chunk.split('\n').filter((line) => line.trim() !== '');
  265. for (const line of lines) {
  266. console.log(line);
  267. $socket?.emit(channel, line);
  268. }
  269. }
  270. };
  271. // Process the stream in the background
  272. await processStream();
  273. } else {
  274. const data = await res.json();
  275. cb(data);
  276. }
  277. } else {
  278. throw new Error('An error occurred while fetching the completion');
  279. }
  280. } catch (error) {
  281. console.error('chatCompletion', error);
  282. cb(error);
  283. }
  284. }
  285. } catch (error) {
  286. console.error('chatCompletion', error);
  287. cb(error);
  288. } finally {
  289. $socket.emit(channel, {
  290. done: true
  291. });
  292. }
  293. } else {
  294. console.log('chatEventHandler', event);
  295. }
  296. }
  297. };
  298. const channelEventHandler = async (event) => {
  299. if (event.data?.type === 'typing') {
  300. return;
  301. }
  302. // check url path
  303. const channel = $page.url.pathname.includes(`/channels/${event.channel_id}`);
  304. let isFocused = document.visibilityState !== 'visible';
  305. if (window.electronAPI) {
  306. const res = await window.electronAPI.send({
  307. type: 'window:isFocused'
  308. });
  309. if (res) {
  310. isFocused = res.isFocused;
  311. }
  312. }
  313. if ((!channel || isFocused) && event?.user?.id !== $user?.id) {
  314. await tick();
  315. const type = event?.data?.type ?? null;
  316. const data = event?.data?.data ?? null;
  317. if (type === 'message') {
  318. if ($isLastActiveTab) {
  319. if ($settings?.notificationEnabled ?? false) {
  320. new Notification(`${data?.user?.name} (#${event?.channel?.name}) | Open WebUI`, {
  321. body: data?.content,
  322. icon: data?.user?.profile_image_url ?? `${WEBUI_BASE_URL}/static/favicon.png`
  323. });
  324. }
  325. }
  326. toast.custom(NotificationToast, {
  327. componentProps: {
  328. onClick: () => {
  329. goto(`/channels/${event.channel_id}`);
  330. },
  331. content: data?.content,
  332. title: event?.channel?.name
  333. },
  334. duration: 15000,
  335. unstyled: true
  336. });
  337. }
  338. }
  339. };
  340. onMount(async () => {
  341. if (typeof window !== 'undefined' && window.applyTheme) {
  342. window.applyTheme();
  343. }
  344. if (window?.electronAPI) {
  345. const info = await window.electronAPI.send({
  346. type: 'app:info'
  347. });
  348. if (info) {
  349. isApp.set(true);
  350. appInfo.set(info);
  351. const data = await window.electronAPI.send({
  352. type: 'app:data'
  353. });
  354. if (data) {
  355. appData.set(data);
  356. }
  357. }
  358. }
  359. // Listen for messages on the BroadcastChannel
  360. bc.onmessage = (event) => {
  361. if (event.data === 'active') {
  362. isLastActiveTab.set(false); // Another tab became active
  363. }
  364. };
  365. // Set yourself as the last active tab when this tab is focused
  366. const handleVisibilityChange = () => {
  367. if (document.visibilityState === 'visible') {
  368. isLastActiveTab.set(true); // This tab is now the active tab
  369. bc.postMessage('active'); // Notify other tabs that this tab is active
  370. }
  371. };
  372. // Add event listener for visibility state changes
  373. document.addEventListener('visibilitychange', handleVisibilityChange);
  374. // Call visibility change handler initially to set state on load
  375. handleVisibilityChange();
  376. theme.set(localStorage.theme);
  377. mobile.set(window.innerWidth < BREAKPOINT);
  378. const onResize = () => {
  379. if (window.innerWidth < BREAKPOINT) {
  380. mobile.set(true);
  381. } else {
  382. mobile.set(false);
  383. }
  384. };
  385. window.addEventListener('resize', onResize);
  386. let backendConfig = null;
  387. try {
  388. backendConfig = await getBackendConfig();
  389. console.log('Backend config:', backendConfig);
  390. } catch (error) {
  391. console.error('Error loading backend config:', error);
  392. }
  393. // Initialize i18n even if we didn't get a backend config,
  394. // so `/error` can show something that's not `undefined`.
  395. initI18n();
  396. if (!localStorage.locale) {
  397. const languages = await getLanguages();
  398. const browserLanguages = navigator.languages
  399. ? navigator.languages
  400. : [navigator.language || navigator.userLanguage];
  401. const lang = backendConfig.default_locale
  402. ? backendConfig.default_locale
  403. : bestMatchingLanguage(languages, browserLanguages, 'en-US');
  404. $i18n.changeLanguage(lang);
  405. }
  406. if (backendConfig) {
  407. // Save Backend Status to Store
  408. await config.set(backendConfig);
  409. await WEBUI_NAME.set(backendConfig.name);
  410. if ($config) {
  411. await setupSocket($config.features?.enable_websocket ?? true);
  412. if (localStorage.token) {
  413. // Get Session User Info
  414. const sessionUser = await getSessionUser(localStorage.token).catch((error) => {
  415. toast.error(`${error}`);
  416. return null;
  417. });
  418. if (sessionUser) {
  419. // Save Session User to Store
  420. $socket.emit('user-join', { auth: { token: sessionUser.token } });
  421. $socket?.on('chat-events', chatEventHandler);
  422. $socket?.on('channel-events', channelEventHandler);
  423. await user.set(sessionUser);
  424. await config.set(await getBackendConfig());
  425. } else {
  426. // Redirect Invalid Session User to /auth Page
  427. localStorage.removeItem('token');
  428. await goto('/auth');
  429. }
  430. } else {
  431. // Don't redirect if we're already on the auth page
  432. // Needed because we pass in tokens from OAuth logins via URL fragments
  433. if ($page.url.pathname !== '/auth') {
  434. await goto('/auth');
  435. }
  436. }
  437. }
  438. } else {
  439. // Redirect to /error when Backend Not Detected
  440. await goto(`/error`);
  441. }
  442. await tick();
  443. if (
  444. document.documentElement.classList.contains('her') &&
  445. document.getElementById('progress-bar')
  446. ) {
  447. loadingProgress.subscribe((value) => {
  448. const progressBar = document.getElementById('progress-bar');
  449. if (progressBar) {
  450. progressBar.style.width = `${value}%`;
  451. }
  452. });
  453. await loadingProgress.set(100);
  454. document.getElementById('splash-screen')?.remove();
  455. const audio = new Audio(`/audio/greeting.mp3`);
  456. const playAudio = () => {
  457. audio.play();
  458. document.removeEventListener('click', playAudio);
  459. };
  460. document.addEventListener('click', playAudio);
  461. loaded = true;
  462. } else {
  463. document.getElementById('splash-screen')?.remove();
  464. loaded = true;
  465. }
  466. return () => {
  467. window.removeEventListener('resize', onResize);
  468. };
  469. });
  470. </script>
  471. <svelte:head>
  472. <title>{$WEBUI_NAME}</title>
  473. <link crossorigin="anonymous" rel="icon" href="{WEBUI_BASE_URL}/static/favicon.png" />
  474. <!-- rosepine themes have been disabled as it's not up to date with our latest version. -->
  475. <!-- feel free to make a PR to fix if anyone wants to see it return -->
  476. <!-- <link rel="stylesheet" type="text/css" href="/themes/rosepine.css" />
  477. <link rel="stylesheet" type="text/css" href="/themes/rosepine-dawn.css" /> -->
  478. </svelte:head>
  479. {#if loaded}
  480. {#if $isApp}
  481. <div class="flex flex-row h-screen">
  482. <AppSidebar />
  483. <div class="w-full flex-1 max-w-[calc(100%-4.5rem)]">
  484. <slot />
  485. </div>
  486. </div>
  487. {:else}
  488. <slot />
  489. {/if}
  490. {/if}
  491. <Toaster
  492. theme={$theme.includes('dark')
  493. ? 'dark'
  494. : $theme === 'system'
  495. ? window.matchMedia('(prefers-color-scheme: dark)').matches
  496. ? 'dark'
  497. : 'light'
  498. : 'light'}
  499. richColors
  500. position="top-right"
  501. />