From 09384cab26a91049caaf29856e6d89d8e116b1e5 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:36:30 +0800 Subject: [PATCH] feat(webui): collapse long user messages exceeding half viewport height (#6739) --- webui/browser/fixture.tsx | 6 +- webui/browser/long-user-message-fixture.tsx | 187 +++++++++++++++ webui/browser/long-user-message.spec.ts | 148 ++++++++++++ webui/src/components/MessageBubble.tsx | 250 ++++++++++++++++++-- webui/src/globals.css | 125 +++++++++- webui/src/i18n/locales/en/common.json | 2 + webui/src/i18n/locales/es/common.json | 2 + webui/src/i18n/locales/fr/common.json | 2 + webui/src/i18n/locales/id/common.json | 2 + webui/src/i18n/locales/ja/common.json | 2 + webui/src/i18n/locales/ko/common.json | 2 + webui/src/i18n/locales/pt-BR/common.json | 2 + webui/src/i18n/locales/vi/common.json | 2 + webui/src/i18n/locales/zh-CN/common.json | 2 + webui/src/i18n/locales/zh-TW/common.json | 2 + webui/src/tests/message-bubble.test.tsx | 61 +++++ 16 files changed, 776 insertions(+), 21 deletions(-) create mode 100644 webui/browser/long-user-message-fixture.tsx create mode 100644 webui/browser/long-user-message.spec.ts diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index 5ce24b393..f8ba411f3 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -73,6 +73,10 @@ async function loadFixture() { const { MobileChatLayoutFixture } = await import("./mobile-chat-layout-fixture"); return withClient(); } + case "long-user-message": { + const { LongUserMessageFixture } = await import("./long-user-message-fixture"); + return withClient(); + } 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({fixture}); diff --git a/webui/browser/long-user-message-fixture.tsx b/webui/browser/long-user-message-fixture.tsx new file mode 100644 index 000000000..a6c16179c --- /dev/null +++ b/webui/browser/long-user-message-fixture.tsx @@ -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(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 ( +
+ {}} + onToggleTheme={() => setDark((value) => !value)} + sessionInfoAction={} + promptNavigatorAction={} + /> + + {(renderContextUsage) => ( + {}} + 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" })} + /> + )} + /> + )} + +
+ ); +} diff --git a/webui/browser/long-user-message.spec.ts b/webui/browser/long-user-message.spec.ts new file mode 100644 index 000000000..ae7c6ac53 --- /dev/null +++ b/webui/browser/long-user-message.spec.ts @@ -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("[data-testid='thread-message-region']")!; + const longRow = document.querySelectorAll("[data-user-text-bubble]")[1]!; + const pill = longRow.querySelector(":scope > p")!; + const clip = pill.querySelector("[data-user-message-clip]")!; + const stackEl = longRow.querySelector("[data-user-message-stack]")!; + const toggleEl = longRow.querySelector("[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("[data-user-message-clip]")!; + const stackEl = el.querySelector("[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(":scope > p")!; + const clip = pill.querySelector("[data-user-message-clip]")!; + const toggleEl = el.querySelector("[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("[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("[data-testid='thread-message-region']")!; + const pill = document.querySelector("[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("[data-testid='thread-message-region']")!; + const pill = document.querySelector("[data-user-prompt-id='long-user'] [data-user-text-bubble] > p")!; + return pill.getBoundingClientRect().top >= scroller.getBoundingClientRect().top; + }); + expect(topVisible).toBe(true); +}); diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index 065439de8..f050cd5b3 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -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 ? ( -
- {contextMenu} -

- - {messageText} -

-
+ + {messageText} + ) : null} {!showDeliveryStatus && showProcessingStatus ? ( @@ -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(null); + const contentRef = useRef(null); + const contentId = useId(); + const [layout, setLayout] = useState(null); + const [expandedForId, setExpandedForId] = useState(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 ( +
+ {contextMenu} +

+ + {isCollapsible ? ( + + + {children} + + + ) : ( + children + )} +

+ {isCollapsible ? ( + <> + +
+ +
+ + ) : null} +
+ ); +} + function UserQuotedContext({ text, label }: { text: string; label: string }) { return (
.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); } diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 5b60ca68e..ed2fe3d98 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -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", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 847ecee04..bf982573b 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -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", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 84f5208d7..53031c1b7 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -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", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 269c6db75..01a2b779d 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -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", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index acf74b047..f228ae2c5 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -2188,6 +2188,8 @@ "fallbackResponse": "この返信では代替モデルに切り替わり、{{preset}} が回答しています。", "copyReply": "コピー", "copiedReply": "コピー済み", + "expandUserMessage": "さらに表示", + "collapseUserMessage": "折りたたむ", "turnLatencyTitle": "応答時間(全行程)", "fileEditViewDiff": "変更を表示", "fileEditViewLargeDiff": "変更を展開", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 01a707111..57d220717 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -2188,6 +2188,8 @@ "fallbackResponse": "이 응답은 대체 모델로 전환되어 {{preset}}이(가) 답변합니다.", "copyReply": "복사", "copiedReply": "복사됨", + "expandUserMessage": "더 보기", + "collapseUserMessage": "접기", "turnLatencyTitle": "응답 시간(엔드투엔드)", "fileEditViewDiff": "변경 보기", "fileEditViewLargeDiff": "변경 펼치기", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 4c5c2a80c..5a92041e0 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -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", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index de96c7b0f..3349092e0 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -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", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index d8134609a..f09b18823 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -2576,6 +2576,8 @@ "fallbackResponse": "本条回复已切换至备用模型,由 {{preset}} 回答。", "copyReply": "复制", "copiedReply": "已复制", + "expandUserMessage": "展开", + "collapseUserMessage": "收起", "turnLatencyTitle": "回复耗时", "fileEditViewDiff": "查看修改", "fileEditViewLargeDiff": "展开修改", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index f8ff1ead6..03a1aeb85 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -2187,6 +2187,8 @@ "fallbackResponse": "本則回覆已切換至備用模型,由 {{preset}} 回答。", "copyReply": "複製", "copiedReply": "已複製", + "expandUserMessage": "展開", + "collapseUserMessage": "收起", "turnLatencyTitle": "回覆耗時", "fileEditViewDiff": "檢視修改", "fileEditViewLargeDiff": "展開修改", diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx index 23bc06208..c89f14c04 100644 --- a/webui/src/tests/message-bubble.test.tsx +++ b/webui/src/tests/message-bubble.test.tsx @@ -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(); + + 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(); + } + }); + });