feat(webui): refine mobile message actions and hover timestamps

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent 4693bba81f
commit 7aac9355ec
10 files changed
+334 -73

No files matched your search

+8
View File
@@ -463,6 +463,14 @@ link menu. For in-app actions on touch devices, open the message's existing
**Message actions → View links** entry. It lists only the web links rendered in
that message, not URLs inside code blocks or file references. Choose a link to
copy it, open it externally, or preview it beside the current conversation.
On phone-sized screens, Copy and Message actions sit below the message, leaving
the full text width available. Message actions opens a bottom sheet; close it
with its close button, by tapping outside, or with Escape. Desktop keeps the
hover-triggered message popover.
On desktop, hovering or focusing a message also reveals a short timestamp below
its actions: a 24-hour clock for today, or month/day for every other date. Hover
or focus that label for the full local date and time, including the year. Replies
use their completion timestamp when available, otherwise their creation timestamp.
There is no persistent action button beside each link and no custom long-press
gesture to interfere with scrolling or text selection.
Ordinary clicks still open links in a browser tab. File and session links keep
+40 -48
View File
@@ -120,6 +120,34 @@ function useMessageCopy(content: string) {
return { copied, label, onCopy };
}
function messageCopyContent(message: UIMessage, t: (key: string) => string) {
return message.role === "assistant" && message.compactReply === "empty"
? t("thread.compaction.empty")
: message.role === "assistant" && message.compactReply === "failed"
? t("thread.compaction.failed")
: message.content;
}
/** The same copy behavior in the desktop menu and the mobile reply footer. */
export function MessageCopyButton({ message, className }: { message: UIMessage; className?: string }) {
const { t } = useTranslation();
const content = messageCopyContent(message, t);
const { copied, label, onCopy } = useMessageCopy(content);
if (!content.trim()) return null;
return <TooltipProvider><Tooltip><TooltipTrigger asChild><button type="button" data-message-block-copy-action
data-assistant-copy-action={message.role === "assistant" || undefined}
onClick={onCopy} aria-label={label}
className={cn(
"inline-flex h-[var(--message-block-control-size)] w-[var(--message-block-action-width)] items-center justify-center rounded-control",
"text-muted-foreground transition-[color,background-color,scale] hover:bg-muted/70 hover:text-foreground active:scale-[0.96]",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transform-none",
className,
)}>
{copied ? <Check className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
: <Copy className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />}
</button></TooltipTrigger><TooltipContent side="top" align="center">{label}</TooltipContent></Tooltip></TooltipProvider>;
}
interface MessageBlockMenuActivity {
label: string;
expanded: boolean;
@@ -133,6 +161,7 @@ interface MessageBlockMenuActionsProps {
onForkFromHere?: () => void;
activity?: MessageBlockMenuActivity;
onViewLinks?: () => void;
sheet?: boolean;
}
/** Actions and metadata shown after opening a visual message block's context panel. */
@@ -142,17 +171,11 @@ export function MessageBlockMenuActions({
onForkFromHere,
activity,
onViewLinks,
sheet = false,
}: MessageBlockMenuActionsProps) {
const { t } = useTranslation();
const content = message.role === "assistant"
? message.compactReply === "empty"
? t("thread.compaction.empty")
: message.compactReply === "failed"
? t("thread.compaction.failed")
: message.content
: message.content;
const content = messageCopyContent(message, t);
const hasText = content.trim().length > 0;
const { copied, label: copyLabel, onCopy } = useMessageCopy(content);
const showFork = message.role === "assistant"
&& !message.isStreaming
&& !isTurnStreaming
@@ -175,50 +198,16 @@ export function MessageBlockMenuActions({
<TooltipProvider>
<div
data-message-block-menu-actions
className="flex w-max max-w-full flex-col items-start gap-1"
className={cn("flex max-w-full flex-col items-start gap-1", sheet ? "w-full" : "w-max")}
>
{hasText || showFork || activity ? (
{(!sheet && hasText) || showFork || activity ? (
<div
data-message-block-toolbar
className="flex w-full flex-wrap items-center gap-x-1 gap-y-1"
className={cn("flex w-full flex-wrap gap-x-1 gap-y-1", sheet ? "flex-col items-stretch" : "items-center")}
>
{hasText || showFork ? (
{(!sheet && hasText) || showFork ? (
<div className="flex min-h-[var(--message-block-control-size)] items-center gap-0.5">
{hasText ? (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
data-message-block-copy-action
data-assistant-copy-action={message.role === "assistant" || undefined}
onClick={onCopy}
aria-label={copyLabel}
className={cn(
"inline-flex h-[var(--message-block-control-size)] w-[var(--message-block-action-width)] items-center justify-center rounded-control",
"text-muted-foreground transition-[color,background-color,scale]",
"hover:bg-muted/70 hover:text-foreground active:scale-[0.96]",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
"motion-reduce:transform-none",
)}
>
{copied ? (
<Check
className="h-3.5 w-3.5 -translate-x-px"
strokeWidth={1.75}
aria-hidden
/>
) : (
<Copy
className="h-3.5 w-3.5 -translate-x-px"
strokeWidth={1.75}
aria-hidden
/>
)}
</button>
</TooltipTrigger>
<TooltipContent side="top" align="center">{copyLabel}</TooltipContent>
</Tooltip>
) : null}
{!sheet && hasText ? <MessageCopyButton message={message} /> : null}
{showFork ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -234,9 +223,11 @@ export function MessageBlockMenuActions({
"hover:bg-muted/70 hover:text-foreground active:scale-[0.96]",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
"motion-reduce:transform-none",
sheet && "w-full justify-start gap-2 px-2 text-sm",
)}
>
<ForkArrowIcon className="h-3.5 w-3.5" />
{sheet ? <span>{t("message.forkFromHere")}</span> : null}
</button>
</TooltipTrigger>
<TooltipContent side="top" align="center">
@@ -258,6 +249,7 @@ export function MessageBlockMenuActions({
"text-start text-[11px] leading-4",
"text-muted-foreground transition-colors hover:text-foreground",
"focus-visible:outline-none",
sheet && "w-full rounded-control text-sm hover:bg-muted/70",
)}
>
<span
@@ -289,7 +281,7 @@ export function MessageBlockMenuActions({
{timestampLabel || automationSourceLabel ? (
<div
data-message-block-metadata
className="mt-0.5 w-full border-t border-border/45 px-1.5 pt-1 text-[10px] leading-4 text-muted-foreground/45"
className={cn("mt-0.5 w-full border-t border-border/45 px-1.5 pt-1 leading-4", sheet ? "text-xs text-muted-foreground" : "text-[10px] text-muted-foreground/45")}
>
{timestampLabel ? (
<time
+4 -3
View File
@@ -37,11 +37,12 @@ export function useMessageWebLinks(root: RefObject<HTMLElement>, open: boolean)
const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} w-full min-h-11 text-start hover:bg-muted/70`;
/** A drill-in inside the existing message popover, not another floating layer. */
export function MessageLinksMenu({ links, onBack, onClose }: {
/** A drill-in inside the message's action surface, not another floating layer. */
export function MessageLinksMenu({ links, onBack, onClose, expanded = false }: {
links: MessageWebLink[];
onBack: () => void;
onClose: () => void;
expanded?: boolean;
}) {
const { t } = useTranslation();
const openPreview = useContext(WebPreviewContext);
@@ -49,7 +50,7 @@ export function MessageLinksMenu({ links, onBack, onClose }: {
const active = links.find((link) => link.href === selected);
const backRef = useRef<HTMLButtonElement>(null);
useLayoutEffect(() => { backRef.current?.focus({ preventScroll: true }); }, [selected]);
return <div className="w-60 max-w-full">
return <div className={expanded ? "w-full" : "w-60 max-w-full"}>
<button ref={backRef} type="button" className={itemClassName} aria-label={t("webPreview.back")}
onClick={() => active && links.length > 1 ? setSelected(null) : onBack()}>
<ArrowLeft aria-hidden /><span>{t("webPreview.viewLinks")}</span>
+69 -12
View File
@@ -1,7 +1,7 @@
import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
import { MoreHorizontal } from "lucide-react";
import { useTranslation } from "react-i18next";
import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
import { MessageBlockMenuActions, MessageBubble, MessageCopyButton } from "@/components/MessageBubble";
import { MessageLinksMenu, useMessageWebLinks } from "@/components/MessageLinksMenu";
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
import {
@@ -11,6 +11,10 @@ import {
} from "@/components/thread/AgentActivityCluster";
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format";
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
@@ -91,6 +95,7 @@ export function ThreadMessages({
}: ThreadMessagesProps) {
const { t } = useTranslation();
const messageListRef = useRef<HTMLDivElement>(null);
const mobileActions = useMediaQuery("(max-width: 767px)");
const units = useMemo(
() => buildDisplayUnits(messages),
[messages],
@@ -222,6 +227,7 @@ export function ThreadMessages({
key={unitKeys[index]}
unitKey={unitKeys[index]}
unit={unit}
mobileActions={mobileActions}
marginTop={marginTop}
userPromptId={userPromptId}
hasBodyBelow={hasBodyBelow}
@@ -323,6 +329,7 @@ function pendingTurnProjection(
}
interface ThreadDisplayUnitProps {
mobileActions: boolean;
unitKey: string;
unit: DisplayUnit;
marginTop: string;
@@ -356,6 +363,7 @@ interface ThreadDisplayUnitProps {
}
interface MessageBlockMenuProps {
mobileActions: boolean;
messageRoot: RefObject<HTMLElement>;
message: UIMessage;
isTurnStreaming: boolean;
@@ -374,6 +382,7 @@ interface MessageBlockMenuProps {
}
function MessageBlockMenu({
mobileActions,
messageRoot,
message,
isTurnStreaming,
@@ -405,6 +414,43 @@ function MessageBlockMenu({
const contextActiveRef = useRef(contextActive);
contextActiveRef.current = contextActive;
const label = t("message.actions");
const timestamp = message.role === "assistant" && Number.isFinite(message.completedAt)
? message.completedAt
: message.createdAt;
// Re-evaluated when this message becomes active, including after an overnight idle.
const shortTime = mobileActions ? "" : formatMessageHoverTime(timestamp);
const fullTime = shortTime ? fmtDateTime(timestamp) : "";
const actions = linksShown && links.length > 0 ? <MessageLinksMenu links={links}
expanded={mobileActions}
onBack={() => { setLinksShown(false); contentRef.current?.focus({ preventScroll: true }); }}
onClose={() => onOpenChange(false)} /> : <MessageBlockMenuActions
message={message}
isTurnStreaming={isTurnStreaming}
onForkFromHere={onForkFromHere ? () => { if (mobileActions) onOpenChange(false); onForkFromHere(); } : undefined}
activity={activity}
sheet={mobileActions}
onViewLinks={links.length > 0 ? () => setLinksShown(true) : undefined}
/>;
if (mobileActions) {
return <div data-message-mobile-actions className={cn("mt-1 flex items-center gap-0.5", message.role === "user" && "justify-end")}>
<MessageCopyButton message={message} className="h-11 w-11" />
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<button ref={triggerRef} type="button" data-message-block-menu-trigger aria-label={label}
className="inline-flex h-11 w-11 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<MoreHorizontal className="h-4 w-4" strokeWidth={1.75} aria-hidden />
</button>
</DialogTrigger>
<DialogContent ref={contentRef} placement="bottom" aria-describedby={undefined}
data-message-block-menu data-message-mobile-sheet data-message-context-menu-block={contextBlockKey}
className="gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))] outline-none"
onCloseAutoFocus={(event) => { if (activity?.expanded) event.preventDefault(); }}>
<DialogTitle className="px-2 pb-2 pe-10 text-sm font-medium text-muted-foreground">{label}</DialogTitle>
{actions}
</DialogContent>
</Dialog>
</div>;
}
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger asChild>
@@ -434,6 +480,21 @@ function MessageBlockMenu({
</span>
</button>
</PopoverTrigger>
{shortTime && fullTime && typeof timestamp === "number" ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<time data-message-hover-time dateTime={new Date(timestamp).toISOString()}
tabIndex={0} aria-label={fullTime}
className="message-block-hover-time absolute start-[calc(-1*var(--message-block-trigger-offset)-2px)] top-[var(--message-block-control-size)] z-10 w-[calc(var(--message-block-control-size)+4px)] truncate rounded-mark text-center text-[10px] leading-4 tabular-nums text-muted-foreground outline-none transition-opacity focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none">
{shortTime}
</time>
</TooltipTrigger>
<TooltipContent side="right" align="start" collisionPadding={12}
data-message-context-menu-block={contextBlockKey}>{fullTime}</TooltipContent>
</Tooltip>
</TooltipProvider>
) : null}
<PopoverContent
ref={contentRef}
data-message-block-menu
@@ -472,21 +533,14 @@ function MessageBlockMenu({
"shadow-[0_2px_10px_rgba(0,0,0,0.08)] dark:shadow-[0_2px_10px_rgba(0,0,0,0.24)]",
)}
>
{linksShown && links.length > 0 ? <MessageLinksMenu links={links}
onBack={() => { setLinksShown(false); contentRef.current?.focus({ preventScroll: true }); }}
onClose={() => onOpenChange(false)} /> : <MessageBlockMenuActions
message={message}
isTurnStreaming={isTurnStreaming}
onForkFromHere={onForkFromHere}
activity={activity}
onViewLinks={links.length > 0 ? () => setLinksShown(true) : undefined}
/>}
{actions}
</PopoverContent>
</Popover>
);
}
const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
mobileActions,
unitKey,
unit,
marginTop,
@@ -579,6 +633,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
]);
const blockMenu = unit.type === "message" && contextBlockKey !== undefined ? (
<MessageBlockMenu
mobileActions={mobileActions}
messageRoot={elementRef}
message={unit.message}
isTurnStreaming={isTurnStreaming}
@@ -649,7 +704,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
)
) : (
<div className={unit.message.role === "assistant" ? "relative" : undefined}>
{unit.message.role === "assistant" ? blockMenu : null}
{unit.message.role === "assistant" && !mobileActions ? blockMenu : null}
{showBlockContext && blockActivity ? (
<div className={blockActivityExpanded ? "mb-2" : undefined}>
<AgentActivityCluster
@@ -678,8 +733,9 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
mcpPresets={mcpPresets}
slashCommands={slashCommands}
onOpenFilePreview={onOpenFilePreview}
contextMenu={unit.message.role === "user" ? blockMenu : undefined}
contextMenu={unit.message.role === "user" && !mobileActions ? blockMenu : undefined}
/>
{mobileActions ? blockMenu : null}
{unit.message.role === "assistant"
&& unit.message.kind !== "compaction"
&& contextBlockKey === undefined ? (
@@ -702,6 +758,7 @@ function threadDisplayUnitPropsEqual(
): boolean {
return (
displayUnitsEqual(previous.unit, next.unit)
&& previous.mobileActions === next.mobileActions
&& previous.marginTop === next.marginTop
&& previous.userPromptId === next.userPromptId
&& previous.hasBodyBelow === next.hasBodyBelow
+13 -7
View File
@@ -38,9 +38,10 @@ const DialogPositionedContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
positionerStyle?: React.CSSProperties;
placement?: "center" | "bottom";
}
>(({ positionerStyle, ...props }, ref) => (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={positionerStyle}>
>(({ positionerStyle, placement, ...props }, ref) => (
<div className={cn("fixed inset-0 z-50 flex justify-center", placement === "bottom" ? "items-end" : "items-center p-4")} style={positionerStyle}>
<DialogPrimitive.Content ref={ref} {...props} />
</div>
));
@@ -50,19 +51,20 @@ interface DialogContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
showCloseButton?: boolean;
overlayClassName?: string;
placement?: "center" | "bottom";
}
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, showCloseButton = true, overlayClassName, onOpenAutoFocus, ...props }, ref) => {
>(({ className, children, showCloseButton = true, overlayClassName, placement = "center", onOpenAutoFocus, ...props }, ref) => {
const { t } = useTranslation();
const [container, setContainer] = React.useState<HTMLDivElement | null>(null);
const contentNode = React.useRef<HTMLDivElement | null>(null);
const layoutAnchor = React.useContext(DialogLayoutContext);
const [layout, setLayout] = React.useState<React.CSSProperties>();
React.useLayoutEffect(() => {
if (!layoutAnchor) {
if (!layoutAnchor || placement === "bottom") {
setLayout(undefined);
return;
}
@@ -81,7 +83,7 @@ const DialogContent = React.forwardRef<
observer?.disconnect();
window.removeEventListener("resize", update);
};
}, [layoutAnchor]);
}, [layoutAnchor, placement]);
const contentRef = React.useCallback((node: HTMLDivElement | null) => {
contentNode.current = node;
setContainer(node);
@@ -93,6 +95,7 @@ const DialogContent = React.forwardRef<
<DialogOverlay className={overlayClassName} />
<DialogPositionedContent
positionerStyle={layout}
placement={placement}
ref={contentRef}
onOpenAutoFocus={(event) => {
if (onOpenAutoFocus) onOpenAutoFocus(event);
@@ -103,7 +106,10 @@ const DialogContent = React.forwardRef<
}}
className={cn(
modalSurfaceClassName,
"relative grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 motion-reduce:animate-none",
"relative grid w-full max-w-lg gap-4 p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 motion-reduce:animate-none",
placement === "bottom"
? "max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-4 data-[state=closed]:slide-out-to-bottom-4"
: "origin-center rounded-modal data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className,
)}
{...props}
@@ -112,7 +118,7 @@ const DialogContent = React.forwardRef<
{children}
</FloatingPortalContext.Provider>
{showCloseButton ? (
<DialogPrimitive.Close className="absolute right-2.5 top-2.5 grid h-7 w-7 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground active:bg-muted/80 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none">
<DialogPrimitive.Close className={cn("absolute right-2.5 top-2.5 grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground active:bg-muted/80 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "h-11 w-11" : "h-7 w-7")}>
<X className="h-4 w-4" />
<span className="sr-only">{t("common.close")}</span>
</DialogPrimitive.Close>
+23 -2
View File
@@ -805,7 +805,8 @@
padding-inline-end: max(0.75rem, calc((100% - var(--content-column-width)) / 2));
}
.message-block-menu-trigger {
.message-block-menu-trigger,
.message-block-hover-time {
pointer-events: none;
opacity: 0;
}
@@ -815,9 +816,16 @@
top: calc((1rem + 28px - var(--message-block-control-size)) / 2);
}
[data-user-text-bubble] > .message-block-hover-time {
top: calc((1rem + 28px + var(--message-block-control-size)) / 2);
}
[data-context-block-active] .message-block-menu-trigger,
[data-message-context-menu-open] .message-block-menu-trigger,
.message-block-menu-trigger:focus-visible {
.message-block-menu-trigger:focus-visible,
[data-context-block-active] .message-block-hover-time,
[data-message-context-menu-open] .message-block-hover-time,
.message-block-hover-time:focus-visible {
pointer-events: auto;
opacity: 1;
}
@@ -859,6 +867,19 @@
}
}
/* On phones, actions follow the message instead of taking a separate gutter. */
@media (max-width: 767px) {
.thread-message-row {
padding-inline: 1rem;
}
[data-message-mobile-actions],
[data-message-mobile-sheet] {
--message-block-control-size: 2.75rem;
--message-block-action-width: 2.75rem;
}
}
/*
* Composer controls adapt to their actual container, not just the viewport.
* Narrow layouts move access and usage into a separate metadata row.
+22
View File
@@ -83,6 +83,7 @@ const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();
const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const clockTimeFormatters = new Map<string, Intl.DateTimeFormat>();
const hoverTimeFormatters = new Map<string, Intl.DateTimeFormat>();
function activeLocale(locale?: string): string {
return locale || i18n.resolvedLanguage || i18n.language || currentLocale();
@@ -167,6 +168,27 @@ export function formatMessageEndTime(
: dateTimeFormatter(loc).format(date);
}
/** One-line gutter label; the full local date/time belongs in its tooltip. */
export function formatMessageHoverTime(
value: number | null | undefined,
locale?: string,
now = new Date(),
): string {
const date = parseDate(value);
if (!date) return "";
const loc = activeLocale(locale);
const today = isSameLocalCalendarDay(date, now);
const key = `${loc}:${today ? "clock" : "date"}`;
let formatter = hoverTimeFormatters.get(key);
if (!formatter) {
formatter = new Intl.DateTimeFormat(loc, today
? { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }
: { month: "numeric", day: "numeric" });
hoverTimeFormatters.set(key, formatter);
}
return formatter.format(date);
}
/** Human-readable turn duration (wall-clock), locale-aware via ``Intl`` (seconds/minutes). */
export function formatTurnLatency(ms: number, locale?: string): string {
const loc = activeLocale(locale);
+28
View File
@@ -4,6 +4,7 @@ import { setAppLanguage } from "@/i18n";
import {
fmtDateTime,
formatMessageEndTime,
formatMessageHoverTime,
formatTurnLatency,
relativeTime,
} from "@/lib/format";
@@ -112,4 +113,31 @@ describe("localized format helpers", () => {
expect(minutePlus).toContain("m");
expect(minutePlus).toContain("s");
});
it("uses a short 24-hour clock today and localized month/day for every other date", () => {
const now = new Date(2026, 8, 24, 16, 0);
expect(formatMessageHoverTime(new Date(2026, 8, 24, 14, 32).getTime(), "zh-CN", now)).toBe("14:32");
expect(formatMessageHoverTime(new Date(2026, 8, 24, 0, 5).getTime(), "en", now)).toBe("00:05");
expect(formatMessageHoverTime(new Date(2026, 8, 23, 14, 32).getTime(), "zh-CN", now)).toBe("9/23");
expect(formatMessageHoverTime(new Date(2026, 8, 23).getTime(), "fr", now)).toBe(
new Intl.DateTimeFormat("fr", { month: "numeric", day: "numeric" }).format(new Date(2026, 8, 23)),
);
expect(formatMessageHoverTime(new Date(2025, 8, 22).getTime(), "zh-CN", now)).toBe("9/22");
expect(formatMessageHoverTime(new Date(2026, 8, 25).getTime(), "zh-CN", now)).toBe("9/25");
});
it.each([
[new Date(2026, 0, 1, 0, 30), new Date(2025, 11, 31, 23, 55)],
[new Date(2026, 2, 1, 0, 30), new Date(2026, 1, 28, 23, 55)],
[new Date(2026, 2, 9, 0, 30), new Date(2026, 2, 8, 0, 15)],
[new Date(2026, 10, 2, 0, 30), new Date(2026, 10, 1, 23, 55)],
])("compares local calendar days across month/year and DST boundaries (%s)", (now, previousDay) => {
expect(formatMessageHoverTime(previousDay.getTime(), "en", now)).toBe(
new Intl.DateTimeFormat("en", { month: "numeric", day: "numeric" }).format(previousDay),
);
});
it.each([null, undefined, NaN, Infinity, 9e15])("omits invalid hover time %s", (value) => {
expect(formatMessageHoverTime(value)).toBe("");
});
});
@@ -0,0 +1,56 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { fmtDateTime } from "@/lib/format";
vi.mock("@/components/MarkdownText", () => ({ MarkdownText: ({ content }: { content: string }) => <p>{content}</p> }));
afterEach(() => { cleanup(); vi.useRealTimers(); });
describe("desktop hover timestamp", () => {
it("uses user creation / assistant completion time and exposes the full date on keyboard focus", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date(2026, 8, 24, 16));
const createdAt = new Date(2026, 8, 23, 12).getTime();
const completedAt = new Date(2026, 8, 24, 14, 32).getTime();
const { container } = render(<ThreadMessages messages={[
{ id: "u", role: "user", content: "Question", createdAt },
{ id: "a", role: "assistant", content: "Answer", createdAt, completedAt },
]} />);
const times = container.querySelectorAll<HTMLTimeElement>("[data-message-hover-time]");
expect(times).toHaveLength(2);
expect(times[0]).toHaveTextContent("9/23");
expect(times[1]).toHaveTextContent("14:32");
expect(times[1]).toHaveAttribute("datetime", new Date(completedAt).toISOString());
expect(times[1]).toHaveAttribute("aria-label", fmtDateTime(completedAt));
fireEvent.focus(times[1]);
expect(await screen.findByRole("tooltip")).toHaveTextContent(fmtDateTime(completedAt));
expect(times[1].closest("[data-thread-display-unit]")).toHaveAttribute("data-context-block-active");
});
it("refreshes the short date when hovering again after midnight", () => {
vi.useFakeTimers({ toFake: ["Date"] });
const createdAt = new Date(2026, 11, 31, 23, 30).getTime();
vi.setSystemTime(new Date(2026, 11, 31, 23, 50));
const { container } = render(<ThreadMessages messages={[{ id: "a", role: "assistant", content: "Answer", createdAt }]} />);
const time = container.querySelector("[data-message-hover-time]")!;
const row = time.closest("[data-thread-display-unit]")!;
fireEvent.pointerEnter(row, { pointerType: "mouse" });
expect(time).toHaveTextContent("23:30");
fireEvent.pointerLeave(row, { pointerType: "mouse", relatedTarget: document.body });
vi.setSystemTime(new Date(2027, 0, 1, 0, 10));
fireEvent.pointerEnter(row, { pointerType: "mouse" });
expect(time).toHaveTextContent("12/31");
});
it("falls back to creation time and omits invalid timestamps", () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date(2026, 8, 24, 16));
const { container } = render(<ThreadMessages messages={[
{ id: "a", role: "assistant", content: "Answer", createdAt: new Date(2026, 8, 22).getTime(), completedAt: NaN },
{ id: "b", role: "assistant", content: "Unknown", createdAt: NaN },
]} />);
const times = container.querySelectorAll("[data-message-hover-time]");
expect(times).toHaveLength(1);
expect(times[0]).toHaveTextContent("9/22");
});
});
+71 -1
View File
@@ -7,7 +7,7 @@ import { useMessageWebLinks } from "@/components/MessageLinksMenu";
import { copyTextToClipboard } from "@/lib/clipboard";
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn(async () => true) }));
afterEach(() => { cleanup(); vi.mocked(copyTextToClipboard).mockReset().mockResolvedValue(true); });
afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.mocked(copyTextToClipboard).mockReset().mockResolvedValue(true); });
function view(content: string, openPreview?: (url: string) => void) {
return <WebPreviewContext.Provider value={openPreview}>
@@ -22,6 +22,76 @@ async function openLinks() {
}
describe("message link actions", () => {
function mobileViewport() {
const listeners = new Set<() => void>();
let narrow = true;
vi.stubGlobal("matchMedia", vi.fn((query: string) => ({
get matches() { return query === "(max-width: 767px)" && narrow; },
media: query,
addEventListener: (_event: string, listener: () => void) => listeners.add(listener),
removeEventListener: (_event: string, listener: () => void) => listeners.delete(listener),
})));
return (value: boolean) => act(() => { narrow = value; listeners.forEach(listener => listener()); });
}
it("puts mobile actions after the reply and opens one bottom sheet with working back, copy and preview", async () => {
mobileViewport();
const preview = vi.fn();
const content = "[Website](https://example.com/demo)";
const { container } = render(view(content, preview));
const link = await screen.findByRole("link", { name: /Website/ });
const footer = container.querySelector("[data-message-mobile-actions]")!;
expect(link.compareDocumentPosition(footer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(container.querySelector(".message-block-menu-trigger")).not.toBeInTheDocument();
expect(container.querySelector("[data-message-hover-time]")).not.toBeInTheDocument();
fireEvent.click(within(footer as HTMLElement).getByRole("button", { name: "Copy" }));
await waitFor(() => expect(copyTextToClipboard).toHaveBeenCalledWith(content));
const menu = await openLinks();
expect(menu).toHaveAttribute("data-message-mobile-sheet");
expect(screen.getAllByRole("dialog")).toHaveLength(1);
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
expect(within(menu).queryByRole("button", { name: "Copy" })).not.toBeInTheDocument();
fireEvent.click(within(menu).getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Message actions" })).toHaveFocus();
await openLinks();
fireEvent.click(screen.getByRole("button", { name: "Preview website" }));
expect(preview).toHaveBeenCalledWith("https://example.com/demo");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("restores the desktop menu on resize without duplicating actions", async () => {
const resize = mobileViewport();
const { container } = render(view("[Website](https://example.com/demo)"));
await screen.findByRole("link", { name: /Website/ });
await openLinks();
resize(false);
await waitFor(() => expect(container.querySelector("[data-message-mobile-actions]")).not.toBeInTheDocument());
expect(screen.queryByRole("dialog")).not.toHaveAttribute("data-message-mobile-sheet");
expect(screen.getAllByRole("button", { name: "Message actions" })).toHaveLength(1);
// Resizing may close the modal as focus is returned; either way its trigger stays usable.
if (!screen.queryByRole("dialog")) fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
expect(screen.getAllByRole("dialog")).toHaveLength(1);
});
it("keeps user actions outside the bubble and exposes a labelled mobile fork action", async () => {
mobileViewport();
const fork = vi.fn();
const { container } = render(<ThreadMessages onForkFromMessage={fork} messages={[
{ id: "user", role: "user", content: "A prompt", createdAt: 1 },
{ id: "reply", role: "assistant", content: "A reply", createdAt: 2 },
]} />);
await screen.findByText("A reply");
expect(container.querySelector("[data-user-text-bubble] [data-message-block-menu-trigger]")).toBeNull();
expect(container.querySelectorAll("[data-message-mobile-actions]")).toHaveLength(2);
fireEvent.click(screen.getAllByRole("button", { name: "Message actions" })[1]);
const menu = screen.getByRole("dialog");
expect(within(menu).getByRole("button", { name: "Fork" })).toHaveTextContent("Fork");
fireEvent.click(within(menu).getByRole("button", { name: "Fork" }));
expect(fork).toHaveBeenCalledWith(1);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("collects rendered links, deduplicates destinations and ignores code, images and file references", async () => {
render(view("[First](https://example.com/) and [Again](https://example.com).\n\n[Second](https://example.org/demo)\n\nhttps://example.net/plain\n\n`https://code.invalid/inline`\n\n```text\nhttps://code.invalid/block\n```\n\n![Image](https://image.invalid/pic.png)\n\n[notes.txt](notes.txt)"));
await screen.findByRole("link", { name: "First" });