open-webui/src/routes/+layout.svelte

824 lines
21 KiB
Svelte
Raw Normal View History

2023-10-08 22:38:42 +00:00
<script>
2024-06-04 06:39:52 +00:00
import { io } from 'socket.io-client';
2024-06-12 07:05:20 +00:00
import { spring } from 'svelte/motion';
2025-02-03 06:38:19 +00:00
import PyodideWorker from '$lib/workers/pyodide.worker?worker';
2025-11-03 18:43:07 +00:00
import { Toaster, toast } from 'svelte-sonner';
2024-06-12 07:05:20 +00:00
2024-06-12 07:13:35 +00:00
let loadingProgress = spring(0, {
stiffness: 0.05
});
2024-06-04 06:39:52 +00:00
2025-05-22 21:08:28 +00:00
import { onMount, tick, setContext, onDestroy } from 'svelte';
2024-06-04 18:13:43 +00:00
import {
config,
user,
2025-01-04 10:15:57 +00:00
settings,
2024-06-04 18:13:43 +00:00
theme,
WEBUI_NAME,
2025-11-03 18:43:07 +00:00
WEBUI_VERSION,
WEBUI_DEPLOYMENT_ID,
2024-06-04 18:13:43 +00:00
mobile,
socket,
2024-12-25 01:25:59 +00:00
chatId,
chats,
currentChatPage,
2024-12-25 04:28:35 +00:00
tags,
temporaryChatEnabled,
2025-01-14 03:18:32 +00:00
isLastActiveTab,
isApp,
2025-03-27 09:50:53 +00:00
appInfo,
2025-04-20 06:13:19 +00:00
toolServers,
playingNotificationSound,
channels
2024-06-04 18:13:43 +00:00
} from '$lib/stores';
2023-11-19 00:47:12 +00:00
import { goto } from '$app/navigation';
import { page } from '$app/stores';
2025-11-03 18:43:07 +00:00
import { beforeNavigate } from '$app/navigation';
import { updated } from '$app/state';
2023-10-08 22:38:42 +00:00
2025-11-03 18:43:07 +00:00
import i18n, { initI18n, getLanguages, changeLanguage } from '$lib/i18n';
2023-12-26 19:32:22 +00:00
2023-10-08 22:38:42 +00:00
import '../tailwind.css';
2024-04-27 22:50:26 +00:00
import '../app.css';
2023-12-14 22:24:56 +00:00
import 'tippy.js/dist/tippy.css';
2024-04-27 22:50:26 +00:00
2025-11-03 18:43:07 +00:00
import { executeToolServer, getBackendConfig, getVersion } from '$lib/apis';
import { getSessionUser, userSignOut } from '$lib/apis/auths';
import { getAllTags, getChatList } from '$lib/apis/chats';
import { chatCompletion } from '$lib/apis/openai';
2025-11-21 01:43:59 +00:00
import { WEBUI_API_BASE_URL, WEBUI_BASE_URL, WEBUI_HOSTNAME } from '$lib/constants';
2024-06-30 03:04:04 +00:00
import { bestMatchingLanguage } from '$lib/utils';
2025-11-19 08:51:10 +00:00
import { setTextScale } from '$lib/utils/text-scale';
2025-11-03 18:43:07 +00:00
2024-12-25 01:25:59 +00:00
import NotificationToast from '$lib/components/NotificationToast.svelte';
2025-01-19 01:50:03 +00:00
import AppSidebar from '$lib/components/app/AppSidebar.svelte';
2025-08-27 00:16:02 +00:00
import Spinner from '$lib/components/common/Spinner.svelte';
2025-11-19 08:51:10 +00:00
import { getUserSettings } from '$lib/apis/users';
import dayjs from 'dayjs';
2025-11-27 12:27:32 +00:00
import { getChannels } from '$lib/apis/channels';
const unregisterServiceWorkers = async () => {
if ('serviceWorker' in navigator) {
try {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((r) => r.unregister()));
return true;
} catch (error) {
console.error('Error unregistering service workers:', error);
return false;
}
}
return false;
};
// handle frontend updates (https://svelte.dev/docs/kit/configuration#version)
beforeNavigate(async ({ willUnload, to }) => {
if (updated.current && !willUnload && to?.url) {
await unregisterServiceWorkers();
location.href = to.url.href;
}
});
2024-03-01 04:40:36 +00:00
setContext('i18n', i18n);
2023-12-26 19:32:22 +00:00
const bc = new BroadcastChannel('active-tab-channel');
2023-11-19 00:47:12 +00:00
let loaded = false;
2025-04-23 18:12:22 +00:00
let tokenTimer = null;
2025-08-27 00:16:02 +00:00
let showRefresh = false;
2024-05-15 06:48:46 +00:00
const BREAKPOINT = 768;
2023-11-19 00:47:12 +00:00
2025-05-09 10:20:43 +00:00
const setupSocket = async (enableWebsocket) => {
const _socket = io(`${WEBUI_BASE_URL}` || undefined, {
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
randomizationFactor: 0.5,
path: '/ws/socket.io',
transports: enableWebsocket ? ['websocket'] : ['polling', 'websocket'],
auth: { token: localStorage.token }
});
await socket.set(_socket);
_socket.on('connect_error', (err) => {
console.log('connect_error', err);
});
2025-11-03 18:43:07 +00:00
_socket.on('connect', async () => {
2025-05-09 10:20:43 +00:00
console.log('connected', _socket.id);
const res = await getVersion(localStorage.token);
const deploymentId = res?.deployment_id ?? null;
const version = res?.version ?? null;
if (version !== null || deploymentId !== null) {
if (
($WEBUI_VERSION !== null && version !== $WEBUI_VERSION) ||
($WEBUI_DEPLOYMENT_ID !== null && deploymentId !== $WEBUI_DEPLOYMENT_ID)
) {
await unregisterServiceWorkers();
2025-11-03 18:43:07 +00:00
location.href = location.href;
return;
2025-11-03 18:43:07 +00:00
}
}
if (deploymentId !== null) {
WEBUI_DEPLOYMENT_ID.set(deploymentId);
}
if (version !== null) {
WEBUI_VERSION.set(version);
}
2025-11-03 18:43:07 +00:00
console.log('version', version);
2025-07-15 17:24:05 +00:00
if (localStorage.getItem('token')) {
// Emit user-join event with auth token
_socket.emit('user-join', { auth: { token: localStorage.token } });
} else {
console.warn('No token found in localStorage, user-join event not emitted');
}
2025-05-09 10:20:43 +00:00
});
_socket.on('reconnect_attempt', (attempt) => {
console.log('reconnect_attempt', attempt);
});
_socket.on('reconnect_failed', () => {
console.log('reconnect_failed');
});
_socket.on('disconnect', (reason, details) => {
console.log(`Socket ${_socket.id} disconnected due to ${reason}`);
if (details) {
console.log('Additional details:', details);
}
});
};
2025-02-03 06:38:19 +00:00
const executePythonAsWorker = async (id, code, cb) => {
let result = null;
let stdout = null;
let stderr = null;
let executing = true;
let packages = [
2025-09-03 11:48:07 +00:00
/\bimport\s+requests\b|\bfrom\s+requests\b/.test(code) ? 'requests' : null,
/\bimport\s+bs4\b|\bfrom\s+bs4\b/.test(code) ? 'beautifulsoup4' : null,
/\bimport\s+numpy\b|\bfrom\s+numpy\b/.test(code) ? 'numpy' : null,
/\bimport\s+pandas\b|\bfrom\s+pandas\b/.test(code) ? 'pandas' : null,
/\bimport\s+matplotlib\b|\bfrom\s+matplotlib\b/.test(code) ? 'matplotlib' : null,
/\bimport\s+seaborn\b|\bfrom\s+seaborn\b/.test(code) ? 'seaborn' : null,
/\bimport\s+sklearn\b|\bfrom\s+sklearn\b/.test(code) ? 'scikit-learn' : null,
/\bimport\s+scipy\b|\bfrom\s+scipy\b/.test(code) ? 'scipy' : null,
2025-09-03 11:46:42 +00:00
/\bimport\s+re\b|\bfrom\s+re\b/.test(code) ? 'regex' : null,
2025-09-03 11:48:07 +00:00
/\bimport\s+seaborn\b|\bfrom\s+seaborn\b/.test(code) ? 'seaborn' : null,
/\bimport\s+sympy\b|\bfrom\s+sympy\b/.test(code) ? 'sympy' : null,
/\bimport\s+tiktoken\b|\bfrom\s+tiktoken\b/.test(code) ? 'tiktoken' : null,
/\bimport\s+pytz\b|\bfrom\s+pytz\b/.test(code) ? 'pytz' : null
2025-02-03 06:38:19 +00:00
].filter(Boolean);
const pyodideWorker = new PyodideWorker();
pyodideWorker.postMessage({
id: id,
code: code,
packages: packages
});
setTimeout(() => {
if (executing) {
executing = false;
stderr = 'Execution Time Limit Exceeded';
pyodideWorker.terminate();
if (cb) {
cb(
JSON.parse(
JSON.stringify(
{
stdout: stdout,
stderr: stderr,
result: result
},
(_key, value) => (typeof value === 'bigint' ? value.toString() : value)
)
)
);
}
}
}, 60000);
pyodideWorker.onmessage = (event) => {
console.log('pyodideWorker.onmessage', event);
const { id, ...data } = event.data;
console.log(id, data);
data['stdout'] && (stdout = data['stdout']);
data['stderr'] && (stderr = data['stderr']);
data['result'] && (result = data['result']);
if (cb) {
cb(
JSON.parse(
JSON.stringify(
{
stdout: stdout,
stderr: stderr,
result: result
},
(_key, value) => (typeof value === 'bigint' ? value.toString() : value)
)
)
);
}
executing = false;
};
pyodideWorker.onerror = (event) => {
console.log('pyodideWorker.onerror', event);
if (cb) {
cb(
JSON.parse(
JSON.stringify(
{
stdout: stdout,
stderr: stderr,
result: result
},
(_key, value) => (typeof value === 'bigint' ? value.toString() : value)
)
)
);
}
executing = false;
};
};
2025-03-26 07:40:24 +00:00
const executeTool = async (data, cb) => {
const toolServer = $settings?.toolServers?.find((server) => server.url === data.server?.url);
const toolServerData = $toolServers?.find((server) => server.url === data.server?.url);
2025-03-27 09:27:56 +00:00
2025-03-27 09:50:53 +00:00
console.log('executeTool', data, toolServer);
2025-03-27 09:27:56 +00:00
if (toolServer) {
2025-04-11 00:47:07 +00:00
console.log(toolServer);
2025-09-08 15:12:20 +00:00
let toolServerToken = null;
const auth_type = toolServer?.auth_type ?? 'bearer';
if (auth_type === 'bearer') {
toolServerToken = toolServer?.key;
} else if (auth_type === 'none') {
// No authentication
} else if (auth_type === 'session') {
toolServerToken = localStorage.token;
}
2025-03-27 09:27:56 +00:00
const res = await executeToolServer(
2025-09-08 15:12:20 +00:00
toolServerToken,
2025-03-27 09:27:56 +00:00
toolServer.url,
data?.name,
data?.params,
toolServerData
2025-03-27 09:50:53 +00:00
);
2025-03-27 09:27:56 +00:00
2025-03-27 09:50:53 +00:00
console.log('executeToolServer', res);
2025-03-27 09:27:56 +00:00
if (cb) {
cb(JSON.parse(JSON.stringify(res)));
}
} else {
if (cb) {
cb(
JSON.parse(
JSON.stringify({
error: 'Tool Server Not Found'
})
)
);
}
2025-03-26 07:40:24 +00:00
}
};
2025-02-03 06:38:19 +00:00
const chatEventHandler = async (event, cb) => {
2024-12-25 04:16:09 +00:00
const chat = $page.url.pathname.includes(`/c/${event.chat_id}`);
2025-01-14 03:47:24 +00:00
let isFocused = document.visibilityState !== 'visible';
if (window.electronAPI) {
2025-01-14 03:53:00 +00:00
const res = await window.electronAPI.send({
2025-01-14 03:47:24 +00:00
type: 'window:isFocused'
});
2025-01-14 03:53:00 +00:00
if (res) {
isFocused = res.isFocused;
}
2025-01-14 03:47:24 +00:00
}
2025-02-03 06:38:19 +00:00
await tick();
const type = event?.data?.type ?? null;
const data = event?.data?.data ?? null;
2024-12-25 01:25:59 +00:00
2025-02-03 06:38:19 +00:00
if ((event.chat_id !== $chatId && !$temporaryChatEnabled) || isFocused) {
2024-12-25 01:25:59 +00:00
if (type === 'chat:completion') {
const { done, content, title } = data;
if (done) {
2025-04-20 06:13:19 +00:00
if ($settings?.notificationSoundAlways ?? false) {
playingNotificationSound.set(true);
const audio = new Audio(`/audio/notification.mp3`);
audio.play().finally(() => {
// Ensure the global state is reset after the sound finishes
playingNotificationSound.set(false);
});
}
if ($isLastActiveTab) {
if ($settings?.notificationEnabled ?? false) {
2025-05-01 12:39:36 +00:00
new Notification(`${title} • Open WebUI`, {
body: content,
icon: `${WEBUI_BASE_URL}/static/favicon.png`
});
}
2025-01-04 10:15:57 +00:00
}
2024-12-25 01:25:59 +00:00
toast.custom(NotificationToast, {
componentProps: {
onClick: () => {
goto(`/c/${event.chat_id}`);
},
content: content,
title: title
},
duration: 15000,
unstyled: true
});
}
} else if (type === 'chat:title') {
currentChatPage.set(1);
await chats.set(await getChatList(localStorage.token, $currentChatPage));
} else if (type === 'chat:tags') {
tags.set(await getAllTags(localStorage.token));
}
2025-02-13 06:56:33 +00:00
} else if (data?.session_id === $socket.id) {
2025-02-03 07:35:58 +00:00
if (type === 'execute:python') {
console.log('execute:python', data);
2025-02-03 06:38:19 +00:00
executePythonAsWorker(data.id, data.code, cb);
2025-03-26 07:40:24 +00:00
} else if (type === 'execute:tool') {
console.log('execute:tool', data);
executeTool(data, cb);
2025-02-13 06:56:33 +00:00
} else if (type === 'request:chat:completion') {
console.log(data, $socket.id);
const { session_id, channel, form_data, model } = data;
try {
const directConnections = $settings?.directConnections ?? {};
if (directConnections) {
const urlIdx = model?.urlIdx;
const OPENAI_API_URL = directConnections.OPENAI_API_BASE_URLS[urlIdx];
const OPENAI_API_KEY = directConnections.OPENAI_API_KEYS[urlIdx];
const API_CONFIG = directConnections.OPENAI_API_CONFIGS[urlIdx];
try {
2025-02-13 07:26:47 +00:00
if (API_CONFIG?.prefix_id) {
const prefixId = API_CONFIG.prefix_id;
form_data['model'] = form_data['model'].replace(`${prefixId}.`, ``);
}
2025-02-13 06:56:33 +00:00
const [res, controller] = await chatCompletion(
OPENAI_API_KEY,
form_data,
OPENAI_API_URL
);
2025-02-13 07:21:16 +00:00
if (res) {
// raise if the response is not ok
if (!res.ok) {
throw await res.json();
}
2025-02-13 06:56:33 +00:00
if (form_data?.stream ?? false) {
2025-02-13 07:21:16 +00:00
cb({
status: true
});
2025-02-13 07:49:00 +00:00
console.log({ status: true });
2025-02-13 07:21:16 +00:00
2025-02-13 06:56:33 +00:00
// res will either be SSE or JSON
const reader = res.body.getReader();
const decoder = new TextDecoder();
const processStream = async () => {
while (true) {
// Read data chunks from the response stream
const { done, value } = await reader.read();
if (done) {
break;
}
// Decode the received chunk
const chunk = decoder.decode(value, { stream: true });
// Process lines within the chunk
const lines = chunk.split('\n').filter((line) => line.trim() !== '');
for (const line of lines) {
2025-02-13 08:34:45 +00:00
console.log(line);
2025-02-13 06:56:33 +00:00
$socket?.emit(channel, line);
}
}
};
// Process the stream in the background
await processStream();
} else {
const data = await res.json();
cb(data);
}
} else {
throw new Error('An error occurred while fetching the completion');
}
} catch (error) {
console.error('chatCompletion', error);
2025-02-13 07:21:16 +00:00
cb(error);
2025-02-13 06:56:33 +00:00
}
}
} catch (error) {
console.error('chatCompletion', error);
2025-02-13 07:21:16 +00:00
cb(error);
2025-02-13 06:56:33 +00:00
} finally {
$socket.emit(channel, {
done: true
});
}
} else {
console.log('chatEventHandler', event);
2025-02-03 06:38:19 +00:00
}
2024-12-25 01:25:59 +00:00
}
};
const channelEventHandler = async (event) => {
2025-01-14 04:21:47 +00:00
if (event.data?.type === 'typing') {
return;
}
2024-12-25 01:25:59 +00:00
// check url path
const channel = $page.url.pathname.includes(`/channels/${event.channel_id}`);
2025-01-14 03:47:24 +00:00
let isFocused = document.visibilityState !== 'visible';
if (window.electronAPI) {
2025-01-14 03:53:00 +00:00
const res = await window.electronAPI.send({
2025-01-14 03:47:24 +00:00
type: 'window:isFocused'
});
2025-01-14 03:53:00 +00:00
if (res) {
isFocused = res.isFocused;
}
2025-01-14 03:47:24 +00:00
}
if ((!channel || isFocused) && event?.user?.id !== $user?.id) {
2024-12-25 01:25:59 +00:00
await tick();
const type = event?.data?.type ?? null;
const data = event?.data?.data ?? null;
if ($channels) {
2025-11-27 12:27:32 +00:00
if ($channels.find((ch) => ch.id === event.channel_id)) {
channels.set(
$channels.map((ch) => {
if (ch.id === event.channel_id) {
if (type === 'message') {
return {
...ch,
unread_count: (ch.unread_count ?? 0) + 1,
last_message_at: event.created_at
};
}
}
2025-11-27 12:27:32 +00:00
return ch;
})
);
} else {
await channels.set(
(await getChannels(localStorage.token)).sort((a, b) =>
a.type === b.type ? 0 : a.type === 'dm' ? 1 : -1
)
);
}
}
2024-12-25 01:25:59 +00:00
if (type === 'message') {
if ($isLastActiveTab) {
if ($settings?.notificationEnabled ?? false) {
2025-05-01 12:39:36 +00:00
new Notification(`${data?.user?.name} (#${event?.channel?.name}) • Open WebUI`, {
body: data?.content,
2025-11-21 01:43:59 +00:00
icon: `${WEBUI_API_BASE_URL}/users/${data?.user?.id}/profile/image`
});
}
2025-01-04 10:15:57 +00:00
}
2024-12-25 01:25:59 +00:00
toast.custom(NotificationToast, {
componentProps: {
onClick: () => {
goto(`/channels/${event.channel_id}`);
},
content: data?.content,
2025-09-15 20:12:01 +00:00
title: `#${event?.channel?.name}`
2024-12-25 01:25:59 +00:00
},
duration: 15000,
unstyled: true
});
}
}
};
2025-05-22 21:08:28 +00:00
const TOKEN_EXPIRY_BUFFER = 60; // seconds
2025-04-23 18:16:46 +00:00
const checkTokenExpiry = async () => {
2025-04-23 18:12:22 +00:00
const exp = $user?.expires_at; // token expiry time in unix timestamp
const now = Math.floor(Date.now() / 1000); // current time in unix timestamp
if (!exp) {
// If no expiry time is set, do nothing
return;
}
2025-05-22 21:08:28 +00:00
if (now >= exp - TOKEN_EXPIRY_BUFFER) {
2025-05-16 20:38:39 +00:00
const res = await userSignOut();
2025-04-23 18:16:46 +00:00
user.set(null);
2025-04-23 18:12:22 +00:00
localStorage.removeItem('token');
2025-05-16 20:38:39 +00:00
location.href = res?.redirect_url ?? '/auth';
2025-04-23 18:12:22 +00:00
}
};
2023-11-19 00:47:12 +00:00
onMount(async () => {
2025-08-27 00:16:02 +00:00
let touchstartY = 0;
function isNavOrDescendant(el) {
const nav = document.querySelector('nav'); // change selector if needed
return nav && (el === nav || nav.contains(el));
}
document.addEventListener('touchstart', (e) => {
if (!isNavOrDescendant(e.target)) return;
touchstartY = e.touches[0].clientY;
});
document.addEventListener('touchmove', (e) => {
if (!isNavOrDescendant(e.target)) return;
const touchY = e.touches[0].clientY;
const touchDiff = touchY - touchstartY;
if (touchDiff > 50 && window.scrollY === 0) {
showRefresh = true;
e.preventDefault();
}
});
document.addEventListener('touchend', (e) => {
if (!isNavOrDescendant(e.target)) return;
if (showRefresh) {
showRefresh = false;
location.reload();
}
});
2025-11-19 08:51:10 +00:00
if (typeof window !== 'undefined') {
if (window.applyTheme) {
window.applyTheme();
}
2025-02-16 05:04:07 +00:00
}
2025-01-14 03:18:32 +00:00
if (window?.electronAPI) {
2025-01-22 17:42:40 +00:00
const info = await window.electronAPI.send({
type: 'app:info'
2025-01-14 03:18:32 +00:00
});
2025-01-22 17:42:40 +00:00
if (info) {
2025-01-14 03:18:32 +00:00
isApp.set(true);
2025-01-22 17:42:40 +00:00
appInfo.set(info);
const data = await window.electronAPI.send({
type: 'app:data'
});
if (data) {
appData.set(data);
}
2025-01-14 03:18:32 +00:00
}
}
// Listen for messages on the BroadcastChannel
bc.onmessage = (event) => {
if (event.data === 'active') {
isLastActiveTab.set(false); // Another tab became active
}
};
// Set yourself as the last active tab when this tab is focused
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
isLastActiveTab.set(true); // This tab is now the active tab
bc.postMessage('active'); // Notify other tabs that this tab is active
2025-05-22 21:08:28 +00:00
// Check token expiry when the tab becomes active
checkTokenExpiry();
}
};
// Add event listener for visibility state changes
document.addEventListener('visibilitychange', handleVisibilityChange);
// Call visibility change handler initially to set state on load
handleVisibilityChange();
2024-01-02 00:05:05 +00:00
theme.set(localStorage.theme);
2024-05-14 22:26:53 +00:00
mobile.set(window.innerWidth < BREAKPOINT);
2024-05-14 22:26:53 +00:00
const onResize = () => {
if (window.innerWidth < BREAKPOINT) {
mobile.set(true);
} else {
mobile.set(false);
}
};
window.addEventListener('resize', onResize);
2025-11-19 08:51:10 +00:00
user.subscribe(async (value) => {
if (value) {
2025-10-02 09:09:17 +00:00
$socket?.off('events', chatEventHandler);
$socket?.off('events:channel', channelEventHandler);
2025-10-02 09:09:17 +00:00
$socket?.on('events', chatEventHandler);
$socket?.on('events:channel', channelEventHandler);
2025-05-22 21:11:44 +00:00
2025-11-19 08:51:10 +00:00
const userSettings = await getUserSettings(localStorage.token);
if (userSettings) {
settings.set(userSettings.ui);
} else {
settings.set(JSON.parse(localStorage.getItem('settings') ?? '{}'));
}
setTextScale($settings?.textScale ?? 1);
2025-05-22 21:11:44 +00:00
// Set up the token expiry check
if (tokenTimer) {
clearInterval(tokenTimer);
}
tokenTimer = setInterval(checkTokenExpiry, 15000);
2025-03-04 04:34:45 +00:00
} else {
2025-10-02 09:09:17 +00:00
$socket?.off('events', chatEventHandler);
$socket?.off('events:channel', channelEventHandler);
}
});
2024-05-13 15:00:30 +00:00
let backendConfig = null;
try {
backendConfig = await getBackendConfig();
console.log('Backend config:', backendConfig);
2024-05-13 15:00:30 +00:00
} catch (error) {
console.error('Error loading backend config:', error);
2024-05-13 15:00:30 +00:00
}
// Initialize i18n even if we didn't get a backend config,
// so `/error` can show something that's not `undefined`.
2024-05-26 07:17:20 +00:00
2025-03-05 22:54:48 +00:00
initI18n(localStorage?.locale);
2024-06-30 21:48:05 +00:00
if (!localStorage.locale) {
2024-06-30 21:52:18 +00:00
const languages = await getLanguages();
const browserLanguages = navigator.languages
? navigator.languages
: [navigator.language || navigator.userLanguage];
const lang = backendConfig.default_locale
? backendConfig.default_locale
: bestMatchingLanguage(languages, browserLanguages, 'en-US');
changeLanguage(lang);
dayjs.locale(lang);
2024-06-30 21:48:05 +00:00
}
2023-11-19 00:47:12 +00:00
2023-12-26 19:32:22 +00:00
if (backendConfig) {
2023-12-26 19:34:14 +00:00
// Save Backend Status to Store
2023-12-26 19:32:22 +00:00
await config.set(backendConfig);
2024-02-24 01:12:19 +00:00
await WEBUI_NAME.set(backendConfig.name);
2023-11-19 00:47:12 +00:00
2023-12-26 06:14:06 +00:00
if ($config) {
2025-05-09 10:20:43 +00:00
await setupSocket($config.features?.enable_websocket ?? true);
const currentUrl = `${window.location.pathname}${window.location.search}`;
const encodedUrl = encodeURIComponent(currentUrl);
2023-11-19 00:47:12 +00:00
if (localStorage.token) {
2023-12-26 06:14:06 +00:00
// Get Session User Info
2023-12-26 19:32:22 +00:00
const sessionUser = await getSessionUser(localStorage.token).catch((error) => {
2025-01-21 06:41:32 +00:00
toast.error(`${error}`);
2023-12-26 19:32:22 +00:00
return null;
});
2023-11-19 00:47:12 +00:00
2023-12-26 06:14:06 +00:00
if (sessionUser) {
await user.set(sessionUser);
2024-08-19 14:49:40 +00:00
await config.set(await getBackendConfig());
2023-11-19 05:41:43 +00:00
} else {
2023-12-26 19:34:14 +00:00
// Redirect Invalid Session User to /auth Page
2023-11-19 05:41:43 +00:00
localStorage.removeItem('token');
await goto(`/auth?redirect=${encodedUrl}`);
2023-11-19 05:41:43 +00:00
}
2023-11-19 00:47:12 +00:00
} else {
// Don't redirect if we're already on the auth page
// Needed because we pass in tokens from OAuth logins via URL fragments
if ($page.url.pathname !== '/auth') {
await goto(`/auth?redirect=${encodedUrl}`);
}
2023-11-19 00:47:12 +00:00
}
}
2023-12-26 06:14:06 +00:00
} else {
2023-12-26 19:34:14 +00:00
// Redirect to /error when Backend Not Detected
2023-12-26 06:14:06 +00:00
await goto(`/error`);
2023-11-19 00:47:12 +00:00
}
await tick();
2024-04-27 22:59:20 +00:00
2024-06-12 07:05:20 +00:00
if (
document.documentElement.classList.contains('her') &&
document.getElementById('progress-bar')
) {
loadingProgress.subscribe((value) => {
2024-06-12 07:16:54 +00:00
const progressBar = document.getElementById('progress-bar');
if (progressBar) {
2024-06-12 10:13:59 +00:00
progressBar.style.width = `${value}%`;
2024-06-12 07:16:54 +00:00
}
2024-06-12 07:05:20 +00:00
});
await loadingProgress.set(100);
document.getElementById('splash-screen')?.remove();
const audio = new Audio(`/audio/greeting.mp3`);
const playAudio = () => {
audio.play();
document.removeEventListener('click', playAudio);
};
document.addEventListener('click', playAudio);
loaded = true;
} else {
document.getElementById('splash-screen')?.remove();
loaded = true;
}
2024-05-14 22:26:53 +00:00
return () => {
window.removeEventListener('resize', onResize);
};
2023-11-19 00:47:12 +00:00
});
2023-10-08 22:38:42 +00:00
</script>
<svelte:head>
2024-02-24 01:12:19 +00:00
<title>{$WEBUI_NAME}</title>
2024-05-17 03:49:28 +00:00
<link crossorigin="anonymous" rel="icon" href="{WEBUI_BASE_URL}/static/favicon.png" />
2025-09-15 16:05:26 +00:00
<meta name="apple-mobile-web-app-title" content={$WEBUI_NAME} />
<meta name="description" content={$WEBUI_NAME} />
<link
rel="search"
type="application/opensearchdescription+xml"
title={$WEBUI_NAME}
href="/opensearch.xml"
crossorigin="use-credentials"
/>
2023-10-08 22:38:42 +00:00
</svelte:head>
2023-11-19 00:47:12 +00:00
2025-08-27 00:16:02 +00:00
{#if showRefresh}
<div class=" py-5">
<Spinner className="size-5" />
</div>
{/if}
2023-12-26 06:14:06 +00:00
{#if loaded}
2025-01-14 03:18:32 +00:00
{#if $isApp}
<div class="flex flex-row h-screen">
2025-01-19 01:50:03 +00:00
<AppSidebar />
2025-01-14 03:18:32 +00:00
2025-01-14 04:21:47 +00:00
<div class="w-full flex-1 max-w-[calc(100%-4.5rem)]">
2025-01-14 03:18:32 +00:00
<slot />
</div>
</div>
{:else}
<slot />
{/if}
2023-11-19 00:47:12 +00:00
{/if}
2023-12-26 06:14:06 +00:00
2024-09-24 10:40:13 +00:00
<Toaster
theme={$theme.includes('dark')
? 'dark'
: $theme === 'system'
? window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
: 'light'}
richColors
2024-12-19 23:14:09 +00:00
position="top-right"
2025-04-18 11:33:18 +00:00
closeButton
2024-09-24 10:40:13 +00:00
/>