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

+5 -1
View File
@@ -73,6 +73,10 @@ async function loadFixture() {
const { MobileChatLayoutFixture } = await import("./mobile-chat-layout-fixture");
return withClient(<MobileChatLayoutFixture parameters={parameters} />);
}
case "long-user-message": {
const { LongUserMessageFixture } = await import("./long-user-message-fixture");
return withClient(<LongUserMessageFixture parameters={parameters} />);
}
case "composer-action": {
const { ComposerActionFixture, installMissingMicrophonePreview } = await import("./composer-action-fixture");
if (parameters.get("voiceError") === "noDevice") installMissingMicrophonePreview();
@@ -228,7 +232,7 @@ if (fixtureCase === "toast" && parameters.has("lang")) {
if (previous === null) localStorage.removeItem(LOCALE_STORAGE_KEY);
else localStorage.setItem(LOCALE_STORAGE_KEY, previous);
}
if ((["appearance", "session-transition", "tools-catalog"].includes(fixtureCase ?? "") || historyPreview) && parameters.has("lang")) {
if ((["appearance", "long-user-message", "session-transition", "tools-catalog"].includes(fixtureCase ?? "") || historyPreview) && parameters.has("lang")) {
await setAppLanguage(normalizeLocale(parameters.get("lang")));
}
createRoot(document.getElementById("root")!).render(<TooltipProvider>{fixture}</TooltipProvider>);
+187
View File
@@ -0,0 +1,187 @@
import { useEffect, useState } from "react";
import { CalendarClock, ListFilter } from "lucide-react";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";
import { ThreadHeader } from "@/components/thread/ThreadHeader";
import { ThreadViewport } from "@/components/thread/ThreadViewport";
import { Button } from "@/components/ui/button";
import type { UIMessage, WorkspaceScopePayload, WorkspacesPayload } from "@/lib/types";
const LONG_USER_MESSAGE_EN = [
"Can you review this release checklist and the deployment log below before we cut v0.9.4?",
"",
"Release checklist:",
"1. Verify WebSocket reconnection restores pending prompts and preserves turn order across idle reconnects.",
"2. Confirm SQLite WAL compaction does not block active session reads during high-throughput tool runs.",
"3. Check mobile Safari safe-area bottom inset when the soft keyboard opens and closes repeatedly.",
"4. Validate custom background blur contrast on composer, side panel, and user message bubbles in both themes.",
"5. Inspect slash command and skill palette keyboard navigation on narrow viewports.",
"6. Ensure fallback model badges stay aligned with response metadata after streaming finishes.",
"",
"Recent staging deployment output:",
"[10:12:04] gateway.startup: loaded 14 skills, 3 MCP presets, 2 active channels (websocket, telegram)",
"[10:12:05] session.sqlite: WAL checkpoint completed in 11ms (0 busy retries, 184 sessions indexed)",
"[10:12:08] webui.assets: serving production bundle hash 9a4f2c18 from nanobot/web/dist",
"[10:12:14] agent.runner: turn #412 started with model preset default (context 24,180 / 200,000 tokens)",
"[10:12:16] tools.exec: ran `pytest tests/webui/test_transcript.py` -> 28 passed in 1.42s",
"[10:12:19] tools.exec: ran `vitest run src/tests/message-bubble.test.tsx` -> 46 passed in 0.98s",
"[10:12:24] agent.runner: turn #412 completed in 9.8s with 0 retries and 0 fallback switches",
"[10:12:31] health.probe: ws_roundtrip_ms=14 http_status=200 memory_rss_mb=138",
"",
"Open questions for the final pass:",
"- Should we keep the existing prompt navigation shortcut on macOS and Linux unchanged?",
"- Do any channel plugins rely on the deprecated settings schema fields?",
"- Can we summarize the changelog highlights into three crisp bullets for the release notes?",
"- Final line sentinel: please confirm every item above is ready to ship.",
].join("\n");
const LONG_USER_MESSAGE_ZH = [
"帮我核对一下 v0.9.4 发布前的检查清单和预发环境日志,看看还有没有遗漏的风险点:",
"",
"发布检查清单:",
"1. 确认 WebSocket 断线重连后,排队中的用户消息能恢复顺序且不会重复提交。",
"2. 确认 SQLite WAL 写入在高频工具调用期间不会阻塞会话历史分页查询。",
"3. 检查移动端 Safari 软键盘反复弹出/收起时,底部安全区域和输入框间距是否稳定。",
"4. 核对自定义壁纸模式下,输入框、侧边栏和用户气泡在浅色与深色主题下的毛玻璃对比度。",
"5. 检查窄屏下 `/` 命令面板与 `$` 技能面板的键盘上下导航与滚屏表现。",
"6. 确认流式回复完成后,回退模型标识与时间戳在操作菜单中展示一致。",
"",
"预发环境部署日志:",
"[10:12:04] gateway.startup: 已加载 14 个技能、3 个 MCP 预设、2 个活跃渠道(websocket、telegram)",
"[10:12:05] session.sqlite: WAL 检查点耗时 11ms(0 次锁等待,已索引 184 个会话)",
"[10:12:08] webui.assets: 已挂载生产构建产物 9a4f2c18(nanobot/web/dist)",
"[10:12:14] agent.runner: 回合 #412 启动,当前上下文 24,180 / 200,000 tokens",
"[10:12:16] tools.exec: 运行 pytest tests/webui/test_transcript.py -> 28 项全部通过(1.42s)",
"[10:12:19] tools.exec: 运行 vitest run src/tests/message-bubble.test.tsx -> 46 项全部通过(0.98s)",
"[10:12:24] agent.runner: 回合 #412 完成,总耗时 9.8s,0 次重试,0 次模型回退",
"[10:12:31] health.probe: ws_roundtrip_ms=14 http_status=200 memory_rss_mb=138",
"",
"最后需要确认的事项:",
"- macOS 与 Linux 的提示词导航快捷键是否保持不变?",
"- 现有渠道插件是否还依赖已废弃的配置字段?",
"- 能否把本次变更提炼为 3 条简明发布说明?",
"- 末尾标记:请确认以上全部检查项都已就绪。",
].join("\n");
const initialScope: WorkspaceScopePayload = {
project_path: "/projects/nanobot",
project_name: "nanobot",
access_mode: "full",
};
const catalog: WorkspacesPayload = {
schema_version: 1,
default_access_mode: "full",
default_scope: initialScope,
recent_projects: [{ path: "/projects/nanobot", name: "nanobot" }],
controls: { can_change_project: true },
};
export function LongUserMessageFixture({ parameters }: { parameters: URLSearchParams }) {
const [dark, setDark] = useState(parameters.has("dark"));
const [scope, setScope] = useState<WorkspaceScopePayload>(initialScope);
const zh = parameters.get("lang")?.startsWith("zh") ?? false;
useEffect(() => {
document.documentElement.classList.toggle("dark", dark);
}, [dark]);
const messages: UIMessage[] = zh
? [
{
id: "short-user",
role: "user",
content: "先把这次发版要检查的重点发你一下。",
createdAt: 1_700_000_000_000,
},
{
id: "short-assistant",
role: "assistant",
content: "好的,发过来我逐条核对。",
createdAt: 1_700_000_001_000,
},
{
id: "long-user",
role: "user",
content: LONG_USER_MESSAGE_ZH,
createdAt: 1_700_000_002_000,
},
{
id: "long-assistant",
role: "assistant",
content: "已逐项核对完清单与预发日志,目前 6 项核心检查和健康探针状态均正常。\n\n**发布前建议**\n- 保持现有快捷键不变,避免影响老用户肌肉记忆。\n- 所有内置渠道已迁移到新配置结构,无废弃字段残留。\n- 发布说明已可按「交互优化 / 稳定性提升 / 移动端体验」三条整理。",
createdAt: 1_700_000_003_000,
},
]
: [
{
id: "short-user",
role: "user",
content: "Sending over the release checklist next.",
createdAt: 1_700_000_000_000,
},
{
id: "short-assistant",
role: "assistant",
content: "Ready whenever you are — share the checklist and logs.",
createdAt: 1_700_000_001_000,
},
{
id: "long-user",
role: "user",
content: LONG_USER_MESSAGE_EN,
createdAt: 1_700_000_002_000,
},
{
id: "long-assistant",
role: "assistant",
content: "Everything in the staging log and checklist looks healthy.\n\n**Release notes draft**\n- Keep prompt navigation shortcuts unchanged across platforms.\n- All built-in channel plugins are already migrated off deprecated settings fields.\n- Ready to summarize the release into UX polish, runtime stability, and mobile layout updates.",
createdAt: 1_700_000_003_000,
},
];
return (
<main className="thread-workspace relative flex min-w-0 flex-col overflow-hidden bg-background" style={{ height: "100dvh" }}>
<ThreadHeader
title={zh ? "v0.9.4 发布核对" : "v0.9.4 Release Review"}
hideTitle
theme={dark ? "dark" : "light"}
onToggleSidebar={() => {}}
onToggleTheme={() => setDark((value) => !value)}
sessionInfoAction={<Button variant="ghost" size="icon" aria-label="Session details"><CalendarClock className="h-3.5 w-3.5" /></Button>}
promptNavigatorAction={<Button variant="ghost" size="icon" aria-label="Conversation navigation"><ListFilter className="h-3.5 w-3.5" /></Button>}
/>
<ComposerUsagePopover context={{ contextTokens: 24_180, contextWindowTokens: 200_000 }} rounds={[]}>
{(renderContextUsage) => (
<ThreadViewport
messages={messages}
isStreaming={false}
conversationReady
conversationKey="websocket:long-user-message-preview"
hasMoreBefore={false}
showScrollToBottomButton
composer={(
<ThreadComposer
variant="thread"
onSend={() => {}}
modelLabel="claude-sonnet-4"
modelProvider="anthropic"
onTranscribeAudio={async () => ""}
renderContextUsage={renderContextUsage}
workspaceScope={scope}
workspaceDefaultScope={initialScope}
workspaceControls={catalog.controls}
workspaceProjectLocked
onWorkspaceScopeChange={setScope}
onLoadWorkspaceProjects={async () => catalog}
onResolveWorkspaceProject={async (path) => ({ path, name: "nanobot" })}
onFavoriteWorkspaceProject={async () => []}
onBrowseWorkspaceDirectories={async (path) => ({ path, parent: null, entries: [], truncated: false, host: "preview", platform: "Linux" })}
/>
)}
/>
)}
</ComposerUsagePopover>
</main>
);
}
+148
View File
@@ -0,0 +1,148 @@
import { expect, test } from "@playwright/test";
for (const theme of ["light", "dark"] as const) {
for (const width of [1280, 390]) {
test(`collapses user messages exceeding half viewport height at ${width}px in ${theme}`, async ({ page }) => {
await page.setViewportSize({ width, height: 844 });
await page.goto(`/browser/fixture.html?case=long-user-message${theme === "dark" ? "&dark" : ""}`);
const bubbles = page.locator("[data-user-text-bubble]");
await expect(bubbles).toHaveCount(2);
const shortBubble = bubbles.first();
const longBubble = bubbles.last();
await expect(shortBubble).not.toHaveAttribute("data-user-message-collapsible");
await expect(shortBubble.locator("[data-user-message-toggle]")).toHaveCount(0);
await expect(longBubble).toHaveAttribute("data-user-message-collapsible", "true");
await expect(longBubble).toHaveAttribute("data-user-message-collapsed", "true");
const toggle = longBubble.locator("[data-user-message-toggle]");
const stack = longBubble.locator("[data-user-message-stack]");
await expect(toggle).toBeVisible();
await expect(toggle).toHaveAttribute("aria-expanded", "false");
await expect(toggle).toHaveAttribute("data-thread-disclosure", "");
await expect(toggle).toHaveText("Show more");
await expect(stack).toHaveAttribute("data-state", "visible");
const collapsedMetrics = await page.evaluate(() => {
const scroller = document.querySelector<HTMLElement>("[data-testid='thread-message-region']")!;
const longRow = document.querySelectorAll<HTMLElement>("[data-user-text-bubble]")[1]!;
const pill = longRow.querySelector<HTMLElement>(":scope > p")!;
const clip = pill.querySelector<HTMLElement>("[data-user-message-clip]")!;
const stackEl = longRow.querySelector<HTMLElement>("[data-user-message-stack]")!;
const toggleEl = longRow.querySelector<HTMLElement>("[data-user-message-toggle]")!;
const scrollerRect = scroller.getBoundingClientRect();
const pillRect = pill.getBoundingClientRect();
const stackRect = stackEl.getBoundingClientRect();
const toggleRect = toggleEl.getBoundingClientRect();
const clipStyle = getComputedStyle(clip);
return {
scrollerHeight: scrollerRect.height,
pillHeight: pillRect.height,
stackHeight: stackRect.height,
clipHeight: clip.getBoundingClientRect().height,
naturalTextHeight: clip.firstElementChild!.getBoundingClientRect().height,
maskImage: clipStyle.maskImage || clipStyle.webkitMaskImage,
toggleInsidePill: toggleRect.top >= pillRect.top && toggleRect.bottom <= pillRect.bottom + 1,
toggleBottomGap: pillRect.bottom - toggleRect.bottom,
pageOverflows: document.documentElement.scrollWidth > innerWidth,
};
});
expect(collapsedMetrics.pageOverflows).toBe(false);
expect(collapsedMetrics.naturalTextHeight).toBeGreaterThan(collapsedMetrics.scrollerHeight * 0.5);
expect(collapsedMetrics.pillHeight).toBeLessThanOrEqual(collapsedMetrics.scrollerHeight * 0.5);
expect(collapsedMetrics.stackHeight).toBeGreaterThan(6);
expect(collapsedMetrics.clipHeight).toBeLessThan(collapsedMetrics.naturalTextHeight - 60);
expect(collapsedMetrics.maskImage).toContain("linear-gradient");
expect(collapsedMetrics.toggleInsidePill).toBe(true);
expect(collapsedMetrics.toggleBottomGap).toBeGreaterThanOrEqual(4);
await toggle.click();
await expect(longBubble).not.toHaveAttribute("data-user-message-collapsed");
await expect(toggle).toHaveAttribute("aria-expanded", "true");
await expect(toggle).toHaveText("Show less");
await expect(stack).toHaveAttribute("data-state", "hidden");
await expect.poll(async () => {
return longBubble.evaluate((el) => {
const clip = el.querySelector<HTMLElement>("[data-user-message-clip]")!;
const stackEl = el.querySelector<HTMLElement>("[data-user-message-stack]")!;
return Math.abs(clip.getBoundingClientRect().height - clip.firstElementChild!.getBoundingClientRect().height)
+ stackEl.getBoundingClientRect().height;
});
}).toBeLessThan(2);
const expandedMetrics = await longBubble.evaluate((el) => {
const pill = el.querySelector<HTMLElement>(":scope > p")!;
const clip = pill.querySelector<HTMLElement>("[data-user-message-clip]")!;
const toggleEl = el.querySelector<HTMLElement>("[data-user-message-toggle]")!;
const clipRect = clip.getBoundingClientRect();
const toggleRect = toggleEl.getBoundingClientRect();
const clipStyle = getComputedStyle(clip);
return {
pillHeight: pill.getBoundingClientRect().height,
maskImage: clipStyle.maskImage || clipStyle.webkitMaskImage,
textClearsToggle: clipRect.bottom <= toggleRect.top + 1,
pageOverflows: document.documentElement.scrollWidth > innerWidth,
};
});
expect(expandedMetrics.pageOverflows).toBe(false);
expect(expandedMetrics.pillHeight).toBeGreaterThan(collapsedMetrics.pillHeight + 100);
expect(expandedMetrics.maskImage).toBe("none");
expect(expandedMetrics.textClearsToggle).toBe(true);
await toggle.click();
await expect(longBubble).toHaveAttribute("data-user-message-collapsed", "true");
await expect(toggle).toHaveAttribute("aria-expanded", "false");
await expect(toggle).toHaveText("Show more");
});
}
}
test("copies full user message text while collapsed and anchors scroll when collapsing from bottom", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.goto("/browser/fixture.html?case=long-user-message");
const longUnit = page.locator("[data-user-prompt-id='long-user']");
const longBubble = longUnit.locator("[data-user-text-bubble]");
await expect(longBubble).toHaveAttribute("data-user-message-collapsed", "true");
await longUnit.hover();
await longUnit.getByRole("button", { name: "Message actions", exact: true }).click();
await page.locator("[data-message-block-menu]").getByRole("button", { name: "Copy", exact: true }).click();
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toContain("Final line sentinel");
await page.keyboard.press("Escape");
const toggle = longBubble.locator("[data-user-message-toggle]");
await toggle.click();
await expect(toggle).toHaveAttribute("aria-expanded", "true");
await expect.poll(async () => {
return longBubble.evaluate((el) => {
const clip = el.querySelector<HTMLElement>("[data-user-message-clip]")!;
return Math.abs(clip.getBoundingClientRect().height - clip.firstElementChild!.getBoundingClientRect().height);
});
}).toBeLessThan(2);
// Scroll the expanded bubble's top above the viewport, then collapse from the bottom toggle.
await page.evaluate(() => {
const scroller = document.querySelector<HTMLElement>("[data-testid='thread-message-region']")!;
const pill = document.querySelector<HTMLElement>("[data-user-prompt-id='long-user'] [data-user-text-bubble] > p")!;
const pillTop = scroller.scrollTop + (pill.getBoundingClientRect().top - scroller.getBoundingClientRect().top);
scroller.scrollTop = pillTop + 260;
});
await toggle.click();
await expect(longBubble).toHaveAttribute("data-user-message-collapsed", "true");
const topVisible = await page.evaluate(() => {
const scroller = document.querySelector<HTMLElement>("[data-testid='thread-message-region']")!;
const pill = document.querySelector<HTMLElement>("[data-user-prompt-id='long-user'] [data-user-text-bubble] > p")!;
return pill.getBoundingClientRect().top >= scroller.getBoundingClientRect().top;
});
expect(topVisible).toBe(true);
});
+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();
}
});
});