This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-26 02:04:30 +04:00
1 parent 9c9a3ca0d6
commit 4b648ec4e7
19 files changed
+586 -20

No files matched your search

+1
View File
@@ -108,6 +108,7 @@ class SessionUserResponse(Token, UserProfileImageResponse):
class SessionUserInfoResponse(SessionUserResponse, UserStatus):
profile_banner_image_url: str | None = None
bio: str | None = None
gender: str | None = None
date_of_birth: dt.date | None = None
+1
View File
@@ -326,6 +326,7 @@ class UserInfoResponse(UserStatus):
name: str
email: str
role: str
profile_banner_image_url: str | None = None
bio: str | None = None
last_active_at: int | None = None
timezone: str | None = None
+1
View File
@@ -238,6 +238,7 @@ async def get_session_user(
'name': user.name,
'role': user.role,
'profile_image_url': user.profile_image_url,
'profile_banner_image_url': user.profile_banner_image_url,
'bio': user.bio,
'gender': user.gender,
'date_of_birth': user.date_of_birth,
+102 -1
View File
@@ -1,6 +1,8 @@
from __future__ import annotations
import asyncio
import base64
import io
import logging
import time
from collections import Counter
@@ -8,7 +10,7 @@ from copy import deepcopy
from datetime import datetime, timedelta
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
from fastapi.responses import FileResponse, Response
from open_webui.config import DEFAULT_USER_PERMISSIONS
from open_webui.constants import ERROR_MESSAGES
@@ -19,6 +21,7 @@ from open_webui.models.auths import ApiKey, Auths
from open_webui.models.config import Config
from open_webui.models.chat_messages import ChatMessages
from open_webui.models.chats import Chats
from open_webui.models.files import Files
from open_webui.models.groups import Groups
from open_webui.models.oauth_sessions import OAuthSessions
from open_webui.models.users import (
@@ -38,6 +41,7 @@ from open_webui.models.access_grants import AccessGrants
from open_webui.models.knowledge import Knowledges
from open_webui.models.models import Models
from open_webui.models.tools import Tools
from open_webui.storage.provider import Storage
from open_webui.tasks import stop_item_tasks
from open_webui.utils.access_control import fill_missing_permissions, get_permissions, has_permission
from open_webui.utils.auth import (
@@ -49,8 +53,10 @@ from open_webui.utils.auth import (
validate_password,
)
from open_webui.utils.chat_variables import ChatVariablesError, normalize_user_variables, validate_user_variables
from open_webui.utils.validate import BACKGROUND_IMAGE_MAX_BYTES, validate_background_image
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.datastructures import Headers
log = logging.getLogger(__name__)
@@ -609,6 +615,80 @@ async def update_user_status_by_session_user(
)
# Update User Profile Banner By Session User
class UserProfileBannerResponse(BaseModel):
profile_banner_image_url: str | None = None
async def set_profile_banner(request: Request, user: UserModel, url: str | None, db: AsyncSession):
from open_webui.routers.files import delete_file_by_id
# Read the current banner here, as the authenticated user may be stale.
current = await Users.get_user_by_id(user.id, db=db)
updated = await Users.update_user_by_id(user.id, {'profile_banner_image_url': url}, db=db)
if not current or not updated:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.USER_NOT_FOUND,
)
if current.profile_banner_image_url:
try:
await delete_file_by_id(request, current.profile_banner_image_url.split('/')[-2], user=user, db=db)
except HTTPException as e:
log.warning('Could not delete the previous profile banner: %s', e.detail)
await publish_event(
request,
EVENTS.USER_PROFILE_UPDATED,
actor=user,
subject_id=user.id,
data={'updated_fields': ['profile_banner_image_url']},
)
return updated
@router.post('/user/profile/banner', response_model=UserProfileBannerResponse)
async def update_user_profile_banner_by_session_user(
request: Request,
file: UploadFile = File(...),
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
from open_webui.routers.files import upload_file_handler
data = await file.read(BACKGROUND_IMAGE_MAX_BYTES + 1)
try:
content_type = await asyncio.to_thread(validate_background_image, data)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
uploaded = await upload_file_handler(
request,
file=UploadFile(
file=io.BytesIO(data),
filename=f'banner.{content_type.split("/")[1]}',
headers=Headers({'content-type': content_type}),
),
metadata=None,
process=False,
user=user,
db=db,
)
return await set_profile_banner(request, user, f'/api/v1/files/{uploaded.id}/content', db)
@router.delete('/user/profile/banner', response_model=UserProfileBannerResponse)
async def delete_user_profile_banner_by_session_user(
request: Request,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
return await set_profile_banner(request, user, None, db)
# Get User Info By Session User
@@ -873,6 +953,27 @@ async def get_user_profile_image_by_id(user_id: str, user=Depends(get_verified_u
)
# Get User Profile Banner By Id
@router.get('/{user_id}/profile/banner')
async def get_user_profile_banner_by_id(
user_id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
):
profile = await Users.get_user_by_id(user_id, db=db)
url = profile.profile_banner_image_url if profile else None
file = await Files.get_file_by_id(url.split('/')[-2], db=db) if url else None
media_type = (file.meta or {}).get('content_type') if file else None
if not file or file.user_id != user_id or media_type not in PROFILE_IMAGE_ALLOWED_MIME_TYPES:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
return FileResponse(
await asyncio.to_thread(Storage.get_file, file.path),
media_type=media_type,
headers={'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-cache'},
)
# Get User Active Status By Id
+15
View File
@@ -360,6 +360,21 @@ export const getUserInfoById = async (token: string, userId: string) => {
return res;
};
// Sets the session user's profile banner, or removes it when no image is given.
export const updateUserBanner = async (token: string, image: File | null) => {
const data = new FormData();
if (image) data.append('file', image);
const res = await fetch(`${WEBUI_API_BASE_URL}/users/user/profile/banner`, {
method: image ? 'POST' : 'DELETE',
headers: { Authorization: `Bearer ${token}` },
...(image ? { body: data } : {})
});
const body = await res.json();
if (!res.ok) throw body.detail;
return body as { profile_banner_image_url: string | null };
};
export const updateUserStatus = async (token: string, formData: object) => {
let error = null;
+228
View File
@@ -0,0 +1,228 @@
<script lang="ts">
import { getContext } from 'svelte';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import dayjs, { getDayjsLocale } from '$lib/dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
import { config, showSettings, user as sessionUser } from '$lib/stores';
import type { AppLayoutContext } from '$lib/types';
import { WEBUI_API_BASE_URL } from '$lib/constants';
import { getDMChannelByUserId } from '$lib/apis/channels';
import { getUserInfoById } from '$lib/apis/users';
import Emoji from '$lib/components/common/Emoji.svelte';
import Modal from '$lib/components/common/Modal.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import XMark from '$lib/components/icons/XMark.svelte';
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
const appLayout = getContext<AppLayoutContext | undefined>('appLayout');
export let userId: string | null = null;
let user: any = null;
let failed = false;
const loadUser = async (id: string) => {
user = null;
failed = false;
const loadedUser = await getUserInfoById(localStorage.token, id).catch(() => null);
if (userId !== id) return;
user = loadedUser;
failed = !loadedUser;
};
$: if (userId) loadUser(userId);
$: isSelf = !!user && $sessionUser?.id === user.id;
$: canMessage =
!!user &&
!isSelf &&
$config?.features?.enable_channels &&
($sessionUser?.role === 'admin' || ($sessionUser?.permissions?.features?.channels ?? true));
$: groups = ((user?.groups ?? []) as { name: string }[]).map((group) => group.name).join(', ');
$: localTime = getLocalTime(user?.timezone, $i18n.language);
$: lastSeen =
!user?.is_active && user?.last_active_at
? dayjs(user.last_active_at * 1000)
.locale(getDayjsLocale($i18n.language) ?? 'en')
.fromNow()
: '';
const getLocalTime = (timeZone: string | null | undefined, language: string) => {
if (!timeZone) return '';
try {
return new Date().toLocaleTimeString(language, {
timeZone,
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short'
});
} catch {
// Older profiles may contain a timezone the browser cannot resolve.
return '';
}
};
const close = () => (userId = null);
const sendMessage = async () => {
const channel = await getDMChannelByUserId(localStorage.token, user.id).catch((error) => {
toast.error(`${error}`);
return null;
});
if (!channel) return;
const href = `/channels/${channel.id}`;
close();
showSettings.set(false);
if (appLayout?.openPageTab) appLayout.openPageTab({ href, label: '' });
else goto(href);
};
const rowClass =
'grid grid-cols-[7rem_minmax(0,1fr)] items-start gap-2 text-base-900 dark:text-base-100';
const labelClass = 'text-base-600 dark:text-base-400';
</script>
<Modal
size="sm"
className="bg-base-0 dark:bg-base-900 rounded-4xl overflow-hidden !border-0"
show={!!userId}
ariaLabel={$i18n.t('Profile')}
onRequestClose={close}
>
<div class="relative flex max-h-[calc(100dvh-3rem)] flex-col">
<button
type="button"
aria-label={$i18n.t('Close')}
class="absolute end-4 top-3 z-10 rounded-lg py-1 transition px-0 {user?.profile_banner_image_url
? 'text-base-0 drop-shadow-sm hover:text-base-0/80'
: 'text-base-500 hover:text-base-700 dark:text-base-400 dark:hover:text-base-200'}"
on:click={close}
>
<XMark className="size-4" />
</button>
{#if user}
<div class="min-h-0 overflow-y-auto scrollbar-hover pb-5">
<!-- The model editor header, edge to edge. -->
<div class="relative w-full {user.profile_banner_image_url ? 'h-36' : 'h-20'}">
{#if user.profile_banner_image_url}
<img
src={`${WEBUI_API_BASE_URL}/users/${user.id}/profile/banner?v=${encodeURIComponent(user.profile_banner_image_url)}`}
alt=""
class="[mask-image:linear-gradient(to_bottom,black_15%,rgba(0,0,0,0.65)_40%,transparent_85%)] absolute inset-0 h-full w-full object-cover"
on:error={() => (user = { ...user, profile_banner_image_url: null })}
/>
{:else}
<div
aria-hidden="true"
class="[mask-image:linear-gradient(to_bottom,black_15%,rgba(0,0,0,0.65)_40%,transparent_85%)] absolute inset-0 h-full w-full bg-base-100 dark:bg-base-850"
></div>
{/if}
</div>
<div
class="relative flex min-w-0 items-center gap-3.5 px-5 pb-1 {user.profile_banner_image_url
? '-mt-14'
: '-mt-9'}"
>
<img
src={`${WEBUI_API_BASE_URL}/users/${user.id}/profile/image`}
alt=""
class="size-12 shrink-0 rounded-full bg-base-50 object-cover ring-1 ring-base-200/70 dark:bg-base-850 dark:ring-base-0/10"
/>
<div class="min-w-0 flex-1">
<div
class="break-words text-base leading-tight text-base-900 dark:text-base-0 md:text-lg"
>
{user.name}
</div>
<div class="flex items-center gap-1.5 py-0.5 text-xs text-base-500">
<span
class="size-1.5 shrink-0 rounded-full {user.is_active
? 'bg-green-500'
: 'bg-base-400'}"
aria-hidden="true"
></span>
{user.is_active ? $i18n.t('Active') : $i18n.t('Away')}
</div>
</div>
{#if canMessage}
<button
type="button"
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-base-900 px-2.5 text-xs font-normal text-base-0 transition hover:bg-base-1000 disabled:opacity-60 dark:bg-base-100 dark:text-base-900 dark:hover:bg-base-0"
on:click={sendMessage}
>
{$i18n.t('Message')}
</button>
{:else if isSelf}
<button
type="button"
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-base-100 px-2.5 text-xs font-normal text-base-800 transition hover:bg-base-100/70 disabled:opacity-60 dark:bg-base-850 dark:text-base-0 dark:hover:bg-base-850/60"
on:click={() => {
close();
showSettings.set('account');
}}
>
{$i18n.t('Edit')}
</button>
{/if}
</div>
{#if user.bio}
<div
class="mt-3 whitespace-pre-line break-words px-5 text-[0.8125rem] font-normal text-base-900 dark:text-base-100"
>
{user.bio}
</div>
{/if}
{#if user.status_emoji || user.status_message || localTime || lastSeen || groups}
<dl class="mt-3 flex flex-col gap-2 px-5 text-xs font-normal">
{#if user.status_emoji || user.status_message}
<div class={rowClass}>
<dt class={labelClass}>{$i18n.t('Status')}</dt>
<dd class="flex min-w-0 items-start gap-1.5">
{#if user.status_emoji}
<span class="flex h-4 shrink-0 items-center">
<Emoji className="size-3.5" shortCode={user.status_emoji} />
</span>
{/if}
<span class="min-w-0 break-words">{user.status_message ?? ''}</span>
</dd>
</div>
{/if}
{#if localTime}
<div class={rowClass}>
<dt class={labelClass}>{$i18n.t('Local time')}</dt>
<dd>{localTime}</dd>
</div>
{/if}
{#if lastSeen}
<div class={rowClass}>
<dt class={labelClass}>{$i18n.t('Last seen')}</dt>
<dd>{lastSeen}</dd>
</div>
{/if}
{#if groups}
<div class={rowClass}>
<dt class={labelClass}>{$i18n.t('Groups')}</dt>
<dd class="min-w-0 break-words">{groups}</dd>
</div>
{/if}
</dl>
{/if}
</div>
{:else if failed}
<div class="py-12 text-center text-xs text-base-500">{$i18n.t('Unknown user')}</div>
{:else}
<div class="flex justify-center py-12"><Spinner className="size-5" /></div>
{/if}
</div>
</Modal>
@@ -16,8 +16,10 @@
import { getContext, tick } from 'svelte';
const i18n = getContext<Writable<i18nType>>('i18n');
const appLayout = getContext<AppLayoutContext | undefined>('appLayout');
import { formatDate } from '$lib/utils';
import type { AppLayoutContext } from '$lib/types';
import { settings, user, shortCodesToEmojis, models } from '$lib/stores';
import { WEBUI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';
@@ -542,6 +544,14 @@
>
{#if message?.meta?.model_id}
{message?.meta?.model_name ?? message?.meta?.model_id}
{:else if message.user?.id && !message.app_id && message.user.role !== 'webhook'}
<button
type="button"
class="max-w-full truncate align-bottom font-medium hover:underline"
on:click={() => appLayout?.openProfile?.(message.user.id)}
>
{message.user.name}
</button>
{:else}
{message?.user?.name}
{/if}
@@ -13,8 +13,10 @@
import { LinkPreview } from 'bits-ui';
import { getContext, onDestroy } from 'svelte';
import { user as sessionUser } from '$lib/stores';
import type { AppLayoutContext } from '$lib/types';
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
const appLayout = getContext<AppLayoutContext | undefined>('appLayout');
import UserStatusLinkPreview from './UserStatusLinkPreview.svelte';
export let user: { id?: string | null; name?: string | null } | null = null;
@@ -25,6 +27,8 @@
export let sideOffset = 8;
export let openPreview = false;
// Replaces opening the profile.
export let onClick: ((userId: string) => void) | null = null;
const closeProfilePreview = () => {
if (openPreview) {
@@ -54,7 +58,13 @@
{...props}
type="button"
aria-label={user.name || $i18n.t('User')}
onclick={() => (openPreview = !openPreview)}
onclick={(event: MouseEvent & { currentTarget: HTMLButtonElement }) => {
const open = onClick ?? appLayout?.openProfile;
openPreview = open ? false : !openPreview;
// Getting focus back from the dialog after a mouse click would reopen the preview.
if (open && event.detail) event.currentTarget.blur();
if (user.id) open?.(user.id);
}}
>
<slot />
</button>
@@ -3,6 +3,7 @@
const { goto } = getPageContext();
import { getContext, onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import dayjs, { getDayjsLocale } from '$lib/dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
@@ -76,6 +77,7 @@
const res = await getDMChannelByUserId(localStorage.token, user.id).catch((error) => {
console.error('Error fetching DM channel:', error);
toast.error(`${error}`);
return null;
});
+33 -2
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { getPageContext } from '$lib/utils/page';
const { goto, url: pageUrl } = getPageContext();
const { goto, url: pageUrl, active } = getPageContext();
import { socket, user } from '$lib/stores';
@@ -29,7 +29,7 @@
let messagesContainerElement = null;
let replyToMessage = null;
let replyToMessage: any = null;
let typingUsers = [];
let typingUsersTimeout = {};
@@ -232,8 +232,39 @@
$socket?.off('events:channel', channelEventHandler);
});
let threadRoot: HTMLDivElement;
// Runs before the thread's own Escape handlers, so what they close is still there to see.
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.isComposing || !(event.target instanceof Element)) return;
const inThread = threadRoot?.contains(event.target);
const unfocused =
$active &&
event.target === document.body &&
!document.querySelector('.modal, [role="menu"], [role="listbox"]');
if (!inThread && !unfocused) return;
// Suggestions, voice recording, message editing and open menus handle Escape themselves.
if (
document.getElementById('suggestions-container') ||
document.querySelector('[data-voice-recording]') ||
event.target.closest('textarea') ||
threadRoot?.querySelector('[aria-haspopup][aria-expanded="true"]')
)
return;
event.preventDefault();
event.stopPropagation();
if (replyToMessage) {
replyToMessage = null;
} else {
onClose();
}
};
</script>
<svelte:window on:keydown|capture={onKeyDown} />
{#if channel}
<div
bind:this={threadRoot}
@@ -490,6 +490,7 @@
<div
bind:this={containerElement}
bind:clientWidth={containerWidth}
data-voice-recording
class="flex items-center gap-3 overflow-hidden rounded-3xl border border-base-200/60 bg-base-0/80 px-2 py-2 shadow-[0_6px_24px_-4px_rgba(0,0,0,0.1)] backdrop-blur-md dark:border-base-800/40 dark:bg-[color-mix(in_oklab,var(--color-base-850)_55%,var(--color-base-900))]/90 {className}"
>
<button
@@ -153,8 +153,10 @@
on:click={async () => {
if (triggerChar === '@') {
if (idType === 'U') {
// Open user profile
console.log('Clicked user mention', id);
if (appLayout?.openProfile && !userUnavailable) {
openPreview = false;
appLayout.openProfile(id);
}
} else if (idType === 'M') {
console.log('Clicked model mention', id);
await goto(`/?model=${id}`);
@@ -11,7 +11,8 @@
getAPIKey,
getSessionUser
} from '$lib/apis/auths';
import { getUserVariables, updateUserVariables } from '$lib/apis/users';
import { getUserVariables, updateUserBanner, updateUserVariables } from '$lib/apis/users';
import { WEBUI_API_BASE_URL } from '$lib/constants';
import UpdatePassword from './Account/UpdatePassword.svelte';
import Mfa from './Account/Mfa.svelte';
@@ -28,6 +29,7 @@
import Textarea from '$lib/components/common/Textarea.svelte';
import Modal from '$lib/components/common/Modal.svelte';
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
import UserProfileBanner from './Account/UserProfileBanner.svelte';
import UserProfileImage from './Account/UserProfileImage.svelte';
import UserSettingField from './UserSettingField.svelte';
import UserSettingRow from './UserSettingRow.svelte';
@@ -39,6 +41,9 @@
export let saveHandler: () => void | Promise<void>;
let profileImageUrl = '';
let savedBannerUrl: string | null = null;
let bannerUrl: string | null = null;
let bannerFile: File | null = null;
let name = '';
let bio = '';
@@ -135,6 +140,23 @@
return variables;
};
const bannerSrc = (userId: string, url: string | null) =>
url
? `${WEBUI_API_BASE_URL}/users/${userId}/profile/banner?v=${encodeURIComponent(url)}`
: null;
const saveBanner = async () => {
if (!bannerFile && bannerUrl === savedBannerUrl) return true;
const res = await updateUserBanner(localStorage.token, bannerFile).catch((error) => {
toast.error(`${error}`);
return null;
});
if (!res) return false;
savedBannerUrl = bannerUrl = bannerSrc($user?.id ?? '', res.profile_banner_image_url);
bannerFile = null;
return true;
};
const submitHandler = async () => {
let variables: Record<string, string>;
try {
@@ -160,12 +182,14 @@
toast.error(`${error}`);
});
const bannerSaved = await saveBanner();
const variablesRes = await updateUserVariables(localStorage.token, variables).catch((error) => {
toast.error(`${error}`);
return null;
});
if (updatedUser && variablesRes) {
if (updatedUser && bannerSaved && variablesRes) {
setVariableRows(variablesRes.variables ?? {});
// Get Session User Info
const sessionUser = await getSessionUser(localStorage.token).catch((error) => {
@@ -209,6 +233,7 @@
if (user) {
name = user?.name ?? '';
profileImageUrl = user?.profile_image_url ?? '';
savedBannerUrl = bannerUrl = bannerSrc(user.id, user?.profile_banner_image_url ?? null);
bio = user?.bio ?? '';
gender = user?.gender ?? '';
@@ -254,12 +279,14 @@
</h2>
<UserSettingSection title={$i18n.t('settings.personal.account.sections.profile.title')} first>
<UserProfileImage
bind:profileImageUrl
user={$user}
variant="account"
displayName={$user?.name}
/>
<UserProfileBanner bind:src={bannerUrl} bind:file={bannerFile}>
<UserProfileImage
bind:profileImageUrl
user={$user}
variant="account"
displayName={$user?.name}
/>
</UserProfileBanner>
<UserSettingField
label={$i18n.t('settings.personal.account.name.label')}
@@ -0,0 +1,120 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { getContext, onDestroy } from 'svelte';
import Photo from '$lib/components/icons/Photo.svelte';
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
// The saved banner, cleared by Remove.
export let src: string | null = null;
// A new image, uploaded when the settings are saved.
export let file: File | null = null;
let input: HTMLInputElement;
let preview: string | null = null;
const setFile = (selected: File | null) => {
if (preview) URL.revokeObjectURL(preview);
preview = selected ? URL.createObjectURL(selected) : null;
file = selected;
};
onDestroy(() => {
if (preview) URL.revokeObjectURL(preview);
});
// Saved: the parent has uploaded the file and cleared it.
$: if (!file && preview) setFile(null);
const selectHandler = async () => {
const selected = input.files?.[0];
input.value = '';
if (!selected) return;
const candidate = URL.createObjectURL(selected);
try {
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(selected.type))
throw new Error($i18n.t('Background image must be PNG, JPEG, WebP, or GIF.'));
if (selected.size > 5 * 1024 * 1024)
throw new Error($i18n.t('Background image must be at most 5 MiB.'));
const image = new Image();
image.src = candidate;
await image.decode().catch(() => {
throw new Error($i18n.t('Invalid background image.'));
});
if (image.naturalWidth * image.naturalHeight > 25_000_000)
throw new Error($i18n.t('Background image must be at most 25 megapixels.'));
setFile(selected);
} catch (error) {
toast.error((error as Error).message);
} finally {
URL.revokeObjectURL(candidate);
}
};
const buttonClass =
'rounded-md px-1 py-1 text-xs font-normal text-base-500 transition hover:text-base-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 dark:text-base-400 dark:hover:text-base-300';
</script>
<input
bind:this={input}
type="file"
accept="image/png,image/jpeg,image/webp,image/gif"
hidden
on:change={selectHandler}
/>
<!-- Same header as the model editor. -->
<div>
<div class="relative w-full {(preview ?? src) ? 'h-36' : 'h-20'}">
{#if preview ?? src}
<img
src={preview ?? src}
alt=""
class="[mask-image:linear-gradient(to_bottom,black_15%,rgba(0,0,0,0.65)_40%,transparent_85%)] absolute inset-0 h-full w-full rounded-xl object-cover"
/>
{:else}
<div
aria-hidden="true"
class="[mask-image:linear-gradient(to_bottom,black_15%,rgba(0,0,0,0.65)_40%,transparent_85%)] absolute inset-0 h-full w-full rounded-xl bg-base-100 dark:bg-base-850"
></div>
{/if}
</div>
<div
class="relative flex min-w-0 flex-wrap items-center justify-between gap-x-3 px-3 {(preview ??
src)
? '-mt-14'
: '-mt-9'}"
>
<slot />
<div
class="flex shrink-0 items-center gap-1"
title={$i18n.t('PNG, JPEG, WebP, or GIF. Up to 5 MiB and 25 megapixels.')}
>
{#if preview ?? src}
<button type="button" class={buttonClass} on:click={() => input.click()}
>{$i18n.t('Change')}</button
>
<button
type="button"
class={buttonClass}
on:click={() => {
setFile(null);
src = null;
}}>{$i18n.t('Remove')}</button
>
{:else}
<button
type="button"
class="flex items-center gap-1.5 {buttonClass}"
on:click={() => input.click()}
>
<Photo className="size-3.5" />
{$i18n.t('Add banner')}
</button>
{/if}
</div>
</div>
</div>
+5 -2
View File
@@ -22,6 +22,7 @@
let transport = 'vnc';
let clipboardAvailable = true;
let audioAvailable = false;
let hideCursor = false;
const send = (message: Record<string, unknown>) => {
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
};
@@ -72,11 +73,13 @@
transport?: string;
audio?: boolean;
clipboard?: boolean;
cursor?: boolean;
}>(target, '/desktop');
if (version !== generation) return;
transport = info.transport ?? 'vnc';
clipboardAvailable = info.clipboard !== false;
audioAvailable = info.audio === true;
hideCursor = info.cursor === true;
await tick();
if (version !== generation) return;
if (transport === 'frames') {
@@ -151,7 +154,7 @@
};
const paste = (text: string, shift = false) => {
if (transport === 'frames' || !clipboardAvailable) {
send({ type: 'paste', text });
send({ type: 'paste', text, shift });
return;
}
if (!viewer) return;
@@ -204,7 +207,7 @@
}
}}
>
{#if transport === 'frames'}<NativeDesktop bind:this={native} {send} />{/if}
{#if transport === 'frames'}<NativeDesktop bind:this={native} {send} {hideCursor} />{/if}
</div>
{#if status || error}
<div
@@ -2,6 +2,8 @@
import { onDestroy } from 'svelte';
import FrameCanvas from './FrameCanvas.svelte';
export let send: (message: Record<string, unknown>) => void;
// The picture already includes the host's cursor.
export let hideCursor = false;
let surface: HTMLDivElement;
let frames: FrameCanvas;
let pending: Record<string, unknown> | null = null;
@@ -51,6 +53,9 @@
event.preventDefault();
flush();
send({ type: 'key', code: event.code, down });
// macOS never reports the release of a key pressed while Command is held.
if (down && event.metaKey && !/^(Meta|Shift|Control|Alt)/.test(event.code))
send({ type: 'key', code: event.code, down: false });
};
onDestroy(release);
</script>
@@ -59,7 +64,9 @@
<div
bind:this={surface}
class="flex h-full w-full touch-none items-center justify-center overflow-hidden outline-none"
class="flex h-full w-full touch-none items-center justify-center overflow-hidden outline-none {hideCursor
? '[&>canvas]:cursor-none'
: ''}"
role="application"
aria-label="Desktop screen"
tabindex="0"
@@ -23,7 +23,7 @@
let showEditChannelModal = false;
let itemElement;
let itemElement: HTMLElement;
const hasPublicReadGrant = (grants: any) =>
Array.isArray(grants) &&
@@ -92,7 +92,7 @@
<div class="flex ml-[0.0625rem] mr-0.5 relative">
{#each channelMembers.slice(0, 2) as u, index}
<div class={index === 1 ? '-ml-2.5' : ''}>
<ProfilePreview user={u}>
<ProfilePreview user={u} onClick={() => itemElement?.querySelector('a')?.click()}>
<img
src={`${WEBUI_API_BASE_URL}/users/${u.id}/profile/image`}
alt={u.name}
+1
View File
@@ -23,6 +23,7 @@ export type MachineContext = {
export type AppLayoutContext = {
openPageTab?: (tab: { href: string; label: string; inSplit?: boolean }) => void;
openProfile?: (userId: string) => void;
initNewChat?: (options?: {
preserveTabs?: boolean;
preserveInput?: boolean;
+6 -1
View File
@@ -53,6 +53,7 @@
import Chat from '$lib/components/chat/Chat.svelte';
import { pageTabKey } from '$lib/components/chat/Tabs/tabs';
import ChangelogModal from '$lib/components/ChangelogModal.svelte';
import UserProfileModal from '$lib/components/UserProfileModal.svelte';
import AccountPending from '$lib/components/layout/Overlay/AccountPending.svelte';
import UpdateInfoToast from '$lib/components/layout/UpdateInfoToast.svelte';
import Modal from '$lib/components/common/Modal.svelte';
@@ -63,7 +64,10 @@
const i18n = getContext('i18n');
const getUserSettings = getContext<(token: string) => Promise<any>>('getUserSettings');
const appLayout = setContext<AppLayoutContext>('appLayout', {});
let profileUserId: string | null = null;
const appLayout = setContext<AppLayoutContext>('appLayout', {
openProfile: (userId) => (profileUserId = userId)
});
let loaded = false;
// Settings (including the admin panels) load on first open, then stay mounted.
@@ -498,6 +502,7 @@
{/await}
{/if}
<ChangelogModal bind:show={$showChangelog} />
<UserProfileModal bind:userId={profileUserId} />
{#if WEBUI_BUILD_CHANNEL === 'main' && version && compareVersion(version.latest, version.current) && ($settings?.showUpdateToast ?? true)}
<div class=" absolute bottom-8 right-8 z-50" in:fade={{ duration: 100 }}>