🖥️ feat: Show Lia on the Welcome Screen (#16684)

* feat: Show Lia on the Welcome Screen

Adds the opt-in Show Lia setting (off by default) and the interface.mascot deployment flag (allowed by default). Lia mounts only on the landing page, loads lazily after first paint, stands on the composer's top edge clear of the greeting, reacts to typing, files and theme changes, and speaks through localized bubbles. She is decorative and hidden from assistive technology.

* fix: Keep Lia's Long-Message Reaction Re-Armed and Pointer Reads Per Frame

Deleting a message back under 280 characters now re-arms the long-message reaction, pointer handling reads layout at most once per animation frame, and the ChatView specs stub Lia like their other children.

* test: Open Settings from the Phone Drawer in the Lia Scenarios

The opt-in scenario no longer resets the stored preference on reload, and both Settings scenarios open the account menu from the mobile drawer on phones.

* fix: Measure Lia's Caret Like the Composer and Label Her When Idle

The caret mirror copies direction, alignment, indentation, wrapping and box sizing, so right-to-left and wrapped text measure like the composer. Hovering Lia between activities now says she is hanging out instead of showing nothing.

* fix: Wave Off Assistants Sends and Keep Lia's Canvas and Bubble Off Welcome Content

* fix: Keep Lia's Speech Bubble Inside Her Stage

* fix: Wrap Long Translations in Lia's Speech Bubble

* fix: Keep Lia's Long-Message Reaction Until It Plays and Pin the Scenario Greeting

* fix: Make Only Lia's Body Clickable So She Fits Beside Long Greetings

* fix: Let Lia Stand Beside the Composer When the Greeting Fills Its Top

* feat: Let Users Drag Lia Around and Keep Her Near the Composer

* test: Cover Picking Lia Up and Setting Her Down on the Composer

* refactor: Keep Lia's Preference Inside Her Feature

* fix: Let Keyboard Users Pet Lia and Move Her With the Arrow Keys

* test: Shift Only the Wall Clock for Lia's Morning Greeting

* test: Measure Lia's Keyboard Walk Both Ways So the Greeting's Width Cannot Pin Her

* fix: Bring Lia Back When a New Chat Opens During Her Farewell

* fix: Start Lia's Reactions on Her Own Clock After a Pause Without Room

* fix: Load Lia Through Stale-Asset Recovery and Skip the Farewell Before She Appears

* feat: Mark the Lia Settings Toggle as Beta
This commit is contained in:
Marco Beretta 2026-10-06 22:55:30 +02:00 • committed by GitHub
parent bcebe1d96a
commit 14c43138c2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 1533 additions and 4 deletions

View file

@ -1,4 +1,4 @@
import { memo, useMemo } from 'react';
import { memo, useMemo, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { useRecoilValue } from 'recoil';
import { useForm } from 'react-hook-form';
@ -38,6 +38,7 @@ import MessagesView from './Messages/MessagesView';
import Presentation from './Presentation';
import ChatForm from './Input/ChatForm';
import { TraceSurface } from './Trace';
import Lia from '~/components/Lia';
import Landing from './Landing';
import Header from './Header';
import { cn } from '~/utils';
@ -88,6 +89,9 @@ function ChatView({
/** Room an open composer popover needs below the composer; see the atom. */
const composerLift = useAtomValue(composerLiftFamily(index));
/** Lia, the welcome screen mascot, stands on the composer band's top edge. */
const composerBandRef = useRef<HTMLDivElement>(null);
const methods = useForm<ChatFormValues>({
defaultValues: { text: '' },
});
@ -213,6 +217,7 @@ function ChatView({
}
className={cn(
'flex flex-col',
isLandingPage && 'relative',
isLandingPage
? /* The gutter is reserved once per state, wherever the
centring happens. A conversation centres the composer
@ -242,6 +247,7 @@ function ChatView({
is a stacking context; keep it above positioned tool glyphs
so they cannot paint through the approval preview. */}
<div
ref={composerBandRef}
className={cn(
'bg-surface-canvas relative z-10 w-full [view-transition-name:chat-form]',
!isLandingPage && 'scrollbar-gutter-spacer',
@ -275,6 +281,11 @@ function ChatView({
with the conversation that always showed it. */}
{!isLandingPage && configuredFooter && <Footer configuredOnly />}
</div>
<Lia
bandRef={composerBandRef}
landing={isLandingPage}
submission={rootSubmission}
/>
</div>
{isLandingPage && <Footer />}
</>

View file

@ -50,6 +50,7 @@ jest.mock('../Footer', () => ({
useConfiguredFooter: () => false,
}));
jest.mock('../Landing', () => ({ __esModule: true, default: () => <div /> }));
jest.mock('~/components/Lia', () => ({ __esModule: true, default: () => null }));
jest.mock('../Messages/MessagesView', () => ({ __esModule: true, default: () => <div /> }));
jest.mock('../Input/ChatForm', () => ({
__esModule: true,

View file

@ -70,6 +70,7 @@ jest.mock('../Presentation', () => ({ children }: { children: React.ReactNode })
));
jest.mock('../Input/ChatForm', () => () => <div data-testid="chat-form" />);
jest.mock('../Landing', () => () => <div data-testid="landing" />);
jest.mock('~/components/Lia', () => () => null);
jest.mock('../Trace', () => ({
TraceSurface: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));

View file

@ -0,0 +1,619 @@
import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import { Button } from '@librechat/client';
import type { RefObject } from 'react';
import type { Bubble, LabelKey, Platform } from './engine/types';
import type { TranslationKeys } from '~/hooks';
import { BX, GRID_W, GRID_H, FOOT_Y, HEAD_ROWS } from './engine/body';
import { LiaEngine } from './engine/engine';
import { freeSpan } from './engine/span';
import { useLocalize } from '~/hooks';
import { SAY } from './speech';
const SCALE = 2;
/** Lia's half width plus a margin, so she never stands past the end of the composer. */
const EDGE = 22 * SCALE;
/** Below this stage width there is no room beside the greeting, so Lia stays away. */
const MIN_WIDTH = 360;
/** On the floor beside the composer, how far from its edge Lia may wander. */
const NEAR = 3 * EDGE;
/** How far above the composer Lia reaches, raised arms included; content there is avoided. */
const HEIGHT = 50 * SCALE;
/** Lia's body, the only part that takes clicks; the canvas around it is see-through room for
* arms and props and lets clicks pass to the page. */
const BODY_W = (GRID_W - 2 * BX) * SCALE;
const BODY_H = HEAD_ROWS * SCALE;
/** How far one arrow key press carries Lia along the composer. */
const KEY_STEP = 24 * SCALE;
/** Words that make Lia react while you type them. */
const KEYWORDS: Readonly<Record<string, string>> = {
hello: 'r-hello',
hi: 'r-hello',
hey: 'r-hello',
thanks: 'r-thanks',
thank: 'r-thanks',
lia: 'r-name',
love: 'r-love',
};
/** Where the caret sits inside a textarea, measured with a hidden mirror element. */
function caretPoint(textarea: HTMLTextAreaElement, mirror: HTMLDivElement, origin: DOMRect) {
const style = getComputedStyle(textarea);
/* Everything that moves text inside the box, so wrapping and right-to-left text match. */
for (const prop of [
'direction',
'textAlign',
'textIndent',
'textTransform',
'fontFamily',
'fontSize',
'fontStyle',
'fontWeight',
'fontVariant',
'lineHeight',
'letterSpacing',
'wordSpacing',
'tabSize',
'wordBreak',
'paddingLeft',
'paddingRight',
'paddingTop',
] as const) {
mirror.style[prop] = style[prop];
}
/* clientWidth includes padding and excludes borders, so size the mirror's border box to it. */
mirror.style.boxSizing = 'border-box';
mirror.style.width = `${textarea.clientWidth}px`;
mirror.textContent = textarea.value.slice(0, textarea.selectionEnd);
const marker = document.createElement('span');
marker.textContent = '​';
mirror.appendChild(marker);
const box = textarea.getBoundingClientRect();
return {
x: box.left - origin.left + marker.offsetLeft,
y: box.top - origin.top + marker.offsetTop - textarea.scrollTop,
};
}
const hasFiles = (e: DragEvent) =>
e.dataTransfer != null && [...e.dataTransfer.types].includes('Files');
export default function Stage({
bandRef,
leaving = false,
}: {
bandRef: RefObject<HTMLElement>;
/** The user just sent the first message: Lia waves it off and sinks behind the composer. */
leaving?: boolean;
}) {
const localize = useLocalize();
const rootRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const hitRef = useRef<HTMLButtonElement>(null);
const keysId = useId();
const bubbleRef = useRef<HTMLDivElement>(null);
/* Measured when the text changes, so placing the bubble each frame reads no layout. */
const bubbleWidthRef = useRef(0);
const [bubble, setBubble] = useState<Bubble | null>(null);
const [activity, setActivity] = useState<LabelKey | null>(null);
const engineRef = useRef<LiaEngine | null>(null);
const leavingRef = useRef(leaving);
useEffect(() => {
const wasLeaving = leavingRef.current;
leavingRef.current = leaving;
if (leaving) {
engineRef.current?.play('r-send', 4);
} else if (wasLeaving) {
/* Back on the welcome screen before the farewell ended: drop it, she hides at its end. */
engineRef.current?.play('intro', 4);
}
}, [leaving]);
useEffect(() => {
const root = rootRef.current;
const canvas = canvasRef.current;
const hit = hitRef.current;
if (!root || !canvas || !hit) {
return;
}
/* The welcome content above the composer (greeting, agent name) is measured as obstacles,
* cached briefly because layout only changes on resize and on content swaps. */
let obstacles: DOMRect[] = [];
let measuredAt = -Infinity;
const measureObstacles = (band: HTMLElement) => {
const now = performance.now();
if (now - measuredAt < 250) {
return obstacles;
}
measuredAt = now;
obstacles = [];
for (const child of Array.from(root.parentElement?.children ?? [])) {
if (child === root || child === band) {
continue;
}
const range = document.createRange();
range.selectNodeContents(child);
const box = range.getBoundingClientRect();
if (box.width > 0 && box.height > 0) {
obstacles.push(box);
}
}
return obstacles;
};
let placed: LiaEngine | null = null;
/* Where Lia's canvas may reach, so the bubble can stay inside the same room. */
let room: readonly [number, number] = [0, Infinity];
/* Set when the user drops her below the composer's middle, so she stays on the floor. */
let floorFirst = false;
/* The bubble belongs to Lia: whenever she has nowhere to stand, it goes with her. */
const setVisible = (visible: boolean) => {
const value = visible ? 'visible' : 'hidden';
canvas.style.visibility = value;
hit.style.visibility = value;
if (bubbleRef.current) {
bubbleRef.current.style.visibility = value;
}
};
const platform = (): Platform | null => {
const band = bandRef.current;
if (!band || root.clientWidth < MIN_WIDTH) {
setVisible(false);
return null;
}
const origin = root.getBoundingClientRect();
const box = band.getBoundingClientRect();
const top = box.top - origin.top;
/* The band runs below the visible composer, so the floor is the form's bottom edge. */
const bottom =
(band.querySelector('form') ?? band).getBoundingClientRect().bottom - origin.top;
const left = box.left - origin.left;
const right = box.right - origin.left;
/* While leaving, the conversation replaces the welcome content and Lia rides the composer down. */
const obstacles = leavingRef.current ? [] : measureObstacles(band);
/* Where she can stand with her feet at `y`, clear of the content beside or above her.
* Any gap that fits her body will do: in a narrow one she stands still. */
const standAt = (y: number, x0: number, x1: number, extra: [number, number][]) =>
freeSpan(
x0,
x1,
obstacles
.filter((o) => o.bottom - origin.top > y - HEIGHT && o.top - origin.top < y)
.map((o) => [o.left - origin.left - EDGE, o.right - origin.left + EDGE] as const)
.concat(extra),
placed?.position.x ?? Infinity,
0,
);
/* On top of the composer beside the greeting, or on the floor beside the composer, level
* with its bottom edge: the top first, unless she was last dropped on the floor. */
const onTop = () => standAt(top, left + EDGE, right - EDGE, []);
const onFloor = () =>
standAt(
bottom,
Math.max(EDGE, left - NEAR),
Math.min(root.clientWidth - EDGE, right + NEAR),
[[left - EDGE, right + EDGE]],
);
const order = floorFirst
? ([
[bottom, onFloor],
[top + 1, onTop],
] as const)
: ([
[top + 1, onTop],
[bottom, onFloor],
] as const);
for (const [y, find] of order) {
const span = find();
if (span) {
setVisible(true);
room = [Math.max(0, span[0] - EDGE), Math.min(root.clientWidth, span[1] + EDGE)];
return { y, x0: span[0], x1: span[1] };
}
}
setVisible(false);
return null;
};
const engine = new LiaEngine(canvas, {
platform,
onBubble: setBubble,
onAction: setActivity,
onFrame: (head) => {
/* The head point is the top of her body, centered. */
hit.style.transform = `translate(${Math.round(head.x - BODY_W / 2)}px, ${Math.round(head.y)}px)`;
const bubbleEl = bubbleRef.current;
if (!bubbleEl) {
return;
}
/* The bubble sits to Lia's right, flips left when that side has no room, and never
* leaves the stage or the span she stands in. */
const width = bubbleWidthRef.current;
const [left, right] = room;
let x = head.x + 10 * SCALE;
if (x + width > right) {
x = head.x - 10 * SCALE - width;
}
x = Math.max(left, Math.min(x, right - width));
bubbleEl.style.transform = `translate(${Math.round(x)}px, ${Math.round(head.y - 6 * SCALE)}px) translateY(-100%)`;
},
});
placed = engine;
engineRef.current = engine;
const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
engine.reducedMotion = motion.matches;
const onMotion = () => {
engine.reducedMotion = motion.matches;
};
motion.addEventListener('change', onMotion);
const cooldowns = new Map<string, number>();
const react = (id: string, ms = 6000) => {
const now = performance.now();
if (
now - (cooldowns.get(id) ?? -Infinity) < ms ||
now - (cooldowns.get('*') ?? -Infinity) < 1500
) {
return false;
}
/* Wall time for the cooldowns; the engine keeps its own clock, paused while she has no room. */
if (!engine.play(id, 2)) {
return false;
}
cooldowns.set(id, now);
cooldowns.set('*', now);
return true;
};
const mirror = document.createElement('div');
mirror.setAttribute('aria-hidden', 'true');
Object.assign(mirror.style, {
position: 'absolute',
visibility: 'hidden',
top: '0',
left: '-9999px',
whiteSpace: 'pre-wrap',
overflowWrap: 'break-word',
});
document.body.appendChild(mirror);
let keyTimes: number[] = [];
let longShown = false;
const onInput = (e: Event) => {
const target = e.target;
if (!(target instanceof HTMLTextAreaElement)) {
return;
}
const now = performance.now();
engine.noteTyping();
engine.caret = caretPoint(target, mirror, root.getBoundingClientRect());
/* Deleting back under the threshold re-arms the reaction for the next long message. */
if (target.value.length <= 280) {
longShown = false;
}
const input = e as InputEvent;
if (input.inputType === 'insertFromPaste') {
if (target.value.length > 40) {
react('r-paste', 8000);
}
return;
}
if (input.inputType?.startsWith('delete')) {
return;
}
keyTimes = keyTimes.filter((k) => now - k < 1500);
keyTimes.push(now);
if (keyTimes.length >= 9 && engine.current == null) {
react('r-type-fast', 12000);
}
/* Only a reaction that actually played uses up the long message; a busy Lia tries again. */
if (!longShown && target.value.length > 280) {
longShown = react('r-long', 1000);
}
const ch = input.data;
if (ch === '?') {
react('r-question', 10000);
} else if (ch === '!') {
react('r-exclaim', 10000);
}
if (ch && /[\s.,!?]/.test(ch)) {
const word = target.value
.slice(0, target.selectionEnd - 1)
.toLowerCase()
.match(/[a-z]+$/)?.[0];
const id = word ? KEYWORDS[word] : undefined;
if (id) {
react(id, 8000);
}
}
};
const onFocusIn = (e: FocusEvent) => {
if (e.target instanceof HTMLTextAreaElement) {
engine.caret = caretPoint(e.target, mirror, root.getBoundingClientRect());
engine.glance('curious', 900, 'caret');
engine.noteActivity(true);
}
};
const onKeyDown = (e: KeyboardEvent) => {
if (
(e.ctrlKey || e.metaKey) &&
e.key === 'a' &&
e.target instanceof HTMLTextAreaElement &&
e.target.value
) {
react('r-select', 15000);
}
};
let shakeDir = 0;
let flips: number[] = [];
/* Pointer events can outpace frames; read layout at most once per frame. */
let pendingPointer: { x: number; y: number } | null = null;
let pointerFrame = 0;
const onPointerMove = (e: PointerEvent) => {
pendingPointer = { x: e.clientX, y: e.clientY };
if (!pointerFrame) {
pointerFrame = requestAnimationFrame(processPointer);
}
};
const processPointer = () => {
pointerFrame = 0;
const client = pendingPointer;
pendingPointer = null;
if (!client) {
return;
}
const origin = root.getBoundingClientRect();
const p = { x: client.x - origin.left, y: client.y - origin.top };
const prev = engine.pointer;
engine.pointer = p;
engine.noteActivity();
if (!prev) {
return;
}
const now = performance.now();
const head = engine.position;
const near = Math.hypot(p.x - head.x, p.y - (head.y - 26 * SCALE)) < 80 * SCALE;
const dir = Math.sign(p.x - prev.x);
if (near && dir && dir !== shakeDir) {
flips = flips.filter((k) => now - k < 700);
flips.push(now);
if (flips.length >= 6) {
flips = [];
react('r-shake', 10000);
}
}
shakeDir = dir || shakeDir;
};
let dragDepth = 0;
const onDragEnter = (e: DragEvent) => {
if (!hasFiles(e)) {
return;
}
dragDepth += 1;
if (dragDepth === 1) {
engine.noteActivity(true);
engine.play('r-drag', 3);
}
};
const onDragLeave = (e: DragEvent) => {
if (!hasFiles(e)) {
return;
}
dragDepth = Math.max(0, dragDepth - 1);
if (dragDepth === 0) {
engine.play('r-drag-cancel', 3);
}
};
const onDrop = (e: DragEvent) => {
if (!hasFiles(e)) {
return;
}
dragDepth = 0;
engine.play('r-drop', 3);
};
let dark = document.documentElement.classList.contains('dark');
const themeObserver = new MutationObserver(() => {
const next = document.documentElement.classList.contains('dark');
if (next !== dark) {
dark = next;
engine.play(next ? 'r-dark' : 'r-light', 3);
}
});
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
let hiddenAt = 0;
const onVisibility = () => {
if (document.hidden) {
hiddenAt = performance.now();
} else if (hiddenAt && performance.now() - hiddenAt > 5000) {
react('r-welcome', 20000);
}
};
/* Dragging her around: a press that moves past a few pixels picks her up, and letting go
* drops her on the composer or the floor beside it, whichever is nearer. A press that does
* not move stays a click, which pets her. */
let grab: { id: number; x: number; y: number; dx: number; dy: number } | null = null;
let dragging = false;
let dragged = false;
const feetAt = (e: PointerEvent) => {
const origin = root.getBoundingClientRect();
return {
x: e.clientX - origin.left - (grab?.dx ?? 0),
y: e.clientY - origin.top - (grab?.dy ?? 0) + BODY_H,
};
};
const onGrab = (e: PointerEvent) => {
if (e.button !== 0) {
return;
}
const box = hit.getBoundingClientRect();
grab = {
id: e.pointerId,
x: e.clientX,
y: e.clientY,
dx: e.clientX - box.left - BODY_W / 2,
dy: e.clientY - box.top,
};
hit.setPointerCapture(e.pointerId);
};
const onCarry = (e: PointerEvent) => {
if (!grab || e.pointerId !== grab.id) {
return;
}
if (!dragging && Math.hypot(e.clientX - grab.x, e.clientY - grab.y) < 5) {
return;
}
dragging = true;
engine.hold(feetAt(e));
};
const onLetGo = (e: PointerEvent) => {
if (!grab || e.pointerId !== grab.id) {
return;
}
if (dragging) {
const feet = feetAt(e);
const band = bandRef.current;
if (band) {
const form = (band.querySelector('form') ?? band).getBoundingClientRect();
const origin = root.getBoundingClientRect();
floorFirst = feet.y > (form.top + form.bottom) / 2 - origin.top;
}
engine.release(feet.x);
dragged = true;
}
grab = null;
dragging = false;
};
const onPet = () => {
if (dragged) {
dragged = false;
return;
}
engine.pet();
};
/* The keyboard's drag: each arrow press picks Lia up and sets her down a step along. */
const onStep = (e: KeyboardEvent) => {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') {
return;
}
e.preventDefault();
const { x, y } = engine.position;
const to = x + (e.key === 'ArrowLeft' ? -KEY_STEP : KEY_STEP);
engine.hold({ x: to, y });
engine.release(to);
};
const onHover = () => {
if (engine.current == null && Math.random() < 0.4) {
react('r-hover', 10000);
} else {
engine.glance('content', 800, 'pointer');
}
};
const band = bandRef.current;
band?.addEventListener('input', onInput);
band?.addEventListener('focusin', onFocusIn);
band?.addEventListener('keydown', onKeyDown);
window.addEventListener('pointermove', onPointerMove, { passive: true });
window.addEventListener('dragenter', onDragEnter);
window.addEventListener('dragleave', onDragLeave);
window.addEventListener('drop', onDrop);
document.addEventListener('visibilitychange', onVisibility);
hit.addEventListener('pointerdown', onGrab);
hit.addEventListener('pointermove', onCarry);
hit.addEventListener('pointerup', onLetGo);
hit.addEventListener('pointercancel', onLetGo);
hit.addEventListener('click', onPet);
hit.addEventListener('keydown', onStep);
hit.addEventListener('pointerenter', onHover);
engine.play(leavingRef.current ? 'r-send' : 'intro', 4);
engine.start();
return () => {
engineRef.current = null;
engine.stop();
band?.removeEventListener('input', onInput);
band?.removeEventListener('focusin', onFocusIn);
band?.removeEventListener('keydown', onKeyDown);
window.removeEventListener('pointermove', onPointerMove);
cancelAnimationFrame(pointerFrame);
window.removeEventListener('dragenter', onDragEnter);
window.removeEventListener('dragleave', onDragLeave);
window.removeEventListener('drop', onDrop);
document.removeEventListener('visibilitychange', onVisibility);
hit.removeEventListener('pointerdown', onGrab);
hit.removeEventListener('pointermove', onCarry);
hit.removeEventListener('pointerup', onLetGo);
hit.removeEventListener('pointercancel', onLetGo);
hit.removeEventListener('click', onPet);
hit.removeEventListener('keydown', onStep);
hit.removeEventListener('pointerenter', onHover);
motion.removeEventListener('change', onMotion);
themeObserver.disconnect();
mirror.remove();
};
}, [bandRef]);
let bubbleText: string | null = null;
if (bubble != null) {
bubbleText = 'say' in bubble ? localize(SAY[bubble.say]) : bubble.symbol;
}
const doing = localize('com_ui_lia_doing', {
0: localize((activity ?? 'com_ui_lia_act_idle') as TranslationKeys),
});
useLayoutEffect(() => {
bubbleWidthRef.current = bubbleRef.current?.offsetWidth ?? 0;
}, [bubbleText]);
return (
<div ref={rootRef} className="pointer-events-none absolute inset-0 overflow-hidden">
<canvas
ref={canvasRef}
aria-hidden="true"
data-testid="lia"
className="absolute top-0 left-0 z-[5] [image-rendering:pixelated]"
style={{
width: GRID_W * SCALE,
height: GRID_H * SCALE,
transformOrigin: `${32 * SCALE}px ${(FOOT_Y - 1) * SCALE}px`,
}}
/>
{/* Lia herself: click or Enter to pet her, drag or the arrow keys to move her. */}
<Button
ref={hitRef}
type="button"
variant={null}
size={null}
data-testid="lia-body"
title={doing}
aria-label={doing}
aria-describedby={keysId}
aria-keyshortcuts="ArrowLeft ArrowRight"
className="pointer-events-auto absolute top-0 left-0 z-[6] cursor-grab touch-none active:cursor-grabbing"
style={{ width: BODY_W, height: BODY_H }}
/>
<span id={keysId} className="sr-only">
{localize('com_ui_lia_keys')}
</span>
<div
ref={bubbleRef}
aria-hidden="true"
data-testid="lia-bubble"
className="absolute top-0 left-0 z-20 w-max max-w-48"
hidden={bubbleText == null}
>
<span className="border-border-medium bg-surface-primary text-text-primary block rounded-lg border px-2 py-1 text-xs font-medium shadow-sm">
{bubbleText}
</span>
</div>
</div>
);
}

View file

@ -0,0 +1,118 @@
import React, { createRef } from 'react';
import { createStore, Provider } from 'jotai';
import { act, render, screen } from '@testing-library/react';
import type { TSubmission } from 'librechat-data-provider';
import Lia, { FAREWELL_MS } from '../index';
import { showLiaAtom } from '../store';
const mockUseGetStartupConfig = jest.fn();
jest.mock('~/data-provider', () => ({
useGetStartupConfig: () => mockUseGetStartupConfig(),
}));
jest.mock('../Stage', () => ({
__esModule: true,
default: () => <div data-testid="lia-stage" />,
}));
interface Options {
enabled: boolean;
mascot?: boolean | null;
landing?: boolean;
submission?: TSubmission | null;
}
type ViewProps = { landing: boolean; submission: TSubmission | null };
const send = () => ({}) as TSubmission;
function renderLia({ enabled, mascot, landing = true, submission = null }: Options) {
const store = createStore();
store.set(showLiaAtom, enabled);
mockUseGetStartupConfig.mockReturnValue({
data: mascot === null ? undefined : { interface: mascot === undefined ? {} : { mascot } },
});
const bandRef = createRef<HTMLElement>();
const view = (props: ViewProps) => (
<Provider store={store}>
<Lia bandRef={bandRef} {...props} />
</Provider>
);
const result = render(view({ landing, submission }));
return {
...result,
update: (props: ViewProps) => result.rerender(view(props)),
};
}
describe('Lia', () => {
beforeEach(() => localStorage.clear());
it('shows nothing until the user opts in', () => {
renderLia({ enabled: false });
expect(screen.queryByTestId('lia-stage')).toBeNull();
});
/* Runs before any other test lets the stage chunk load; the load is remembered per module. */
it('gives no farewell to a send made before her chunk arrived', async () => {
const { update } = renderLia({ enabled: true });
expect(screen.queryByTestId('lia-stage')).toBeNull();
update({ landing: false, submission: send() });
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
expect(screen.queryByTestId('lia-stage')).toBeNull();
});
it('shows Lia when the user opted in and the deployment allows it', async () => {
renderLia({ enabled: true });
expect(await screen.findByTestId('lia-stage')).toBeInTheDocument();
});
it('respects a deployment that turns the mascot off', () => {
renderLia({ enabled: true, mascot: false });
expect(screen.queryByTestId('lia-stage')).toBeNull();
});
it('waits for the deployment config before showing anything', () => {
renderLia({ enabled: true, mascot: null });
expect(screen.queryByTestId('lia-stage')).toBeNull();
});
it('stays to wave off the first message, then leaves', async () => {
jest.useFakeTimers();
const { update } = renderLia({ enabled: true });
expect(await screen.findByTestId('lia-stage')).toBeInTheDocument();
update({ landing: false, submission: send() });
expect(screen.getByTestId('lia-stage')).toBeInTheDocument();
act(() => {
jest.advanceTimersByTime(FAREWELL_MS);
});
expect(screen.queryByTestId('lia-stage')).toBeNull();
jest.useRealTimers();
});
it('leaves at once when the user navigates away instead of sending', async () => {
const { update } = renderLia({ enabled: true });
expect(await screen.findByTestId('lia-stage')).toBeInTheDocument();
update({ landing: false, submission: null });
expect(screen.queryByTestId('lia-stage')).toBeNull();
});
it('does not take a send from an earlier conversation for a new one', async () => {
const stale = send();
const { update } = renderLia({ enabled: true, submission: stale });
expect(await screen.findByTestId('lia-stage')).toBeInTheDocument();
update({ landing: false, submission: stale });
expect(screen.queryByTestId('lia-stage')).toBeNull();
});
it('stays away from conversations', () => {
renderLia({ enabled: true, landing: false });
expect(screen.queryByTestId('lia-stage')).toBeNull();
});
it('persists the opt-in in local storage', () => {
const store = createStore();
store.set(showLiaAtom, true);
expect(JSON.parse(localStorage.getItem('showLia') ?? 'null')).toBe(true);
});
});

View file

@ -54,6 +54,30 @@ describe('LiaEngine', () => {
expect(engine.current).toBeNull();
});
it('follows the pointer while held and lands on the platform under the drop', () => {
const { engine } = setup();
run(engine, 0, 500);
engine.hold({ x: 900, y: 120 }, 600);
run(engine, 600, 800);
expect(engine.current?.id).toBe('r-held');
expect(engine.position).toEqual({ x: 900, y: 120 });
expect(engine.play('r-hello', 2, 810)).toBe(false);
engine.release(900, 900);
run(engine, 900, 1000);
expect(engine.current?.id).toBe('r-landed');
expect(engine.position).toEqual({ x: PLATFORM.x1, y: PLATFORM.y });
});
it('ignores a release when she is not held', () => {
const { engine } = setup();
run(engine, 0, 500);
const before = engine.position;
engine.release(300, 600);
expect(engine.position).toEqual(before);
expect(engine.current?.id).not.toBe('r-landed');
});
it('keeps a more important action from being interrupted', () => {
const { engine } = setup();
engine.play('r-crash', 3, 0);

View file

@ -0,0 +1,32 @@
import en from '~/locales/en/translation.json';
import { EXPRESSIONS } from '../engine/face';
import { ACTIONS } from '../engine/catalog';
import { SAY } from '../speech';
describe('Lia speech', () => {
it('has an English label for everything Lia does and feels', () => {
const labels = [
...ACTIONS.map((a) => a.label),
...EXPRESSIONS.map((e) => e.label),
'com_ui_lia_doing',
'com_ui_lia_act_idle',
];
for (const label of labels) {
expect({ label, present: label in en }).toEqual({ label, present: true });
}
});
it('has an English line for every word Lia says', () => {
for (const action of ACTIONS) {
for (const [, spec] of action.steps) {
if (spec.b && 'say' in spec.b) {
const key = SAY[spec.b.say];
expect({ say: spec.b.say, present: key in en }).toEqual({
say: spec.b.say,
present: true,
});
}
}
}
});
});

View file

@ -378,6 +378,13 @@ react('r-love', 'com_ui_lia_act_r_love', [
react('r-drag', 'com_ui_lia_act_r_drag', [
step(20000, { s: 'file', a: 'reachBoth', o: 'bounce', b: { say: 'ready' } }),
]);
react('r-held', 'com_ui_lia_act_r_held', [
step(60000, { a: 'out', f: 'startled', o: 'wobble', b: null }),
]);
react('r-landed', 'com_ui_lia_act_r_landed', [
step(500, { f: 'startled' }),
step(1100, { f: 'happy', a: 'thumbs' }),
]);
react('r-drop', 'com_ui_lia_act_r_drop', [
step(300, { a: 'catch', f: 'startled', b: null }),
step(1300, { f: 'chewing' }),

View file

@ -132,6 +132,8 @@ export class LiaEngine {
private gx = 0;
private gy = 0;
private placed = false;
/** Where the user holds her by, as her feet's position, while she is being dragged. */
private held: Point | null = null;
private move: Move | null = null;
private landAt = -1e9;
private pose: Required<PoseOffset> = { ox: 0, oy: 0, rot: 0, sx: 1, sy: 1 };
@ -216,6 +218,28 @@ export class LiaEngine {
return { x: this.gx, y: this.gy };
}
/** Lia is picked up and carried with her feet at `feet`; call again as the pointer moves. */
hold(feet: Point, now = this.clock()) {
if (!this.held) {
this.noteActivity(true, now);
this.stopRun();
this.play('r-held', 5, now);
}
this.held = feet;
}
/** Lia is let go above `x` and lands on the platform under it. */
release(x: number, now = this.clock()) {
if (!this.held) {
return;
}
this.held = null;
this.gx = x;
this.landAt = now;
this.stopRun();
this.play('r-landed', 4, now);
}
attention(now = this.clock()): Attention {
if (now < this.typingUntil + TYPING_QUIET_MS) {
return 'busy';
@ -515,8 +539,8 @@ export class LiaEngine {
private updateMotion(dt: number, now: number, platform: Platform) {
const S = this.scale;
const pose = { ox: 0, oy: 0, rot: 0, sx: 1, sy: 1 };
this.gy = platform.y;
const move = this.move;
this.gy = this.held?.y ?? platform.y;
const move = this.held ? null : this.move;
if (move) {
const style = STYLES[move.style];
/* The platform can shrink mid-walk; aim for the nearest end Lia can still reach. */
@ -545,7 +569,7 @@ export class LiaEngine {
}
}
}
this.gx = clamp(this.gx, platform.x0, platform.x1);
this.gx = this.held ? this.held.x : clamp(this.gx, platform.x0, platform.x1);
if (!this.reducedMotion) {
const overlay = this.overlay && now < this.overlay.until ? this.overlay : null;

View file

@ -0,0 +1,71 @@
import { Suspense, useEffect, useState } from 'react';
import { useAtomValue } from 'jotai';
import type { TSubmission } from 'librechat-data-provider';
import type { RefObject } from 'react';
import { useGetStartupConfig } from '~/data-provider';
import { lazyWithRecovery } from '~/lib/assets/lazy';
import { showLiaAtom } from './store';
/* The engine and its art load only for people who turned Lia on, after the page has painted,
* so the welcome screen's first paint never waits on them. */
let stageLoaded = false;
const Stage = lazyWithRecovery(() =>
import('./Stage').then((module) => {
stageLoaded = true;
return module;
}),
);
/** How long Lia stays to wave off the first message after the welcome screen gives way. */
export const FAREWELL_MS = 1900;
interface LiaProps {
/** The composer band Lia stands on. */
bandRef: RefObject<HTMLElement>;
/** Whether the welcome screen is showing. */
landing: boolean;
/** The latest send. Every endpoint sets it in the same update that adds the first message,
* unlike `isSubmitting`, which Assistants endpoints only raise once their stream opens. */
submission: TSubmission | null;
}
/**
* Lia, the welcome screen mascot. Purely decorative: hidden from assistive technology, and
* shown only when the deployment allows it (`interface.mascot`) and the user opted in.
*/
export default function Lia({ bandRef, landing, submission }: LiaProps) {
const show = useAtomValue(showLiaAtom);
const { data: startupConfig } = useGetStartupConfig();
const [prevLanding, setPrevLanding] = useState(landing);
/* The send already in place while the welcome screen showed, such as one left from an
* earlier conversation, so only a new one counts as sending from here. */
const [seen, setSeen] = useState(submission);
const [leaving, setLeaving] = useState(false);
if (landing && submission !== seen) {
setSeen(submission);
}
/* Leaving the welcome screen by sending a message gets a farewell; navigating away does not. */
if (landing !== prevLanding) {
setPrevLanding(landing);
/* Only once she has been on screen: a send that beats her chunk ends without a farewell. */
setLeaving(stageLoaded && !landing && submission != null && submission !== seen);
}
useEffect(() => {
if (!leaving) {
return;
}
const timer = setTimeout(() => setLeaving(false), FAREWELL_MS);
return () => clearTimeout(timer);
}, [leaving]);
const allowed = startupConfig != null && startupConfig.interface?.mascot !== false;
if (!show || !allowed || (!landing && !leaving)) {
return null;
}
return (
<Suspense fallback={null}>
<Stage bandRef={bandRef} leaving={leaving} />
</Suspense>
);
}

View file

@ -0,0 +1,19 @@
import type { TranslationKeys } from '~/hooks';
import type { SayKey } from './engine/types';
/** The localized line for each word Lia can say in a speech bubble. */
export const SAY: Readonly<Record<SayKey, TranslationKeys>> = {
hi: 'com_ui_lia_say_hi',
hmm: 'com_ui_lia_say_hmm',
haha: 'com_ui_lia_say_haha',
yay: 'com_ui_lia_say_yay',
oops: 'com_ui_lia_say_oops',
brb: 'com_ui_lia_say_brb',
gg: 'com_ui_lia_say_gg',
wow: 'com_ui_lia_say_wow',
beep: 'com_ui_lia_say_beep',
okay: 'com_ui_lia_say_okay',
boo: 'com_ui_lia_say_boo',
thatsMe: 'com_ui_lia_say_thats_me',
ready: 'com_ui_lia_say_ready',
};

View file

@ -0,0 +1,9 @@
import { createStorageAtom } from '~/store/jotai-utils';
const DEFAULT_SHOW_LIA = false;
/**
* Whether Lia, the welcome screen mascot, is shown. Off until the user opts in, and only
* offered when the deployment allows it (`interface.mascot`).
*/
export const showLiaAtom = createStorageAtom<boolean>('showLia', DEFAULT_SHOW_LIA);

View file

@ -22,6 +22,7 @@ const ctx: SettingsContextValue = {
twoFactorEnabled: false,
allowAccountDeletion: true,
aboutEnabled: false,
mascotAllowed: true,
engineTTS: 'browser',
langfuseConnectionAccess: false,
adminPanelURL: '',

View file

@ -24,6 +24,7 @@ const settingsContext: SettingsContextValue = {
twoFactorEnabled: false,
allowAccountDeletion: true,
aboutEnabled: false,
mascotAllowed: true,
engineTTS: 'browser',
langfuseConnectionAccess: false,
adminPanelURL: '',

View file

@ -43,6 +43,8 @@ export function useSettingsContext(): SettingsContextValue {
const twoFactorEnabled = user?.twoFactorEnabled === true;
const allowAccountDeletion = startupConfig?.allowAccountDeletion !== false;
const aboutEnabled = startupConfig?.interface?.buildInfo !== false;
/* Offered only once the deployment has answered, so an operator's opt-out never flashes the row. */
const mascotAllowed = startupConfig != null && startupConfig.interface?.mascot !== false;
/* Offered only once the deployment has answered, matching the capability hook the alerts
read: before then a toggle could store a preference, or raise the browser's permission
prompt, for a capability the operator turns off. */
@ -79,6 +81,7 @@ export function useSettingsContext(): SettingsContextValue {
twoFactorEnabled,
allowAccountDeletion,
aboutEnabled,
mascotAllowed,
engineTTS,
langfuseConnectionAccess,
adminPanelURL,
@ -103,6 +106,7 @@ export function useSettingsContext(): SettingsContextValue {
twoFactorEnabled,
allowAccountDeletion,
aboutEnabled,
mascotAllowed,
engineTTS,
langfuseConnectionAccess,
adminPanelURL,

View file

@ -5,6 +5,7 @@ import { ThemeContext } from '@librechat/client';
import type { ComponentType } from 'react';
import type { TranslationKeys } from '~/hooks';
import { ThemeSelector, LangSelector } from '~/components/Appearance';
import { BetaPill } from '~/components/SidePanel/Agents/Advanced/ui';
import ToggleSwitch from '../SettingsTabs/ToggleSwitch';
import store from '~/store';
@ -13,6 +14,7 @@ export function toggleControl(opts: {
localizationKey: TranslationKeys;
switchId: string;
hoverCardText?: TranslationKeys;
beta?: boolean;
onCheckedChange?: (value: boolean) => void;
}): ComponentType {
const Control = () => (
@ -21,6 +23,7 @@ export function toggleControl(opts: {
localizationKey={opts.localizationKey}
switchId={opts.switchId}
hoverCardText={opts.hoverCardText}
badge={opts.beta === true ? <BetaPill /> : undefined}
onCheckedChange={opts.onCheckedChange}
/>
);

View file

@ -55,6 +55,7 @@ import ImageResize from '../SettingsTabs/Chat/ImageResize';
import Passkeys from '../SettingsTabs/Account/Passkeys';
import { showThinkingAtom } from '~/store/showThinking';
import ProviderKeys from '../SettingsTabs/ProviderKeys';
import { showLiaAtom } from '~/components/Lia/store';
import { autoScrollAtom } from '~/store/autoScroll';
import Avatar from '../SettingsTabs/Account/Avatar';
import CodeEnvironments from './CodeEnvironments';
@ -155,6 +156,21 @@ export const registry: SettingEntry[] = [
switchId: 'centerFormOnLanding',
}),
},
{
id: 'showLia',
tab: GENERAL,
section: 'layout',
labelKey: 'com_nav_show_lia',
keywords: ['mascot', 'lia', 'fun', 'animation', 'welcome'],
show: (ctx) => ctx.mascotAllowed,
Component: toggleControl({
stateAtom: showLiaAtom,
localizationKey: 'com_nav_show_lia',
switchId: 'showLia',
hoverCardText: 'com_nav_info_show_lia',
beta: true,
}),
},
{
id: 'showScrollButton',
tab: GENERAL,

View file

@ -55,6 +55,7 @@ export interface SettingsContextValue {
twoFactorEnabled: boolean;
allowAccountDeletion: boolean;
aboutEnabled: boolean;
mascotAllowed: boolean;
engineTTS: string;
langfuseConnectionAccess: boolean;
adminPanelURL: string;

View file

@ -10,6 +10,8 @@ interface ToggleSwitchProps {
stateAtom: RecoilState<boolean> | WritableAtom<boolean, [boolean], void>;
localizationKey: LocalizeKey;
hoverCardText?: LocalizeKey;
/** Rendered after the label, outside its accessible name (for example a Beta pill). */
badge?: React.ReactNode;
switchId: string;
onCheckedChange?: (value: boolean) => void;
showSwitch?: boolean;
@ -27,6 +29,7 @@ const RecoilToggle: React.FC<
stateAtom,
localizationKey,
hoverCardText,
badge,
switchId,
onCheckedChange,
disabled = false,
@ -48,6 +51,7 @@ const RecoilToggle: React.FC<
<div id={labelId}>
{strongLabel ? <strong>{localize(localizationKey)}</strong> : localize(localizationKey)}
</div>
{badge}
{hoverCardText && <InfoHoverCard side={ESide.Bottom} text={localize(hoverCardText)} />}
</div>
<Switch
@ -69,6 +73,7 @@ const JotaiToggle: React.FC<
stateAtom,
localizationKey,
hoverCardText,
badge,
switchId,
onCheckedChange,
disabled = false,
@ -90,6 +95,7 @@ const JotaiToggle: React.FC<
<div id={labelId}>
{strongLabel ? <strong>{localize(localizationKey)}</strong> : localize(localizationKey)}
</div>
{badge}
{hoverCardText && <InfoHoverCard side={ESide.Bottom} text={localize(hoverCardText)} />}
</div>
<Switch

View file

@ -874,6 +874,7 @@
"com_nav_info_reply_notifications": "Show a desktop notification when a reply arrives while you are away from LibreChat. Your browser will ask for permission the first time you enable this. Notifications are not shown while you are looking at LibreChat, since the conversation list already marks the reply.",
"com_nav_info_save_badges_state": "When enabled, the state of the chat badges will be saved. This means that if you create a new chat, the badges will remain in the same state as the previous chat. If you disable this option, the badges will reset to their default state every time you create a new chat",
"com_nav_info_save_draft": "When enabled, the text and attachments you enter in the chat form will be automatically saved locally as drafts. These drafts will be available even if you reload the page or switch to a different conversation. Drafts are stored locally on your device and are deleted once the message is sent.",
"com_nav_info_show_lia": "Lia is a small pixel mascot that lives around the chat input on the welcome screen. It is decorative and never sends anything.",
"com_nav_info_show_thinking": "When enabled, the chat will display the thinking dropdowns open by default, allowing you to view the AI's reasoning in real-time. When disabled, the thinking dropdowns will remain closed by default for a cleaner and more streamlined interface",
"com_nav_info_smooth_streaming": "When enabled, newly streamed words fade in smoothly for the latest response. This is purely visual — it does not delay token delivery — and is disabled automatically when your device prefers reduced motion.",
"com_nav_info_stateful_sessions": "When enabled, this agent uses the dedicated stateful Code API instead of the default stateless service. Retained files under /mnt/data carry across runs, but each run starts a fresh process. Shell variables, the working directory, $HOME, temporary files, global installs, and background processes are not durable. The runtime may reset, so keep anything important under /mnt/data. Requires Code Interpreter and the app-level stateful sessions capability.",
@ -971,6 +972,7 @@
"com_nav_setting_speech": "Speech",
"com_nav_settings": "Settings",
"com_nav_shared_links": "Shared chats",
"com_nav_show_lia": "Show Lia on the Welcome Screen",
"com_nav_show_thinking": "Open Thinking Dropdowns by Default",
"com_nav_slash_command": "/-Command",
"com_nav_slash_command_description": "Toggle command \"/\" for selecting a prompt via keyboard",
@ -1926,6 +1928,205 @@
"com_ui_latest_footer": "Every AI for Everyone.",
"com_ui_latest_version": "Latest version",
"com_ui_leave_blank_to_keep": "Leave blank to keep existing",
"com_ui_lia_act_bounce_around": "Bounces in place",
"com_ui_lia_act_come_closer": "Comes over to say hi",
"com_ui_lia_act_dance_ballet": "Tries ballet",
"com_ui_lia_act_dance_cartwheel": "Does a cartwheel",
"com_ui_lia_act_dance_disco": "Disco dances",
"com_ui_lia_act_dance_headbang": "Headbangs",
"com_ui_lia_act_dance_jacks": "Does jumping jacks",
"com_ui_lia_act_dance_macarena": "Does the Macarena",
"com_ui_lia_act_dance_moonwalk": "Moonwalks with style",
"com_ui_lia_act_dance_robot": "Does the robot",
"com_ui_lia_act_dance_spin": "Spins around",
"com_ui_lia_act_dance_tap": "Tap dances",
"com_ui_lia_act_dance_twist": "Does the twist",
"com_ui_lia_act_dance_victory": "Does a victory dance",
"com_ui_lia_act_dance_wiggle": "Does the wiggle",
"com_ui_lia_act_gesture_airguitar": "Plays air guitar",
"com_ui_lia_act_gesture_bow": "Takes a bow",
"com_ui_lia_act_gesture_box": "Shadowboxes",
"com_ui_lia_act_gesture_catch": "Gets ready to catch",
"com_ui_lia_act_gesture_cheer": "Cheers",
"com_ui_lia_act_gesture_clap": "Claps",
"com_ui_lia_act_gesture_conduct": "Conducts the air",
"com_ui_lia_act_gesture_cover": "Covers its eyes",
"com_ui_lia_act_gesture_drum": "Air drums",
"com_ui_lia_act_gesture_facepalm": "Facepalms",
"com_ui_lia_act_gesture_fan": "Fans itself",
"com_ui_lia_act_gesture_flex": "Flexes",
"com_ui_lia_act_gesture_hips": "Strikes a pose",
"com_ui_lia_act_gesture_hug": "Hugs itself",
"com_ui_lia_act_gesture_jazz": "Does jazz hands",
"com_ui_lia_act_gesture_knock": "Knocks on its own head",
"com_ui_lia_act_gesture_pointDown": "Points at the chat box",
"com_ui_lia_act_gesture_pointL": "Points left",
"com_ui_lia_act_gesture_pointR": "Points right",
"com_ui_lia_act_gesture_pointUp": "Points at the sky",
"com_ui_lia_act_gesture_pray": "Says thank you",
"com_ui_lia_act_gesture_reach": "Reaches for the sky",
"com_ui_lia_act_gesture_rub": "Rubs its eyes",
"com_ui_lia_act_gesture_salute": "Salutes",
"com_ui_lia_act_gesture_scratch": "Scratches its head",
"com_ui_lia_act_gesture_shield": "Ducks for cover",
"com_ui_lia_act_gesture_shrug": "Shrugs",
"com_ui_lia_act_gesture_stretch": "Stretches",
"com_ui_lia_act_gesture_swim": "Pretends to swim",
"com_ui_lia_act_gesture_thumbs": "Gives a thumbs up",
"com_ui_lia_act_gesture_thumbsBoth": "Gives two thumbs up",
"com_ui_lia_act_gesture_tpose": "Does a T-pose",
"com_ui_lia_act_gesture_wave": "Waves hello",
"com_ui_lia_act_gesture_waveBoth": "Waves both arms",
"com_ui_lia_act_gesture_waveL": "Waves with the other arm",
"com_ui_lia_act_hiccups": "Gets the hiccups",
"com_ui_lia_act_hide_peek": "Hides behind the chat box",
"com_ui_lia_act_high_five": "Asks for a high five",
"com_ui_lia_act_hum": "Hums a tune",
"com_ui_lia_act_idle": "Hangs out",
"com_ui_lia_act_intro": "Boots up",
"com_ui_lia_act_look_around": "Looks around",
"com_ui_lia_act_nap": "Takes a nap",
"com_ui_lia_act_peekaboo": "Plays peekaboo",
"com_ui_lia_act_pet": "Gets petted",
"com_ui_lia_act_r_crash": "Crashes and reboots",
"com_ui_lia_act_r_dark": "Puts on sunglasses for dark mode",
"com_ui_lia_act_r_dizzy": "Gets clicked too much",
"com_ui_lia_act_r_drag": "Gets ready to catch your file",
"com_ui_lia_act_r_drag_cancel": "Is sad the file got away",
"com_ui_lia_act_r_drop": "Catches and munches your file",
"com_ui_lia_act_r_exclaim": "Gets excited with you",
"com_ui_lia_act_r_focus": "Notices you clicking into the chat box",
"com_ui_lia_act_r_held": "Gets carried around",
"com_ui_lia_act_r_hello": "Says hi back",
"com_ui_lia_act_r_hover": "Enjoys the attention",
"com_ui_lia_act_r_landed": "Lands with a thumbs up",
"com_ui_lia_act_r_light": "Squints at the light",
"com_ui_lia_act_r_long": "Is impressed by a long message",
"com_ui_lia_act_r_love": "Feels the love",
"com_ui_lia_act_r_name": "Hears its name",
"com_ui_lia_act_r_near": "Gets shy when you come close",
"com_ui_lia_act_r_paste": "Catches your paste",
"com_ui_lia_act_r_question": "Ponders your question",
"com_ui_lia_act_r_select": "Notices you selected everything",
"com_ui_lia_act_r_send": "Waves your message off",
"com_ui_lia_act_r_shake": "Gets dizzy from your pointer",
"com_ui_lia_act_r_squish": "Gets squished by the resize",
"com_ui_lia_act_r_thanks": "Bows to your thanks",
"com_ui_lia_act_r_type_fast": "Bounces along with your typing",
"com_ui_lia_act_r_wake": "Wakes up with a start",
"com_ui_lia_act_r_welcome": "Welcomes you back",
"com_ui_lia_act_reboot": "Reboots for fun",
"com_ui_lia_act_say_beep": "Says beep boop",
"com_ui_lia_act_say_brb": "Says it will be right back",
"com_ui_lia_act_say_dots": "Trails off",
"com_ui_lia_act_say_gg": "Says good game",
"com_ui_lia_act_say_haha": "Laughs",
"com_ui_lia_act_say_hi": "Says hi",
"com_ui_lia_act_say_hmm": "Thinks out loud",
"com_ui_lia_act_say_love": "Says it loves you",
"com_ui_lia_act_say_okay": "Says okay",
"com_ui_lia_act_say_oops": "Says oops",
"com_ui_lia_act_say_wow": "Says wow",
"com_ui_lia_act_say_yay": "Says yay",
"com_ui_lia_act_screensaver": "Runs its screensaver",
"com_ui_lia_act_shake_dust": "Shakes off some dust",
"com_ui_lia_act_sit_edge": "Sits at the edge and daydreams",
"com_ui_lia_act_sneak_pointer": "Sneaks toward your pointer",
"com_ui_lia_act_sneeze": "Sneezes",
"com_ui_lia_act_stare_contest": "Starts a staring contest with you",
"com_ui_lia_act_stretch_yawn": "Stretches and yawns",
"com_ui_lia_act_travel_dash": "Dashes off",
"com_ui_lia_act_travel_explore": "Explores",
"com_ui_lia_act_travel_hop": "Hops around",
"com_ui_lia_act_travel_march": "Marches along",
"com_ui_lia_act_travel_moonwalk": "Moonwalks over",
"com_ui_lia_act_travel_run": "Runs somewhere",
"com_ui_lia_act_travel_shuffle": "Shuffles over",
"com_ui_lia_act_travel_skip": "Skips along",
"com_ui_lia_act_travel_slide": "Slides across",
"com_ui_lia_act_travel_sneak": "Sneaks around",
"com_ui_lia_act_travel_teleport": "Teleports",
"com_ui_lia_act_travel_tiptoe": "Tiptoes around",
"com_ui_lia_act_travel_walk": "Strolls around",
"com_ui_lia_act_travel_wobble": "Wobbles along",
"com_ui_lia_act_trip": "Trips and falls over",
"com_ui_lia_doing": "Lia: {{0}}",
"com_ui_lia_feel_amazed": "Feels amazed",
"com_ui_lia_feel_angry": "Feels angry",
"com_ui_lia_feel_annoyed": "Feels annoyed",
"com_ui_lia_feel_asleep": "Falls asleep",
"com_ui_lia_feel_blushing": "Blushes",
"com_ui_lia_feel_bored": "Feels bored",
"com_ui_lia_feel_catface": "Makes a cat face",
"com_ui_lia_feel_cheeky": "Feels cheeky",
"com_ui_lia_feel_chewing": "Chews",
"com_ui_lia_feel_confused": "Feels confused",
"com_ui_lia_feel_content": "Feels content",
"com_ui_lia_feel_cool": "Feels cool",
"com_ui_lia_feel_crying": "Cries",
"com_ui_lia_feel_curious": "Feels curious",
"com_ui_lia_feel_dazed": "Feels dazed",
"com_ui_lia_feel_deadpan": "Keeps a straight face",
"com_ui_lia_feel_determined": "Feels determined",
"com_ui_lia_feel_dizzy": "Feels dizzy",
"com_ui_lia_feel_dreamy": "Feels dreamy",
"com_ui_lia_feel_embarrassed": "Feels embarrassed",
"com_ui_lia_feel_excited": "Feels excited",
"com_ui_lia_feel_fancy": "Feels fancy",
"com_ui_lia_feel_focused": "Feels focused",
"com_ui_lia_feel_furious": "Feels furious",
"com_ui_lia_feel_giggle": "Giggles",
"com_ui_lia_feel_grumpy": "Feels grumpy",
"com_ui_lia_feel_happy": "Feels happy",
"com_ui_lia_feel_hopeful": "Feels hopeful",
"com_ui_lia_feel_hungry": "Feels hungry",
"com_ui_lia_feel_hurt": "Says ouch",
"com_ui_lia_feel_joyful": "Feels joyful",
"com_ui_lia_feel_kissy": "Feels kissy",
"com_ui_lia_feel_laughing": "Laughs out loud",
"com_ui_lia_feel_love": "Is in love",
"com_ui_lia_feel_mischievous": "Feels mischievous",
"com_ui_lia_feel_nerd": "Feels nerdy",
"com_ui_lia_feel_nervous": "Feels nervous",
"com_ui_lia_feel_neutral": "Feels neutral",
"com_ui_lia_feel_pouting": "Pouts",
"com_ui_lia_feel_proud": "Feels proud",
"com_ui_lia_feel_relieved": "Feels relieved",
"com_ui_lia_feel_rich": "Feels rich",
"com_ui_lia_feel_sad": "Feels sad",
"com_ui_lia_feel_scared": "Feels scared",
"com_ui_lia_feel_shocked": "Feels shocked",
"com_ui_lia_feel_shy": "Feels shy",
"com_ui_lia_feel_sick": "Feels sick",
"com_ui_lia_feel_skeptical": "Feels skeptical",
"com_ui_lia_feel_sleepy": "Feels sleepy",
"com_ui_lia_feel_smug": "Feels smug",
"com_ui_lia_feel_sneezy": "Is about to sneeze",
"com_ui_lia_feel_sobbing": "Sobs",
"com_ui_lia_feel_starstruck": "Feels starstruck",
"com_ui_lia_feel_startled": "Feels startled",
"com_ui_lia_feel_surprised": "Feels surprised",
"com_ui_lia_feel_suspicious": "Feels suspicious",
"com_ui_lia_feel_thinking": "Thinks",
"com_ui_lia_feel_tired": "Feels tired",
"com_ui_lia_feel_whistling": "Whistles",
"com_ui_lia_feel_wink": "Winks",
"com_ui_lia_feel_yummy": "Feels yummy",
"com_ui_lia_feel_zen": "Feels zen",
"com_ui_lia_keys": "Press Enter to pet her, or the arrow keys to move her along the message box.",
"com_ui_lia_say_beep": "Beep boop",
"com_ui_lia_say_boo": "Boo!",
"com_ui_lia_say_brb": "Be right back",
"com_ui_lia_say_gg": "Good game!",
"com_ui_lia_say_haha": "Ha ha!",
"com_ui_lia_say_hi": "Hi!",
"com_ui_lia_say_hmm": "Hmm...",
"com_ui_lia_say_okay": "Okay!",
"com_ui_lia_say_oops": "Oops!",
"com_ui_lia_say_ready": "Ready!",
"com_ui_lia_say_thats_me": "That's me!",
"com_ui_lia_say_wow": "Wow!",
"com_ui_lia_say_yay": "Yay!",
"com_ui_light_theme_enabled": "Light theme enabled",
"com_ui_line_count": "{0} line",
"com_ui_lines_count": "{0} lines",

View file

@ -0,0 +1,342 @@
import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import { NEW_CHAT_PATH, sendMessage } from '../helpers';
/**
* Lia, the welcome screen mascot: off until the user opts in from Settings, standing on the
* composer clear of the greeting, waving the first message off, and absent from conversations.
*/
test.describe.configure({ timeout: 120_000 });
const lia = (page: Page) => page.getByTestId('lia');
/* The greeting rotates with the clock and some lines span the whole composer, leaving Lia no
* room by design; this morning shows the short "Good morning" line on every run. */
const MORNING = new Date(2026, 0, 14, 10, 0);
/** Opens the welcome screen; `optedIn` stores the preference before the app boots. */
async function open(page: Page, { optedIn }: { optedIn: boolean }) {
/* Only the wall clock moves to the morning: Playwright's clock would also take over timers and
* animation frames, freezing Lia's animation loop. */
await page.addInitScript((morning) => {
const RealDate = Date;
const offset = morning - RealDate.now();
class MorningDate extends RealDate {
constructor(...args: unknown[]) {
super(...((args.length ? args : [RealDate.now() + offset]) as [number]));
}
static now() {
return RealDate.now() + offset;
}
}
window.Date = MorningDate as DateConstructor;
}, MORNING.getTime());
if (optedIn) {
await page.addInitScript(() => localStorage.setItem('showLia', 'true'));
}
await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({
timeout: 15000,
});
}
const isPhone = (page: Page) => (page.viewportSize()?.width ?? 1280) <= 768;
/** Opens Settings from the account menu, which lives in the drawer on phones. */
async function openSettings(page: Page) {
if (isPhone(page)) {
const drawer = page.locator('#mobile-drawer');
await expect(drawer).toBeAttached();
await expect(async () => {
if (await drawer.evaluate((element) => element.hasAttribute('inert'))) {
await page.getByRole('button', { name: 'Open sidebar' }).click({ timeout: 2_000 });
}
await expect(drawer).not.toHaveAttribute('inert', /.*/, { timeout: 2_000 });
}).toPass({ timeout: 15_000 });
}
const account = isPhone(page)
? page.locator('#mobile-drawer').getByTestId('nav-user')
: page.getByTestId('nav-user');
await account.click();
await page.getByRole('menuitem', { name: 'Settings' }).click();
await expect(page.getByRole('heading', { name: 'Settings', exact: true })).toBeVisible({
timeout: 10000,
});
if (isPhone(page)) {
/* Phones open Settings on its section list; the General rows render once it is chosen. */
await page.getByRole('dialog').getByText('General', { exact: true }).click();
}
}
/** Closes Settings and, on phones, the drawer it was opened from. */
async function closeSettings(page: Page) {
const heading = page.getByRole('heading', { name: 'Settings', exact: true });
/* On phones the first Escape may step back to the section list before closing. */
await expect(async () => {
await page.keyboard.press('Escape');
await expect(heading).toBeHidden({ timeout: 1_000 });
}).toPass({ timeout: 10_000 });
if (isPhone(page)) {
const drawer = page.locator('#mobile-drawer');
await expect(async () => {
if (!(await drawer.evaluate((element) => element.hasAttribute('inert')))) {
await page.getByRole('button', { name: 'Close sidebar' }).click({ timeout: 2_000 });
}
await expect(drawer).toHaveAttribute('inert', /.*/, { timeout: 2_000 });
}).toPass({ timeout: 15_000 });
}
}
/** The pixels Lia's body occupies: the canvas carries transparent room for raised arms. */
async function bodyBox(page: Page) {
const box = await lia(page).boundingBox();
if (!box) {
throw new Error('Lia has no box');
}
const scale = box.width / 64;
return { x: box.x + 12 * scale, y: box.y + 20 * scale, width: 40 * scale, height: 37 * scale };
}
test.describe('Lia mascot', () => {
test('nobody sees Lia until they opt in @scenario:lia-off-by-default', async ({ page }) => {
await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({
timeout: 15000,
});
await page.waitForTimeout(1500);
await expect(lia(page)).toHaveCount(0);
});
test('turning Lia on in Settings shows her and remembers it @scenario:lia-opt-in-from-settings', async ({
page,
}) => {
await open(page, { optedIn: false });
await openSettings(page);
const toggle = page.getByTestId('showLia');
await toggle.scrollIntoViewIfNeeded();
await toggle.click();
await expect(toggle).toHaveAttribute('aria-checked', 'true');
await closeSettings(page);
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.reload();
await expect(lia(page)).toBeVisible({ timeout: 15000 });
});
test('Lia stands on the composer without covering the greeting @scenario:lia-clear-of-greeting', async ({
page,
}) => {
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(3500);
const body = await bodyBox(page);
const greeting = await page.evaluate(() => {
const content = document.querySelector('[data-chat-pane="0"]')?.firstElementChild;
if (!content) {
return null;
}
const range = document.createRange();
range.selectNodeContents(content);
const { x, y, width, height } = range.getBoundingClientRect();
return { x, y, width, height };
});
expect(greeting).not.toBeNull();
const overlaps =
greeting != null &&
body.x < greeting.x + greeting.width &&
greeting.x < body.x + body.width &&
body.y < greeting.y + greeting.height &&
greeting.y < body.y + body.height;
expect(overlaps).toBe(false);
const composer = await page.getByRole('textbox', { name: 'Message input' }).boundingBox();
expect(composer).not.toBeNull();
expect(body.y + body.height).toBeLessThanOrEqual((composer?.y ?? 0) + 4);
});
test('hovering Lia says what she is doing @scenario:lia-hover-label', async ({ page }) => {
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(3500);
const body = page.getByTestId('lia-body');
await body.hover();
await expect(body).toHaveAttribute('title', /^Lia: \S/, { timeout: 5000 });
});
test('what Lia says stays inside her stage @scenario:lia-bubble-in-stage', async ({ page }) => {
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(3500);
const input = page.getByRole('textbox', { name: 'Message input' });
await input.click();
await input.pressSequentially('hello ', { delay: 50 });
const bubble = page.getByTestId('lia-bubble');
await expect(bubble).toHaveText('Hi!', { timeout: 5000 });
const stage = await lia(page).evaluate((canvas) => {
const { x, width } = (canvas.parentElement as HTMLElement).getBoundingClientRect();
return { x, width };
});
/* Sampled while she waves, since the bubble follows her across frames. */
for (let i = 0; i < 5; i++) {
const box = await bubble.boundingBox();
if (!box) {
break;
}
expect(box.x).toBeGreaterThanOrEqual(stage.x - 1);
expect(box.x + box.width).toBeLessThanOrEqual(stage.x + stage.width + 1);
await page.waitForTimeout(200);
}
});
test('Lia waves the first message off, then leaves the conversation @scenario:lia-farewell-on-send', async ({
page,
}) => {
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(3500);
await sendMessage(page, 'Hello Lia');
await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
await expect(lia(page)).toHaveCount(0, { timeout: 5000 });
await page.reload();
await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({
timeout: 15000,
});
await page.waitForTimeout(1500);
await expect(lia(page)).toHaveCount(0);
});
test('a new chat opened during the farewell brings Lia back instead of hiding her @scenario:lia-farewell-cancelled-by-new-chat', async ({
page,
}) => {
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(3500);
const control = page.getByRole('button', { name: /^Lia: / });
await sendMessage(page, 'Hello Lia');
await expect(control).toHaveAccessibleName('Lia: Waves your message off');
/* Back on the welcome screen inside the farewell, which would hide her for five seconds; the
* header button stands in for the sidebar's link only while the sidebar is closed. */
const header = page.getByTestId('header-new-chat-button');
await (
(await header.isVisible())
? header
: page.getByRole('link', { name: 'New chat', exact: true })
).click();
await expect(page).toHaveURL(/\/c\/new/);
/* Unfixed, the farewell would keep her name on it for most of its 6.8 s. */
await expect(control).toHaveAccessibleName('Lia: Boots up', { timeout: 3000 });
await page.waitForTimeout(2500);
await expect(control).not.toHaveAccessibleName('Lia: Waves your message off');
await expect(lia(page)).toBeVisible();
});
test('a deployment that turns the mascot off hides Lia and her setting @scenario:lia-respects-deployment-opt-out', async ({
page,
}) => {
await page.route(
(url) => url.pathname === '/api/config',
async (route) => {
const response = await route.fetch();
const body = await response.json();
await route.fulfill({
response,
json: { ...body, interface: { ...body.interface, mascot: false } },
});
},
);
await open(page, { optedIn: true });
await page.waitForTimeout(2000);
await expect(lia(page)).toHaveCount(0);
await openSettings(page);
await expect(page.getByTestId('centerFormOnLanding')).toBeAttached();
await expect(page.getByTestId('showLia')).toHaveCount(0);
});
test('Lia can be picked up, carried and set down on the composer @scenario:lia-drag-to-move', async ({
page,
}) => {
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(3500);
const start = await bodyBox(page);
const composer = await page.getByRole('textbox', { name: 'Message input' }).boundingBox();
if (!composer) {
throw new Error('The composer has no box');
}
const from = { x: start.x + start.width / 2, y: start.y + start.height / 2 };
/* Toward the other end of the composer from where she stands. */
const target =
from.x > composer.x + composer.width / 2
? composer.x + composer.width * 0.15
: composer.x + composer.width * 0.85;
const lift = { x: (from.x + target) / 2, y: from.y - 60 };
const centerX = async () => {
const box = await bodyBox(page);
return box.x + box.width / 2;
};
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move(lift.x, lift.y, { steps: 10 });
/* While held she follows the pointer, off the composer. */
await expect.poll(async () => Math.abs((await centerX()) - lift.x)).toBeLessThan(start.width);
expect((await bodyBox(page)).y).toBeLessThan(start.y - 20);
await page.mouse.move(target, lift.y, { steps: 10 });
await page.mouse.up();
await page.waitForTimeout(2500);
const end = await bodyBox(page);
expect(Math.abs(end.x + end.width / 2 - target)).toBeLessThan(Math.abs(from.x - target));
expect(end.y + end.height).toBeLessThanOrEqual(composer.y + 4);
});
test('a keyboard user can pet Lia and move her along the composer @scenario:lia-keyboard-control', async ({
page,
}) => {
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(3500);
const control = page.getByRole('button', { name: /^Lia: / });
await expect(control).toHaveAccessibleDescription(/arrow keys/);
await control.focus();
await expect(control).toBeFocused();
const composer = await page.getByRole('textbox', { name: 'Message input' }).boundingBox();
if (!composer) {
throw new Error('The composer has no box');
}
/* She stops at the end of the free span she stands in, and where the greeting cuts it short
* depends on the fonts, so walk her both ways and measure the ground she covered. */
const xs = [(await bodyBox(page)).x];
for (const key of ['ArrowLeft', 'ArrowRight', 'ArrowRight'] as const) {
for (let i = 0; i < 3; i++) {
await page.keyboard.press(key);
}
await expect(control).toHaveAccessibleName('Lia: Lands with a thumbs up');
/* The landing outranks a pet, so let it finish (1.6 s) before the next key. */
await page.waitForTimeout(2000);
const box = await bodyBox(page);
expect(box.y + box.height).toBeLessThanOrEqual(composer.y + 4);
xs.push(box.x);
}
expect(Math.max(...xs) - Math.min(...xs)).toBeGreaterThan(40);
await page.keyboard.press('Enter');
await expect(control).toHaveAccessibleName('Lia: Gets petted');
});
test('with reduced motion Lia stays where she stands @scenario:lia-reduced-motion-stays-put', async ({
page,
}) => {
await page.emulateMedia({ reducedMotion: 'reduce' });
await open(page, { optedIn: true });
await expect(lia(page)).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(1500);
const first = await lia(page).boundingBox();
await page.waitForTimeout(6000);
const second = await lia(page).boundingBox();
expect(second?.x).toBe(first?.x);
expect(second?.y).toBe(first?.y);
});
});

View file

@ -267,6 +267,8 @@ interface:
create: true
share: false
public: false
# Allow Lia, the welcome screen mascot. Users still opt in from Settings (default: true).
mascot: true
# Scheduled chats are experimental and disabled unless explicitly enabled.
# A deployment with Redis-backed resumable streams can run this on every replica.
# A single-process deployment without Redis must also set

View file

@ -2731,6 +2731,8 @@ export const interfaceSchema = z
/** Tool keys (and `'mcp'` or an MCP server name) pinned to the prompt bar by default */
defaultPinnedTools: z.array(z.string()).optional(),
buildInfo: z.boolean().optional(),
/** Allows Lia, the welcome screen mascot. Users still opt in from Settings. */
mascot: z.boolean().optional(),
remoteAgents: z
.object({
use: z.boolean().optional(),
@ -2943,6 +2945,7 @@ export const interfaceSchema = z
fileSearch: true,
fileCitations: true,
buildInfo: true,
mascot: true,
remoteAgents: {
use: false,
create: false,

View file

@ -75,6 +75,18 @@ describe('loadDefaultInterface', () => {
expect(configuredInterface?.queuedTurnReconciliationTimeoutMs).toBe(180_000);
});
it('allows the mascot by default and preserves an explicit opt-out', async () => {
const configDefaults = getConfigDefaults();
const defaultInterface = await loadDefaultInterface({ config: {}, configDefaults });
expect(defaultInterface?.mascot).toBe(true);
const disabledInterface = await loadDefaultInterface({
config: { interface: { mascot: false } },
configDefaults,
});
expect(disabledInterface?.mascot).toBe(false);
});
it('uses and preserves the schema default for the queued-send lock expiry', async () => {
const configDefaults = getConfigDefaults();
const defaultInterface = await loadDefaultInterface({

View file

@ -44,6 +44,7 @@ export async function loadDefaultInterface({
customWelcome: interfaceConfig?.customWelcome ?? defaults.customWelcome,
autoSubmitFromUrl: interfaceConfig?.autoSubmitFromUrl ?? defaults.autoSubmitFromUrl,
buildInfo: interfaceConfig?.buildInfo ?? defaults.buildInfo,
mascot: interfaceConfig?.mascot ?? defaults.mascot,
contextUsage: interfaceConfig?.contextUsage ?? defaults.contextUsage,
artifactUndocking: interfaceConfig?.artifactUndocking ?? defaults.artifactUndocking,
contextCost: interfaceConfig?.contextCost ?? defaults.contextCost,