feat(webui): collapse long user messages exceeding half viewport height (#6739)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-20 22:36:30 +08:00
1 parent db0306b404
commit 09384cab26
16 files changed
+776 -21

No files matched your search

+231 -19
View File
@@ -1,7 +1,9 @@
import {
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -21,6 +23,7 @@ import { INLINE_REFERENCE_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/compon
import { MarkdownText } from "@/components/MarkdownText";
import { PendingEdgeOverlay, usePendingEdgeState, type PendingEdgeState } from "@/components/PendingEdgeOverlay";
import { SlashCommandText } from "@/components/SlashCommandText";
import { DiffViewportContext } from "@/components/thread/activity/DiffViewportContext";
import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";
import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
@@ -510,25 +513,17 @@ export function MessageBubble({
/>
) : null}
{hasText ? (
<div data-user-text-bubble className="relative ml-auto w-fit max-w-full min-w-0">
{contextMenu}
<p
data-theme-surface
data-temporary-message={temporary ? "true" : undefined}
data-pending-edge={edgeState !== "solid" ? edgeState : undefined}
className={cn(
"relative ml-auto w-fit max-w-full min-w-0 rounded-floating px-4 py-2",
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
temporary
? "border border-dashed border-muted-foreground/40 bg-transparent"
: "user-message-surface bg-secondary/70",
showProcessingStatus && "user-message-surface-dashed",
)}
>
<PendingEdgeOverlay state={edgeState} onSealEnd={completeSeal} />
{messageText}
</p>
</div>
<UserTextBubble
messageId={message.id}
contentKey={userContent}
temporary={temporary}
showProcessingStatus={showProcessingStatus}
edgeState={edgeState}
onSealEnd={completeSeal}
contextMenu={contextMenu}
>
{messageText}
</UserTextBubble>
) : null}
{!showDeliveryStatus && showProcessingStatus ? (
<span role="status" className="sr-only">
@@ -591,6 +586,223 @@ export function MessageBubble({
);
}
const USER_MESSAGE_COLLAPSE_THRESHOLD_RATIO = 0.5;
const USER_MESSAGE_COLLAPSED_HEIGHT_RATIO = 0.38;
const MIN_USER_MESSAGE_COLLAPSE_THRESHOLD_PX = 200;
const MIN_USER_MESSAGE_COLLAPSED_BUBBLE_PX = 160;
const MIN_USER_MESSAGE_COLLAPSED_TEXT_PX = 96;
const DEFAULT_COLLAPSIBLE_PADDING_BOTTOM_PX = 40;
const COLLAPSE_SCROLL_TOP_INSET_PX = 48;
interface UserTextCollapseLayout {
collapsible: boolean;
fullTextHeight: number;
collapsedTextHeight: number;
}
interface UserTextBubbleProps {
messageId: string;
contentKey: string;
temporary: boolean;
showProcessingStatus: boolean;
edgeState: PendingEdgeState;
onSealEnd: () => void;
contextMenu?: ReactNode;
children: ReactNode;
}
function UserTextBubble({
messageId,
contentKey,
temporary,
showProcessingStatus,
edgeState,
onSealEnd,
contextMenu,
children,
}: UserTextBubbleProps) {
const { t } = useTranslation();
const viewport = useContext(DiffViewportContext);
const bubbleRef = useRef<HTMLParagraphElement>(null);
const contentRef = useRef<HTMLSpanElement>(null);
const contentId = useId();
const [layout, setLayout] = useState<UserTextCollapseLayout | null>(null);
const [expandedForId, setExpandedForId] = useState<string | null>(null);
const expanded = expandedForId === messageId;
const isCollapsible = layout?.collapsible ?? false;
const isCollapsed = isCollapsible && !expanded;
useLayoutEffect(() => {
const bubble = bubbleRef.current;
if (!bubble) return;
const scroller = viewport?.scroller.current ?? null;
const measure = () => {
const currentBubble = bubbleRef.current;
if (!currentBubble) return;
const scrollerHeight = scroller?.clientHeight ?? 0;
const referenceHeight = scrollerHeight > 0 ? scrollerHeight : window.innerHeight;
if (!Number.isFinite(referenceHeight) || referenceHeight <= 0) return;
const style = getComputedStyle(currentBubble);
const paddingTop = Number.parseFloat(style.paddingTop) || 0;
const paddingBottom = Number.parseFloat(style.paddingBottom) || 0;
const normalPaddingY = paddingTop * 2;
const content = contentRef.current;
const fullTextHeight = content
? content.scrollHeight
: Math.max(0, currentBubble.scrollHeight - paddingTop - paddingBottom);
if (fullTextHeight <= 0) return;
const naturalBubbleHeight = fullTextHeight + normalPaddingY;
const collapseThreshold = Math.max(
MIN_USER_MESSAGE_COLLAPSE_THRESHOLD_PX,
Math.round(referenceHeight * USER_MESSAGE_COLLAPSE_THRESHOLD_RATIO),
);
const collapsible = naturalBubbleHeight > collapseThreshold;
const collapsedPaddingY = content
? paddingTop + paddingBottom
: paddingTop + DEFAULT_COLLAPSIBLE_PADDING_BOTTOM_PX;
const targetBubbleHeight = Math.max(
MIN_USER_MESSAGE_COLLAPSED_BUBBLE_PX,
Math.round(referenceHeight * USER_MESSAGE_COLLAPSED_HEIGHT_RATIO),
);
const collapsedTextHeight = Math.min(
fullTextHeight,
Math.max(MIN_USER_MESSAGE_COLLAPSED_TEXT_PX, targetBubbleHeight - collapsedPaddingY),
);
setLayout((current) => (
current?.collapsible === collapsible
&& current.fullTextHeight === fullTextHeight
&& current.collapsedTextHeight === collapsedTextHeight
? current
: { collapsible, fullTextHeight, collapsedTextHeight }
));
};
measure();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
observer?.observe(contentRef.current ?? bubble);
if (scroller) observer?.observe(scroller);
window.addEventListener("resize", measure);
return () => {
observer?.disconnect();
window.removeEventListener("resize", measure);
};
}, [contentKey, isCollapsible, messageId, viewport]);
const toggleCollapsed = useCallback(() => {
if (expanded) {
const bubble = bubbleRef.current;
if (bubble) {
const scroller = viewport?.scroller.current ?? null;
if (scroller) {
const scrollerRect = scroller.getBoundingClientRect();
const bubbleRect = bubble.getBoundingClientRect();
if (bubbleRect.top < scrollerRect.top + COLLAPSE_SCROLL_TOP_INSET_PX) {
const targetTop = Math.max(
0,
scroller.scrollTop + (bubbleRect.top - scrollerRect.top) - COLLAPSE_SCROLL_TOP_INSET_PX,
);
scroller.scrollTo({ top: targetTop, behavior: "auto" });
}
} else if (bubble.getBoundingClientRect().top < 16) {
bubble.scrollIntoView({ block: "nearest" });
}
}
setExpandedForId(null);
return;
}
setExpandedForId(messageId);
}, [expanded, messageId, viewport]);
const clipHeight = layout
? (isCollapsed ? layout.collapsedTextHeight : layout.fullTextHeight)
: undefined;
return (
<div
data-user-text-bubble
data-user-message-collapsible={isCollapsible ? "true" : undefined}
data-user-message-collapsed={isCollapsed ? "true" : undefined}
className="relative ml-auto w-fit max-w-full min-w-0"
>
{contextMenu}
<p
ref={bubbleRef}
id={isCollapsible ? contentId : undefined}
data-theme-surface
data-temporary-message={temporary ? "true" : undefined}
data-pending-edge={edgeState !== "solid" ? edgeState : undefined}
className={cn(
"relative ml-auto w-fit max-w-full min-w-0 rounded-floating px-4 py-2",
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
temporary
? "border border-dashed border-muted-foreground/40 bg-transparent"
: "user-message-surface bg-secondary/70",
showProcessingStatus && "user-message-surface-dashed",
isCollapsible && "user-message-collapsible",
)}
>
<PendingEdgeOverlay state={edgeState} onSealEnd={onSealEnd} />
{isCollapsible ? (
<span
data-user-message-clip
data-state={isCollapsed ? "closed" : "open"}
className={cn(
"user-message-collapsible-body block overflow-hidden",
isCollapsed && "user-message-collapsible-masked",
)}
style={clipHeight !== undefined ? { height: clipHeight } : undefined}
>
<span ref={contentRef} className="block">
{children}
</span>
</span>
) : (
children
)}
</p>
{isCollapsible ? (
<>
<div
data-user-message-stack
data-state={isCollapsed ? "visible" : "hidden"}
data-temporary={temporary ? "true" : undefined}
aria-hidden="true"
className="user-message-stack pointer-events-none flex flex-col"
>
<span className="user-message-stack-sheet user-message-stack-sheet-first" />
<span className="user-message-stack-sheet user-message-stack-sheet-second" />
</div>
<div
data-user-message-toggle-bar
className="user-message-toggle-bar pointer-events-none absolute inset-x-0 z-[2] flex items-center justify-center px-3 pb-1.5 pt-1"
>
<button
type="button"
data-thread-disclosure=""
data-user-message-toggle
aria-expanded={!isCollapsed}
aria-controls={contentId}
onClick={toggleCollapsed}
className={cn(
"pointer-events-auto touch-target inline-flex h-7 items-center rounded-full px-3.5",
"text-ui-label text-muted-foreground transition-colors",
"hover:bg-foreground/[0.06] hover:text-foreground dark:hover:bg-foreground/[0.09]",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
)}
>
{isCollapsed ? t("message.expandUserMessage") : t("message.collapseUserMessage")}
</button>
</div>
</>
) : null}
</div>
);
}
function UserQuotedContext({ text, label }: { text: string; label: string }) {
return (
<blockquote
+124 -1
View File
@@ -761,9 +761,19 @@
overflow: hidden;
}
@media (prefers-reduced-motion: no-preference) {
.expandable-text {
.expandable-text,
.user-message-collapsible-body {
transition: height 240ms cubic-bezier(0.4, 0, 0.2, 1);
}
.user-message-toggle-bar {
transition: bottom 240ms cubic-bezier(0.4, 0, 0.2, 1);
}
.user-message-stack {
transition: height 240ms cubic-bezier(0.4, 0, 0.2, 1), opacity 180ms ease-out;
}
.user-message-stack-sheet {
transition: transform 200ms cubic-bezier(0.2, 0.8, 0.2, 1), opacity 180ms ease-out;
}
.inline-disclosure {
transition:
grid-template-rows var(--inline-disclosure-duration)
@@ -1227,6 +1237,101 @@
--tw-shadow: var(--surface-depth-shadow);
}
.user-message-collapsible {
padding-bottom: 2.5rem;
}
.user-message-collapsible-masked {
-webkit-mask-image: linear-gradient(to bottom, #000 0%, #000 calc(100% - 2.75rem), transparent 100%);
mask-image: linear-gradient(to bottom, #000 0%, #000 calc(100% - 2.75rem), transparent 100%);
}
[data-user-text-bubble][data-user-message-collapsed="true"] {
--user-message-stack-height: 10px;
}
.user-message-toggle-bar {
bottom: var(--user-message-stack-height, 0px);
}
.user-message-stack {
--composer-shadow-color: 240 10% 16%;
height: 10px;
overflow: visible;
opacity: 1;
}
.dark .user-message-stack {
--composer-shadow-color: 240 12% 3%;
}
.user-message-stack[data-state="hidden"] {
height: 0;
overflow: hidden;
opacity: 0;
}
.user-message-stack-sheet {
display: block;
height: 5px;
border-inline: 1px solid hsl(var(--border) / 0.82);
border-bottom: 1px solid hsl(var(--border) / 0.82);
background-color: hsl(var(--secondary) / 0.62);
box-shadow: 0 2px 6px -2px hsl(var(--composer-shadow-color) / 0.1);
}
.dark .user-message-stack-sheet {
border-color: hsl(var(--border) / 0.92);
}
.user-message-stack-sheet-first {
margin-inline: 1rem;
border-bottom-left-radius: 0.625rem;
border-bottom-right-radius: 0.625rem;
}
.user-message-stack-sheet-second {
margin-inline: 2rem;
border-bottom-left-radius: 0.5rem;
border-bottom-right-radius: 0.5rem;
border-color: hsl(var(--border) / 0.62);
background-color: hsl(var(--secondary) / 0.42);
box-shadow: 0 2px 6px -2px hsl(var(--composer-shadow-color) / 0.08);
}
.dark .user-message-stack-sheet-second {
border-color: hsl(var(--border) / 0.68);
}
.user-message-stack[data-state="hidden"] .user-message-stack-sheet {
transform: translateY(-5px);
}
.user-message-stack[data-temporary="true"] .user-message-stack-sheet {
background-color: transparent;
border-style: dashed;
border-color: hsl(var(--muted-foreground) / 0.34);
}
.user-message-stack[data-temporary="true"] .user-message-stack-sheet-second {
border-color: hsl(var(--muted-foreground) / 0.22);
}
@media (hover: hover) and (prefers-reduced-motion: no-preference) {
[data-user-text-bubble][data-user-message-collapsed="true"]:has([data-user-message-toggle]:hover) .user-message-stack-sheet-first {
transform: translateY(1px);
}
[data-user-text-bubble][data-user-message-collapsed="true"]:has([data-user-message-toggle]:hover) .user-message-stack-sheet-second {
transform: translateY(2px);
}
}
@media (pointer: coarse) {
.user-message-collapsible {
padding-bottom: 3.25rem;
}
}
.pending-edge-overlay {
--pending-edge-progress: -20%;
--pending-edge-solid-color: hsl(var(--border) / 0.75);
@@ -1457,6 +1562,16 @@
@media (forced-colors: active) {
.thread-composer-surface, .composer-palette-surface, .context-inspector-surface, .user-message-surface, .side-panel-surface { outline: 1px solid CanvasText; }
.user-message-surface-dashed { outline-style: dashed; }
.user-message-collapsible-masked {
-webkit-mask-image: none;
mask-image: none;
}
[data-user-message-toggle] {
border: 1px solid ButtonBorder;
}
.user-message-stack-sheet {
border-color: CanvasText;
}
.pending-edge-overlay { display: none; }
:has(> .pending-edge-overlay[data-solid-tone="card"][data-pending-edge-overlay="pending"]) {
border-color: CanvasText;
@@ -2193,6 +2308,14 @@ html[data-custom-background] .side-panel-surface {
background-color: hsl(var(--settings-surface) / 0.78);
backdrop-filter: blur(12px);
}
html[data-custom-background] .user-message-stack:not([data-temporary="true"]) .user-message-stack-sheet-first {
background-color: hsl(var(--settings-surface) / 0.56);
backdrop-filter: blur(10px);
}
html[data-custom-background] .user-message-stack:not([data-temporary="true"]) .user-message-stack-sheet-second {
background-color: hsl(var(--settings-surface) / 0.38);
backdrop-filter: blur(10px);
}
html[data-custom-background] aside.bg-settings-surface {
background-color: hsl(var(--settings-surface) / 0.65);
}
+2
View File
@@ -2576,6 +2576,8 @@
"fallbackResponse": "This reply switched to a fallback model, answered by {{preset}}.",
"copyReply": "Copy",
"copiedReply": "Copied",
"expandUserMessage": "Show more",
"collapseUserMessage": "Show less",
"turnLatencyTitle": "Response time (end-to-end)",
"fileEditViewDiff": "View changes",
"fileEditViewLargeDiff": "Expand changes",
+2
View File
@@ -2188,6 +2188,8 @@
"fallbackResponse": "Esta respuesta usa un modelo de respaldo: {{preset}}.",
"copyReply": "Copiar",
"copiedReply": "Copiado",
"expandUserMessage": "Mostrar más",
"collapseUserMessage": "Mostrar menos",
"turnLatencyTitle": "Tiempo de respuesta (extremo a extremo)",
"fileEditViewDiff": "Ver cambios",
"fileEditViewLargeDiff": "Expandir cambios",
+2
View File
@@ -2188,6 +2188,8 @@
"fallbackResponse": "Cette réponse utilise un modèle de secours : {{preset}}.",
"copyReply": "Copier",
"copiedReply": "Copié",
"expandUserMessage": "Afficher plus",
"collapseUserMessage": "Afficher moins",
"turnLatencyTitle": "Temps de réponse (de bout en bout)",
"fileEditViewDiff": "Voir les modifications",
"fileEditViewLargeDiff": "Déplier les modifications",
+2
View File
@@ -2188,6 +2188,8 @@
"fallbackResponse": "Balasan ini beralih ke model cadangan dan dijawab oleh {{preset}}.",
"copyReply": "Salin",
"copiedReply": "Disalin",
"expandUserMessage": "Tampilkan lebih banyak",
"collapseUserMessage": "Tampilkan lebih sedikit",
"turnLatencyTitle": "Waktu respons (ujung ke ujung)",
"fileEditViewDiff": "Lihat perubahan",
"fileEditViewLargeDiff": "Perluas perubahan",
+2
View File
@@ -2188,6 +2188,8 @@
"fallbackResponse": "この返信では代替モデルに切り替わり、{{preset}} が回答しています。",
"copyReply": "コピー",
"copiedReply": "コピー済み",
"expandUserMessage": "さらに表示",
"collapseUserMessage": "折りたたむ",
"turnLatencyTitle": "応答時間(全行程)",
"fileEditViewDiff": "変更を表示",
"fileEditViewLargeDiff": "変更を展開",
+2
View File
@@ -2188,6 +2188,8 @@
"fallbackResponse": "이 응답은 대체 모델로 전환되어 {{preset}}이(가) 답변합니다.",
"copyReply": "복사",
"copiedReply": "복사됨",
"expandUserMessage": "더 보기",
"collapseUserMessage": "접기",
"turnLatencyTitle": "응답 시간(엔드투엔드)",
"fileEditViewDiff": "변경 보기",
"fileEditViewLargeDiff": "변경 펼치기",
+2
View File
@@ -2396,6 +2396,8 @@
"fallbackResponse": "Esta resposta usa um modelo alternativo: {{preset}}.",
"copyReply": "Copiar",
"copiedReply": "Copiado",
"expandUserMessage": "Mostrar mais",
"collapseUserMessage": "Mostrar menos",
"turnLatencyTitle": "Tempo de resposta (ponta a ponta)",
"fileEditViewDiff": "Ver alterações",
"fileEditViewLargeDiff": "Expandir alterações",
+2
View File
@@ -2188,6 +2188,8 @@
"fallbackResponse": "Phản hồi này đã chuyển sang mô hình dự phòng, do {{preset}} trả lời.",
"copyReply": "Sao chép",
"copiedReply": "Đã sao chép",
"expandUserMessage": "Hiển thị thêm",
"collapseUserMessage": "Thu gọn",
"turnLatencyTitle": "Thời gian phản hồi (end-to-end)",
"fileEditViewDiff": "Xem thay đổi",
"fileEditViewLargeDiff": "Mở rộng thay đổi",
+2
View File
@@ -2576,6 +2576,8 @@
"fallbackResponse": "本条回复已切换至备用模型,由 {{preset}} 回答。",
"copyReply": "复制",
"copiedReply": "已复制",
"expandUserMessage": "展开",
"collapseUserMessage": "收起",
"turnLatencyTitle": "回复耗时",
"fileEditViewDiff": "查看修改",
"fileEditViewLargeDiff": "展开修改",
+2
View File
@@ -2187,6 +2187,8 @@
"fallbackResponse": "本則回覆已切換至備用模型,由 {{preset}} 回答。",
"copyReply": "複製",
"copiedReply": "已複製",
"expandUserMessage": "展開",
"collapseUserMessage": "收起",
"turnLatencyTitle": "回覆耗時",
"fileEditViewDiff": "檢視修改",
"fileEditViewLargeDiff": "展開修改",
+61
View File
@@ -1509,4 +1509,65 @@ describe("MessageBubble", () => {
expect(screen.queryByRole("link", { name: "Download growth.svg" })).not.toBeInTheDocument();
});
it("collapses user messages taller than half the viewport and restores them on toggle or resize", () => {
let textHeight = 620;
let resize: ResizeObserverCallback | undefined;
const disconnect = vi.fn();
vi.spyOn(window, "innerHeight", "get").mockReturnValue(800);
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(function (this: HTMLElement) {
if (this.tagName === "P" || this.parentElement?.hasAttribute("data-user-message-clip")) {
return textHeight;
}
return 0;
});
vi.stubGlobal("ResizeObserver", class {
constructor(callback: ResizeObserverCallback) { resize = callback; }
observe() {}
disconnect = disconnect;
});
try {
const content = Array.from({ length: 24 }, (_, i) => `Line ${i + 1}: detailed release log entry`).join("\n");
const message: UIMessage = {
id: "u-long",
role: "user",
content,
createdAt: Date.now(),
};
const { container, unmount } = render(<MessageBubble message={message} />);
const wrapper = container.querySelector("[data-user-text-bubble]")!;
const toggle = screen.getByRole("button", { name: "Show more" });
const clip = container.querySelector("[data-user-message-clip]") as HTMLElement;
expect(wrapper).toHaveAttribute("data-user-message-collapsible", "true");
expect(wrapper).toHaveAttribute("data-user-message-collapsed", "true");
expect(toggle).toHaveAttribute("aria-expanded", "false");
expect(toggle).toHaveAttribute("data-thread-disclosure", "");
expect(toggle.getAttribute("aria-controls")).toBe(container.querySelector("[data-user-text-bubble] > p")?.id);
expect(clip).toHaveClass("user-message-collapsible-masked");
expect(clip.style.height).toBe("304px");
fireEvent.click(toggle);
expect(wrapper).not.toHaveAttribute("data-user-message-collapsed");
expect(screen.getByRole("button", { name: "Show less" })).toHaveAttribute("aria-expanded", "true");
expect(clip).not.toHaveClass("user-message-collapsible-masked");
expect(clip.style.height).toBe("620px");
fireEvent.click(screen.getByRole("button", { name: "Show less" }));
expect(wrapper).toHaveAttribute("data-user-message-collapsed", "true");
expect(clip.style.height).toBe("304px");
textHeight = 320;
act(() => { resize?.([], {} as ResizeObserver); });
expect(wrapper).not.toHaveAttribute("data-user-message-collapsible");
expect(screen.queryByRole("button", { name: "Show more" })).not.toBeInTheDocument();
unmount();
expect(disconnect).toHaveBeenCalled();
} finally {
vi.restoreAllMocks();
vi.unstubAllGlobals();
}
});
});