Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(web-app): conversation scroll fades, quieter traces and a tidier message footer

James Damf8c4c96d9fef
diff --git a/e2e/specs/message-actions.e2e.ts b/e2e/specs/message-actions.e2e.ts
index b9129b5c4..656e2c630 100644
--- a/e2e/specs/message-actions.e2e.ts
+++ b/e2e/specs/message-actions.e2e.ts
@@ -291,15 +291,15 @@ describe('message actions', () => {
await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(1)
await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(1)
- // The assistant row on purpose. Its actions are always visible when not
- // streaming (MessageItem.tsx:677-682 hides the cluster only while the reply
- // is in flight), so this covers delete without also re-covering the
- // transparency workaround the edit test above already exercises.
+ // The assistant row on purpose, so delete is covered on both sides. Its
+ // secondary actions are hover-revealed (opacity-0) like the user row's, so
+ // this uses the same waitForExist + bare click as the edit test above:
+ // waitForDisplayed rejects a transparent element.
const assistantMessage = await $(ASSISTANT_MESSAGES)
const deleteTrigger = await assistantMessage.$(
'[data-testid="delete-message-trigger"]'
)
- await deleteTrigger.waitForDisplayed({ timeout: 30_000 })
+ await deleteTrigger.waitForExist({ timeout: 30_000 })
await deleteTrigger.click()
await $('[data-testid="delete-message-dialog"]').waitForDisplayed({
@@ -380,10 +380,11 @@ describe('message actions', () => {
await waitForStreamToFinish(30_000)
// Not just "the stream ended" -- that is also what finishing looks like.
- // The Continue button renders only when metadata.stopped is true
- // (MessageItem.tsx:114, :700-714), so its presence is what says the app
- // recorded a stop rather than a completion.
- await $('[data-testid="continue-message"]').waitForDisplayed({
+ // The Continue button renders only when metadata.stopped is true, so its
+ // presence is what says the app recorded a stop rather than a
+ // completion. Exist, not displayed: it sits in the hover-revealed
+ // (opacity-0) footer group.
+ await $('[data-testid="continue-message"]').waitForExist({
timeout: 30_000,
timeoutMsg:
'no Continue button appeared after stopping, so the reply was not ' +
diff --git a/web-app/src/components/ai-elements/chain-of-thought.tsx b/web-app/src/components/ai-elements/chain-of-thought.tsx
index 3005a55a8..6c5a9bf81 100644
--- a/web-app/src/components/ai-elements/chain-of-thought.tsx
+++ b/web-app/src/components/ai-elements/chain-of-thought.tsx
@@ -7,8 +7,6 @@ import {
} from '@/components/ui/collapsible'
import { cn } from '@/lib/utils'
import {
- SparklesIcon,
- ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
CheckCircle2Icon,
@@ -31,6 +29,7 @@ import { Streamdown } from 'streamdown'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { formatCompactDuration } from '@/lib/duration'
import { Shimmer } from './shimmer'
+import { useReleaseScrollLock } from './conversation'
import {
ExternalAnchor,
type ExternalAnchorProps,
@@ -118,7 +117,13 @@ export const ChainOfThought = memo(
else if (shouldCollapse === false) setIsOpen(true)
}, [forceOpen, shouldCollapse, setIsOpen])
+ // A click on the header is the reader choosing what to look at, so the
+ // conversation stops pinning to the bottom; otherwise expanding the last
+ // trace would scroll it straight back out of view. The automatic opens and
+ // collapses above are not routed here and keep following the stream.
+ const releaseScrollLock = useReleaseScrollLock()
const handleOpenChange = (newOpen: boolean) => {
+ releaseScrollLock()
setIsOpen(newOpen)
}
@@ -168,15 +173,9 @@ export const ChainOfThought = memo(
return (
<ChainOfThoughtContext.Provider value={contextValue}>
<Collapsible
- className={cn(
- 'not-prose transition-colors',
- // Expanded: a full-width card frame around the timeline.
- 'data-[state=open]:w-full data-[state=open]:rounded-2xl data-[state=open]:border data-[state=open]:border-border/50 data-[state=open]:bg-main-view-fg/2 data-[state=open]:p-3',
- // Collapsed: a compact pill that hugs its label, so the folded trace
- // reads as a distinct chip between messages, not a full-width row.
- 'data-[state=closed]:w-fit data-[state=closed]:self-start data-[state=closed]:rounded-full data-[state=closed]:border data-[state=closed]:border-border/50 data-[state=closed]:bg-main-view-fg/2 data-[state=closed]:px-2.5 data-[state=closed]:py-1 data-[state=closed]:hover:bg-main-view-fg/5',
- className
- )}
+ // Plain text in both states: no card frame when expanded and no pill
+ // when collapsed, so the trace reads as a quiet line between messages.
+ className={cn('not-prose w-full', className)}
onOpenChange={handleOpenChange}
open={isOpen}
{...props}
@@ -231,6 +230,7 @@ export const ChainOfThoughtHeader = memo(
}: ChainOfThoughtHeaderProps) => {
const { t } = useTranslation()
const { isStreaming, isOpen, duration } = useChainOfThought()
+ const releaseScrollLock = useReleaseScrollLock()
const keys = COMPLETED_KEYS[completedVariant]
const completedLabel =
@@ -238,12 +238,9 @@ export const ChainOfThoughtHeader = memo(
? t(keys.aWhile)
: t(keys.withDuration, { duration: formatCompactDuration(duration, t) })
- // The folded summary is a compact pill, so it reads a notch smaller than
- // the expanded card's header.
- const iconSize = isOpen ? 'size-4' : 'size-3.5'
+ // w-fit so the clickable row hugs its label instead of spanning the column.
const rowClassName = cn(
- 'flex w-full items-center gap-2 text-muted-foreground transition-colors hover:text-foreground',
- isOpen ? 'text-sm' : 'text-xs',
+ 'flex w-fit cursor-pointer items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-foreground',
className
)
@@ -257,7 +254,6 @@ export const ChainOfThoughtHeader = memo(
const label = (
<>
- <SparklesIcon className={cn(iconSize, 'shrink-0')} />
{isStreaming ? (
<Shimmer duration={1}>
{streamingLabel ?? t('chat:reasoning.label')}
@@ -279,7 +275,12 @@ export const ChainOfThoughtHeader = memo(
<button
type="button"
className={rowClassName}
- onClick={onNavigate}
+ onClick={() => {
+ // Switching to the full timeline grows the trace like expanding
+ // it does, so release the bottom lock for the same reason.
+ releaseScrollLock()
+ onNavigate?.()
+ }}
aria-label={navLabel}
title={navLabel}
{...props}
@@ -294,11 +295,12 @@ export const ChainOfThoughtHeader = memo(
return (
<CollapsibleTrigger className={rowClassName} {...props}>
{label}
- <ChevronDownIcon
+ {/* Points at the folded content: right when collapsed, turning down
+ as the trace opens beneath it. */}
+ <ChevronRightIcon
className={cn(
- iconSize,
- 'shrink-0 transition-transform',
- isOpen ? 'rotate-180' : 'rotate-0'
+ 'size-4 shrink-0 transition-transform',
+ isOpen ? 'rotate-90' : 'rotate-0'
)}
/>
</CollapsibleTrigger>
@@ -316,11 +318,9 @@ export const ChainOfThoughtContent = memo(
({ className, children, ...props }: ChainOfThoughtContentProps) => (
<CollapsibleContent
className={cn(
- 'mt-4 text-sm relative',
+ 'mt-3 text-sm relative',
// Expand animates in; collapse unmounts synchronously (no exit
- // animation). A lingering exit keeps the content's height while the
- // root has already snapped to the folded w-fit/rounded-full pill,
- // which renders a tall narrow rounded box as a circle for that frame.
+ // animation), so the folded header never sits on a lingering body.
'data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=open]:animate-in',
className
)}
diff --git a/web-app/src/components/ai-elements/conversation.tsx b/web-app/src/components/ai-elements/conversation.tsx
index ae1e11488..fc9af5f8d 100644
--- a/web-app/src/components/ai-elements/conversation.tsx
+++ b/web-app/src/components/ai-elements/conversation.tsx
@@ -1,22 +1,50 @@
+/* eslint-disable react-refresh/only-export-components */
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { IconArrowDown } from '@tabler/icons-react'
import type { ComponentProps } from 'react'
-import { useCallback, memo } from 'react'
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+ memo,
+} from 'react'
import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom'
export type ConversationProps = ComponentProps<typeof StickToBottom>
-export const Conversation = memo(({ className, ...props }: ConversationProps) => (
- <StickToBottom
- className={cn('relative flex-1 overflow-y-hidden', className)}
- initial="smooth"
- resize="smooth"
- role="log"
- {...props}
- />
-))
+// Lets content release the stick-to-bottom lock. Outside any Conversation
+// there is no lock, so the default is a no-op.
+const ReleaseScrollLockContext = createContext<() => void>(() => {})
+
+/** Call before a user-driven size change (expanding a trace, say): while
+ * locked, the library re-pins to the bottom on every resize, which would carry
+ * the expanded content up and out of view. */
+export const useReleaseScrollLock = () => useContext(ReleaseScrollLockContext)
+
+export const Conversation = memo(
+ ({ className, children, ...props }: ConversationProps) => (
+ <StickToBottom
+ className={cn('relative flex-1 overflow-y-hidden', className)}
+ initial="smooth"
+ resize="smooth"
+ role="log"
+ {...props}
+ >
+ {/* The render callback hands over the library context directly, so
+ stopScroll needs no ref, and function children keep working. */}
+ {(context) => (
+ <ReleaseScrollLockContext.Provider value={context.stopScroll}>
+ {typeof children === 'function' ? children(context) : children}
+ </ReleaseScrollLockContext.Provider>
+ )}
+ </StickToBottom>
+ )
+)
Conversation.displayName = 'Conversation'
@@ -68,34 +96,140 @@ export const ConversationEmptyState = ({
export type ConversationScrollButtonProps = ComponentProps<typeof Button>
+/** Opaque and raised: the outline variant is translucent in dark mode, and the
+ * page surface alone made the button blend in. Shared with the in-trace
+ * scroll button so both read the same. */
+export const scrollToBottomButtonClassName =
+ 'rounded-full bg-background text-foreground shadow-lg hover:bg-accent dark:border-input dark:bg-secondary dark:hover:bg-secondary dark:hover:brightness-125'
+
+/** Within this many px of an edge, nothing is clipped there (sub-pixel scroll
+ * positions never land exactly on 0). */
+const EDGE_EPSILON_PX = 1
+
export const ConversationScrollButton = ({
className,
...props
}: ConversationScrollButtonProps) => {
const { t } = useTranslation()
- const { isAtBottom, scrollToBottom } = useStickToBottomContext()
+ const { isAtBottom, scrollToBottom, scrollRef, contentRef, state } =
+ useStickToBottomContext()
+
+ // The fades follow the real edges, measured here. The library's isAtBottom
+ // also counts the last 70px as "at bottom", which would drop the bottom fade
+ // while a sliver is still clipped; it stays the button's cue only.
+ const [edges, setEdges] = useState({ top: true, bottom: true })
+ const boundRef = useRef<HTMLElement | null>(null)
+ const unbindRef = useRef<(() => void) | null>(null)
+ // No deps: re-checked every render so a remounted scroll element is picked
+ // up (scrollRef itself is stable and never re-triggers an effect).
+ useEffect(() => {
+ const el = scrollRef.current
+ if (el === boundRef.current) return
+ unbindRef.current?.()
+ unbindRef.current = null
+ boundRef.current = el
+ if (!el) return
+ let frame = 0
+ const schedule = () => {
+ cancelAnimationFrame(frame)
+ frame = requestAnimationFrame(update)
+ }
+ const update = () => {
+ const top = el.scrollTop <= EDGE_EPSILON_PX
+ // While pinned, each streamed chunk is followed by a spring back to the
+ // bottom that leaves a gap for a few frames; that is not "clipped", so
+ // an in-flight animation counts as at bottom and the fade stays off.
+ // The library clears the animation without firing any event we hear
+ // (e.g. when an upward scroll interrupts it), so keep re-checking each
+ // frame until it is gone and the real edge can be measured.
+ const animating = Boolean(state.animation)
+ if (animating) schedule()
+ // So does a growth the library is about to follow: it records
+ // resizeDifference in its observer but starts the animation a frame
+ // later. (Not the bare lock state: that is also true when the reader
+ // stops within 70px of the bottom, where content really is clipped.)
+ const following = state.isAtBottom && state.resizeDifference > 0
+ const bottom =
+ animating ||
+ following ||
+ el.scrollHeight - el.scrollTop - el.clientHeight <= EDGE_EPSILON_PX
+ setEdges((prev) =>
+ prev.top === top && prev.bottom === bottom ? prev : { top, bottom }
+ )
+ }
+ update()
+ // Both checks run a frame later. In a frame, scroll events fire before
+ // resize observers, and the library starts its spring in its observer, so
+ // reading straight away sees newly streamed content as a bare gap.
+ el.addEventListener('scroll', schedule, { passive: true })
+ // Streaming text and a resized window change the edges without a scroll.
+ const observer = new ResizeObserver(schedule)
+ observer.observe(el)
+ if (contentRef.current) observer.observe(contentRef.current)
+ unbindRef.current = () => {
+ el.removeEventListener('scroll', schedule)
+ observer.disconnect()
+ cancelAnimationFrame(frame)
+ }
+ })
+ // Forget the bound element too: StrictMode and Fast Refresh unmount and
+ // remount effects in place, and the remount must bind again.
+ useEffect(
+ () => () => {
+ unbindRef.current?.()
+ unbindRef.current = null
+ boundRef.current = null
+ },
+ []
+ )
const handleScrollToBottom = useCallback(() => {
scrollToBottom()
}, [scrollToBottom])
return (
- !isAtBottom && (
- <Button
+ <>
+ {/* Mirrors the bottom fade below: text slides out under the header
+ instead of being cut at its edge. Hidden at the top so the first
+ message is never dimmed. Both fades end in the surface the app layout
+ paints behind the chat (neutral-50 light, background dark), so
+ neither shows as a band, and ease in (40% at the midpoint) so the
+ dimming starts gently instead of as a straight ramp. */}
+ <div
+ aria-hidden="true"
className={cn(
- 'absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full',
- className
+ 'pointer-events-none absolute inset-x-0 top-0 h-16 bg-gradient-to-t from-transparent via-neutral-50/40 via-50% to-neutral-50 dark:via-background/40 dark:to-background transition-opacity duration-200',
+ edges.top ? 'opacity-0' : 'opacity-100'
)}
- onClick={handleScrollToBottom}
- size="icon"
- type="button"
- variant="outline"
- aria-label={t('common:scrollToBottom')}
- title={t('common:scrollToBottom')}
- {...props}
- >
- <IconArrowDown className="size-4" aria-hidden="true" />
- </Button>
- )
+ />
+ {/* Fades text into the page surface above the composer instead of
+ clipping it at a hard edge. Only while scrolled up: at the bottom the
+ last line is the newest content and must stay fully legible. */}
+ <div
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none absolute inset-x-0 bottom-0 h-20 bg-gradient-to-b from-transparent via-neutral-50/40 via-50% to-neutral-50 dark:via-background/40 dark:to-background transition-opacity duration-200',
+ edges.bottom ? 'opacity-0' : 'opacity-100'
+ )}
+ />
+ {!isAtBottom && (
+ <Button
+ className={cn(
+ 'absolute bottom-4 left-[50%] translate-x-[-50%]',
+ scrollToBottomButtonClassName,
+ className
+ )}
+ onClick={handleScrollToBottom}
+ size="icon"
+ type="button"
+ variant="outline"
+ aria-label={t('common:scrollToBottom')}
+ title={t('common:scrollToBottom')}
+ {...props}
+ >
+ <IconArrowDown className="size-4" aria-hidden="true" />
+ </Button>
+ )}
+ </>
)
}
diff --git a/web-app/src/components/ai-elements/reasoning.tsx b/web-app/src/components/ai-elements/reasoning.tsx
index b94e5d07d..a8f94329a 100644
--- a/web-app/src/components/ai-elements/reasoning.tsx
+++ b/web-app/src/components/ai-elements/reasoning.tsx
@@ -6,7 +6,7 @@ import {
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { cn } from '@/lib/utils'
-import { BrainIcon, ChevronDownIcon } from 'lucide-react'
+import { BrainIcon, ChevronRightIcon } from 'lucide-react'
import type { ComponentProps, ReactNode } from 'react'
import {
createContext,
@@ -149,10 +149,12 @@ export const ReasoningTrigger = memo(
<>
<BrainIcon className="size-4" />
{getThinkingMessage(isStreaming, duration)}
- <ChevronDownIcon
+ {/* Right when folded, turning down as it opens: the same cue as
+ every other expandable row. */}
+ <ChevronRightIcon
className={cn(
'size-4 transition-transform',
- isOpen ? 'rotate-180' : 'rotate-0'
+ isOpen ? 'rotate-90' : 'rotate-0'
)}
/>
</>
diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsx
index a52698b9f..1b898fae6 100644
--- a/web-app/src/components/ai-elements/tool.tsx
+++ b/web-app/src/components/ai-elements/tool.tsx
@@ -7,7 +7,7 @@ import {
} from '@/components/ui/collapsible'
import { cn } from '@/lib/utils'
import type { ToolUIPart } from 'ai'
-import { ChevronDownIcon, WrenchIcon, SearchIcon, GlobeIcon } from 'lucide-react'
+import { ChevronRightIcon, WrenchIcon, SearchIcon, GlobeIcon } from 'lucide-react'
import type { ComponentProps, ReactNode } from 'react'
import {
createContext,
@@ -188,8 +188,10 @@ export const ToolHeader = memo(
return (
<CollapsibleTrigger
className={cn(
- 'cursor-pointer flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors',
- !isOpen && 'hover:bg-secondary',
+ // Hover brightens the label like the trace header above it and
+ // fades the chevron in, rather than painting a full-width square
+ // block behind the row.
+ 'group/tool-header cursor-pointer flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground',
className
)}
>
@@ -224,6 +226,18 @@ export const ToolHeader = memo(
{summary}
</span>
)}
+ {/* Right when folded, turning down as it opens, inline after the
+ label: the same cue as the trace header and every other
+ expandable row. Shown while open (it is the collapse cue), on
+ hover, on keyboard focus, and always where nothing can hover. */}
+ <ChevronRightIcon
+ className={cn(
+ '-ml-1 size-4 shrink-0 transition-[opacity,transform]',
+ isOpen
+ ? 'rotate-90 opacity-100'
+ : 'rotate-0 opacity-0 group-hover/tool-header:opacity-100 group-focus-visible/tool-header:opacity-100 [@media(hover:none)]:opacity-100'
+ )}
+ />
<span className="ml-auto flex shrink-0 items-center gap-2">
{queuePosition > 0 && (
<span className="text-xs text-muted-foreground/60">
@@ -235,12 +249,6 @@ export const ToolHeader = memo(
endedAt={endedAt}
className="text-muted-foreground/60"
/>
- <ChevronDownIcon
- className={cn(
- 'size-4 shrink-0 transition-transform',
- isOpen ? 'rotate-180' : 'rotate-0'
- )}
- />
</span>
</CollapsibleTrigger>
)
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 3acc2e31e..a8f9c3df6 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -2054,8 +2054,12 @@ const ChatInput = memo(function ChatInput({
<div
className={cn(
- 'relative z-20 px-0 border rounded-3xl border-input bg-white dark:bg-input/30',
- isFocused && 'ring-1 ring-ring/50',
+ 'relative z-20 px-0 border rounded-3xl border-input bg-white dark:bg-input/30 transition-[border-color,box-shadow] duration-200 ease-out',
+ // Focus brightens the single 1px border instead of adding a
+ // ring outside it, which doubled the edge to a heavy 2px.
+ // Full strength in light, where the resting border is already
+ // pale; softened in dark so it doesn't glare.
+ isFocused && 'border-ring dark:border-ring/60',
isDragOver && 'ring-2 ring-ring/50 border-primary'
)}
data-drop-zone={dropAcceptsAnything ? 'true' : undefined}
diff --git a/web-app/src/containers/CopyButton.tsx b/web-app/src/containers/CopyButton.tsx
index fbe9d4847..f276ab097 100644
--- a/web-app/src/containers/CopyButton.tsx
+++ b/web-app/src/containers/CopyButton.tsx
@@ -1,8 +1,10 @@
import { Button } from '@/components/ui/button'
import { IconCopy, IconCopyCheck } from '@tabler/icons-react'
import { useState } from 'react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
export const CopyButton = ({ text }: { text: string }) => {
+ const { t } = useTranslation()
const [copied, setCopied] = useState(false)
const handleCopy = () => {
@@ -16,13 +18,15 @@ export const CopyButton = ({ text }: { text: string }) => {
variant="ghost"
size="icon-xs"
onClick={handleCopy}
+ aria-label={copied ? t('common:copied') : t('common:copy')}
+ title={copied ? t('common:copied') : t('common:copy')}
>
{copied ? (
<>
- <IconCopyCheck size={16} className="text-primary" />
+ <IconCopyCheck size={16} className="text-primary" aria-hidden="true" />
</>
) : (
- <IconCopy size={16} />
+ <IconCopy size={16} aria-hidden="true" />
)}
</Button>
)
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 063d8dba4..94ec9cc53 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -18,7 +18,8 @@ import {
import { CopyButton } from './CopyButton'
import { RememberButton } from './RememberButton'
import { useTranslation } from '@/i18n/react-i18next-compat'
-import { formatDate } from '@/utils/formatDate'
+import { formatDate, formatMessageTime } from '@/utils/formatDate'
+import { useTouchDevice } from '@/hooks/useMediaQuery'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
import { useMessageErrors } from '@/stores/message-errors'
@@ -74,6 +75,15 @@ export type MessageItemProps = {
highlightedPrefix?: string | null
}
+// Footer icon buttons: 28px boxes (a roomier hover highlight at the same pitch
+// as 24px + gap-1), and keyboard focus shown as that soft highlight plus a 1px
+// neutral-500 ring (the fill alone is ~1.2:1 on the page; neutral-500 clears
+// 3:1 in both themes, the light --ring token does not). The shared Button's 3px focus
+// ring is far heavier than a 16px icon.
+// Dialog triggers swap data-slot to "dialog-trigger", hence both.
+const FOOTER_ICON_BUTTONS =
+ '[&_:is([data-slot=button],[data-slot=dialog-trigger])]:size-7 [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:ring-1 [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:ring-neutral-500 [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:bg-accent [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:text-accent-foreground'
+
export const MessageItem = memo(
({
message,
@@ -96,11 +106,30 @@ export const MessageItem = memo(
highlightedPrefix,
}: MessageItemProps) => {
const { t } = useTranslation()
+ // Footer controls fade in on hover or keyboard focus. Keyboard only
+ // (:focus-visible): a mouse click also focuses the button, and with plain
+ // focus-within the footer stayed shown after the pointer left. A touch
+ // screen has no hover, so there they are always shown rather than
+ // unreachable.
+ const isTouch = useTouchDevice()
+ const hoverReveal = isTouch
+ ? 'opacity-100'
+ : // will-change keeps each group on its own layer at all times. Without
+ // it WebKit promotes the group only while the fade runs, snapping its
+ // fractional position to a whole pixel, so the controls jumped ~1px
+ // as they appeared and again as they settled.
+ 'opacity-0 transition-opacity will-change-[opacity] group-hover/message:opacity-100 group-has-[:focus-visible]/message:opacity-100'
const selectedModel = useModelProvider((state) => state.selectedModel)
const coloredUserBubble = useInterfaceSettings((s) => s.coloredUserBubble)
const metadata = message.metadata as Record<string, unknown> | undefined
const messageError = useMessageErrors((s) => s.errors[message.id])
const createdAt = (metadata?.createdAt as Date) ?? new Date()
+ // Machine-readable stamp for <time>; toISOString throws on an invalid date,
+ // which a malformed stored value must not turn into a crashed message.
+ const createdAtMs = new Date(createdAt).getTime()
+ const createdAtIso = Number.isNaN(createdAtMs)
+ ? undefined
+ : new Date(createdAtMs).toISOString()
const [previewImage, setPreviewImage] = useState<{
url: string
filename?: string
@@ -278,6 +307,24 @@ export const MessageItem = memo(
.join('\n')
}, [message.parts])
+ // Copy stays visible on the last message, the one most often copied, and
+ // on any message with versions, where it anchors the always-visible
+ // version switcher beside it. Elsewhere it joins the hover reveal so the
+ // history stays uncluttered.
+ const hasVersions = Boolean(
+ versionInfo && versionInfo.count > 1 && onSwitchVersion
+ )
+ const copyButton = (
+ <div
+ className={cn(
+ 'flex items-center',
+ !isLastMessage && !hasVersions && hoverReveal
+ )}
+ >
+ <CopyButton text={getFullTextContent()} />
+ </div>
+ )
+
const renderTextPart = (
part: { type: 'text'; text: string },
partIndex: number
@@ -581,9 +628,11 @@ export const MessageItem = memo(
<div
data-testid="message-item"
data-message-role={message.role}
+ // Kept tight: every message now carries a footer row (hidden until
+ // hover), and that row already separates one turn from the next.
className={cn(
- 'w-full mb-4 group/message',
- message.role === 'user' && !isFirstMessage && 'mt-8'
+ 'w-full mb-2 group/message',
+ message.role === 'user' && !isFirstMessage && 'mt-4'
)}
>
{/* Render message parts. A turn alternates collapsed traces with
@@ -648,112 +697,148 @@ export const MessageItem = memo(
</div>
)}
- {/* Message actions for user messages. Same shape as the assistant row
- below -- a timestamp, gap-2, then a gap-1 icon cluster -- so the two
- meta rows line up across roles. */}
+ {/* Message actions for user messages. The bubble is right-aligned, so
+ the row mirrors the assistant one: the date sits on the left and the
+ actions on the right, with copy last so it stays at the bubble's edge.
+ Only copy on the last message is always visible; the rest appear on
+ hover or focus. */}
{message.role === 'user' && !hideActions && (
- <div className="mt-3 flex items-center justify-end gap-2 text-muted-foreground text-xs opacity-0 transition-opacity group-hover/message:opacity-100 focus-within:opacity-100">
- <span className="text-muted-foreground">
- {formatDate(createdAt)}
- </span>
- <div className="flex items-center gap-1">
+ <div className="-mr-1.5 mt-0.5 flex items-center justify-end gap-2.5 text-muted-foreground text-xs">
+ <time
+ className={cn('text-muted-foreground', hoverReveal)}
+ dateTime={createdAtIso}
+ title={formatDate(createdAt)}
+ >
+ {formatMessageTime(createdAt)}
+ </time>
+ <div className={cn('flex items-center', FOOTER_ICON_BUTTONS)}>
+ <div className={cn('flex items-center', hoverReveal)}>
+ {/* Editing re-runs the turn, so with no model it is hidden
+ rather than shown disabled. */}
+ {onEdit &&
+ selectedModel &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED && (
+ <EditMessageDialog
+ message={getFullTextContent()}
+ imageUrls={imageUrls.length > 0 ? imageUrls : undefined}
+ onSave={handleEdit}
+ />
+ )}
+
+ {onRetry &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => onRetry(message.id, getFullTextContent())}
+ title={t('chat:actions.askAgain')}
+ >
+ <IconRefresh size={16} className="text-muted-foreground" />
+ </Button>
+ )}
+
+ {onDelete &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED && (
+ <DeleteMessageDialog onDelete={handleDelete} />
+ )}
+ </div>
+ {/* Shown at rest when there are versions, beside copy. */}
{versionNav}
- <CopyButton text={getFullTextContent()} />
-
- {onEdit &&
- status !== CHAT_STATUS.STREAMING &&
- status !== CHAT_STATUS.SUBMITTED && (
- <EditMessageDialog
- message={getFullTextContent()}
- imageUrls={imageUrls.length > 0 ? imageUrls : undefined}
- onSave={handleEdit}
- />
- )}
-
- {onRetry &&
- status !== CHAT_STATUS.STREAMING &&
- status !== CHAT_STATUS.SUBMITTED && (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() => onRetry(message.id, getFullTextContent())}
- title={t('chat:actions.askAgain')}
- >
- <IconRefresh size={16} className="text-muted-foreground" />
- </Button>
- )}
-
- {onDelete &&
- status !== CHAT_STATUS.STREAMING &&
- status !== CHAT_STATUS.SUBMITTED && (
- <DeleteMessageDialog onDelete={handleDelete} />
- )}
+ {copyButton}
</div>
</div>
)}
- {/* Message actions for assistant messages (non-tool) */}
+ {/* Message actions for assistant messages (non-tool). Mirrors the user
+ row: the actions, then the date and token speed beside them, all
+ hugging the message's leading edge. The icon buttons are 28px and
+ butt together (same 28px pitch as 24px + gap-1, but a roomier hover
+ highlight); -ml-1.5 cancels their padding so the first glyph lines
+ up with the text above, and gap-2.5 between groups evens the
+ visible gaps against the icon spacing. Only copy on the last message is
+ always visible; everything else appears on hover or keyboard focus.
+ The hidden controls keep their space (opacity, not display) so the
+ row never shifts as the pointer moves in and out. */}
{message.role === 'assistant' && !hideActions && (
- <div className="mt-3 flex items-center gap-2 text-muted-foreground text-xs">
- {!isStreaming && (
- <span className="text-muted-foreground">
- {formatDate(createdAt)}
- </span>
- )}
+ <div className="@container -ml-1.5 mt-1.5 flex items-center gap-2.5 text-muted-foreground text-xs">
<div
className={cn(
- 'flex items-center gap-1',
+ 'flex items-center',
+ FOOTER_ICON_BUTTONS,
(isStreaming || hideActions) && 'hidden'
)}
>
+ {copyButton}
+ {/* Shown at rest when there are versions (copy is then shown
+ too, so the pair sits at the leading edge together). */}
{versionNav}
- <CopyButton text={getFullTextContent()} />
- <RememberButton text={getFullTextContent()} />
-
- {onEdit && !isStreaming && (
- <EditMessageDialog
- message={getFullTextContent()}
- onSave={handleEdit}
- />
- )}
-
- {onDelete && !isStreaming && (
- <DeleteMessageDialog onDelete={handleDelete} />
- )}
+ <div className={cn('flex items-center', hoverReveal)}>
+ <RememberButton text={getFullTextContent()} />
- {selectedModel &&
- onContinue &&
- !isStreaming &&
- isLastMessage &&
- canContinue && (
- <Button
- variant="ghost"
- size="icon-xs"
- data-testid="continue-message"
- onClick={handleContinue}
- title={t('chat:actions.continue')}
- >
- <IconPlayerPlay size={16} />
- </Button>
+ {onEdit && selectedModel && !isStreaming && (
+ <EditMessageDialog
+ message={getFullTextContent()}
+ onSave={handleEdit}
+ />
)}
- {selectedModel &&
- onRegenerate &&
- !isStreaming &&
- isLastMessage && (
- <Button
- variant="ghost"
- size="icon-xs"
- data-testid="regenerate-message"
- onClick={handleRegenerate}
- title={t('chat:actions.regenerate')}
- >
- <IconRefresh size={16} />
- </Button>
+ {onDelete && !isStreaming && (
+ <DeleteMessageDialog onDelete={handleDelete} />
)}
+
+ {selectedModel &&
+ onContinue &&
+ !isStreaming &&
+ isLastMessage &&
+ canContinue && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ data-testid="continue-message"
+ onClick={handleContinue}
+ title={t('chat:actions.continue')}
+ >
+ <IconPlayerPlay size={16} />
+ </Button>
+ )}
+
+ {selectedModel &&
+ onRegenerate &&
+ !isStreaming &&
+ isLastMessage && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ data-testid="regenerate-message"
+ onClick={handleRegenerate}
+ title={t('chat:actions.regenerate')}
+ >
+ <IconRefresh size={16} />
+ </Button>
+ )}
+ </div>
</div>
- <TokenSpeedIndicator streaming={isStreaming} metadata={metadata} />
+ <div
+ className={cn(
+ 'flex items-center gap-4',
+ hoverReveal
+ )}
+ >
+ {!isStreaming && (
+ <time
+ className="text-muted-foreground"
+ dateTime={createdAtIso}
+ title={formatDate(createdAt)}
+ >
+ {formatMessageTime(createdAt)}
+ </time>
+ )}
+ <TokenSpeedIndicator streaming={isStreaming} metadata={metadata} />
+ </div>
</div>
)}
diff --git a/web-app/src/containers/TokenSpeedIndicator.tsx b/web-app/src/containers/TokenSpeedIndicator.tsx
index f87e55416..71b79d361 100644
--- a/web-app/src/containers/TokenSpeedIndicator.tsx
+++ b/web-app/src/containers/TokenSpeedIndicator.tsx
@@ -52,11 +52,15 @@ export const TokenSpeedIndicator = memo(
if (showTokenSpeed) {
return (
- <div className="flex items-center gap-2 text-muted-foreground text-xs">
+ // The footer needs ~400px with the inline stats; in a narrower column
+ // (small window, Cowork's docked rail) they are the first thing to go
+ // rather than wrapping it. Queries the footer's @container. The
+ // compact gauge below stays, so the numbers remain reachable.
+ <div className="flex items-center gap-2 text-muted-foreground text-xs @max-md:hidden">
{displaySpeed > 0 && (
<div className="flex items-center gap-1">
<Gauge size={16} />
- <span>{displaySpeed} tokens/sec</span>
+ <span>{displaySpeed} tokens/s</span>
</div>
)}
{displayTokenCount > 0 && (
diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsx
index 514c34338..25b5e2886 100644
--- a/web-app/src/containers/__tests__/MessageItem.test.tsx
+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx
@@ -84,7 +84,13 @@ vi.mock('../CopyButton', () => ({
}))
vi.mock('@/utils/formatDate', () => ({
- formatDate: () => '2024-01-01',
+ formatDate: () => '2024-01-01 full',
+ formatMessageTime: () => '3:30 PM',
+}))
+
+const touchRef = vi.hoisted(() => ({ current: false }))
+vi.mock('@/hooks/useMediaQuery', () => ({
+ useTouchDevice: () => touchRef.current,
}))
vi.mock('@/lib/fileMetadata', () => ({
@@ -137,6 +143,7 @@ describe('MessageItem', () => {
vi.clearAllMocks()
selectedModelRef.current = { id: 'm1' }
pendingApprovalsRef.current = {}
+ touchRef.current = false
})
it('renders assistant text via RenderMarkdown', () => {
@@ -768,6 +775,23 @@ describe('MessageItem', () => {
expect(copy.getAttribute('data-text')).toBe('a\nb')
})
+ it.each(['user', 'assistant'])(
+ 'hides edit on a %s message when no selectedModel',
+ (role) => {
+ selectedModelRef.current = null
+ render(
+ <MessageItem
+ message={makeMsg({ role }) as any}
+ isFirstMessage
+ isLastMessage
+ status={'ready' as any}
+ onEdit={vi.fn()}
+ />
+ )
+ expect(screen.queryByTestId('edit-btn')).not.toBeInTheDocument()
+ }
+ )
+
it('does not render regenerate button when no selectedModel', () => {
selectedModelRef.current = null
const onRegenerate = vi.fn()
@@ -782,4 +806,84 @@ describe('MessageItem', () => {
)
expect(screen.queryByTitle('chat:actions.regenerate')).not.toBeInTheDocument()
})
+
+ describe('footer', () => {
+ const renderAssistant = () =>
+ render(
+ <MessageItem
+ message={makeMsg() as any}
+ isFirstMessage
+ isLastMessage
+ status={'ready' as any}
+ onRegenerate={vi.fn()}
+ />
+ )
+
+ it('shows the compact time with the full date as its tooltip', () => {
+ renderAssistant()
+ const time = screen.getByText('3:30 PM')
+ expect(time).toHaveAttribute('title', '2024-01-01 full')
+ // A real <time> with a machine-readable stamp, not a titled span.
+ expect(time.tagName).toBe('TIME')
+ expect(time.getAttribute('datetime')).toMatch(/^\d{4}-\d{2}-\d{2}T/)
+ })
+
+ it('reveals secondary actions on hover only, with copy always visible', () => {
+ renderAssistant()
+ const regenerate = screen.getByTestId('regenerate-message')
+ // Secondary actions sit in a hover-revealed group; copy does not.
+ expect(regenerate.parentElement?.className).toContain('opacity-0')
+ expect(regenerate.parentElement?.className).toContain(
+ 'group-hover/message:opacity-100'
+ )
+ // Keyboard users reach the same controls: focus inside reveals them.
+ expect(regenerate.parentElement?.className).toContain(
+ 'group-has-[:focus-visible]/message:opacity-100'
+ )
+ const copy = screen.getByTestId('copy-btn')
+ expect(copy.parentElement).not.toBeNull()
+ expect(copy.parentElement!.className).not.toContain('opacity-0')
+ })
+
+ it('hides copy behind hover on an earlier message', () => {
+ render(
+ <MessageItem
+ message={makeMsg() as any}
+ isFirstMessage
+ isLastMessage={false}
+ status={'ready' as any}
+ />
+ )
+ const copy = screen.getByTestId('copy-btn')
+ expect(copy.parentElement?.className).toContain('opacity-0')
+ expect(copy.parentElement?.className).toContain(
+ 'group-hover/message:opacity-100'
+ )
+ })
+
+ it('keeps copy and the version switcher visible together when there are versions', () => {
+ render(
+ <MessageItem
+ message={makeMsg() as any}
+ isFirstMessage
+ isLastMessage={false}
+ status={'ready' as any}
+ versionInfo={{ index: 1, count: 2 }}
+ onSwitchVersion={vi.fn()}
+ />
+ )
+ const copy = screen.getByTestId('copy-btn')
+ expect(copy.parentElement!.className).not.toContain('opacity-0')
+ const prev = screen.getByTestId('message-version-prev')
+ expect(prev.closest('[class*="opacity-0"]')).toBeNull()
+ })
+
+ it('shows every action on a touch device', () => {
+ touchRef.current = true
+ renderAssistant()
+ const regenerate = screen.getByTestId('regenerate-message')
+ expect(regenerate.parentElement?.className).toContain('opacity-100')
+ expect(regenerate.parentElement?.className).not.toContain('opacity-0')
+ })
+ })
})
diff --git a/web-app/src/containers/dialogs/DeleteMessageDialog.tsx b/web-app/src/containers/dialogs/DeleteMessageDialog.tsx
index 7c9201e06..1aa6e5a1d 100644
--- a/web-app/src/containers/dialogs/DeleteMessageDialog.tsx
+++ b/web-app/src/containers/dialogs/DeleteMessageDialog.tsx
@@ -40,6 +40,8 @@ export function DeleteMessageDialog({ onDelete }: DeleteMessageDialogProps) {
role="button"
tabIndex={0}
data-testid="delete-message-trigger"
+ aria-label={t('common:deleteMessage')}
+ title={t('common:deleteMessage')}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
@@ -47,7 +49,7 @@ export function DeleteMessageDialog({ onDelete }: DeleteMessageDialogProps) {
}
}}
>
- <IconTrash size={16} />
+ <IconTrash size={16} aria-hidden="true" />
</Button>
)
diff --git a/web-app/src/containers/dialogs/EditMessageDialog.tsx b/web-app/src/containers/dialogs/EditMessageDialog.tsx
index 7c4e5e191..405e53d75 100644
--- a/web-app/src/containers/dialogs/EditMessageDialog.tsx
+++ b/web-app/src/containers/dialogs/EditMessageDialog.tsx
@@ -86,6 +86,8 @@ export function EditMessageDialog({
role="button"
tabIndex={0}
data-testid="edit-message-trigger"
+ aria-label={t('common:dialogs.editMessage.title')}
+ title={t('common:dialogs.editMessage.title')}
disabled={!selectedModel}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -94,7 +96,7 @@ export function EditMessageDialog({
}
}}
>
- <IconPencil size={16} />
+ <IconPencil size={16} aria-hidden="true" />
</Button>
)
diff --git a/web-app/src/containers/message/ChainOfThoughtGroup.tsx b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
index 93bfc43bc..c09d3caea 100644
--- a/web-app/src/containers/message/ChainOfThoughtGroup.tsx
+++ b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
@@ -11,6 +11,7 @@ import {
StepRow,
} from '@/components/ai-elements/reasoning-timeline'
import { Button } from '@/components/ui/button'
+import { scrollToBottomButtonClassName } from '@/components/ai-elements/conversation'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
import {
isToolCallRunning,
@@ -236,13 +237,18 @@ export const ChainOfThoughtGroup = memo(
</div>
{!isReasoningAtBottom && (
<Button
- className="absolute bottom-2 left-[50%] translate-x-[-50%] rounded-full size-7 z-10"
+ className={twMerge(
+ 'absolute bottom-2 left-[50%] translate-x-[-50%] size-7 z-10',
+ scrollToBottomButtonClassName
+ )}
onClick={onReasoningScrollToBottom}
size="icon"
type="button"
variant="outline"
+ aria-label={t('common:scrollToBottom')}
+ title={t('common:scrollToBottom')}
>
- <IconArrowDown className="size-3" />
+ <IconArrowDown className="size-3" aria-hidden="true" />
</Button>
)}
</div>
diff --git a/web-app/src/hooks/__tests__/useMediaQuery.coverage.test.ts b/web-app/src/hooks/__tests__/useMediaQuery.coverage.test.ts
index 0ee82fa5d..f3fc7374b 100644
--- a/web-app/src/hooks/__tests__/useMediaQuery.coverage.test.ts
+++ b/web-app/src/hooks/__tests__/useMediaQuery.coverage.test.ts
@@ -54,10 +54,10 @@ describe('useMediaQuery screen size hooks', () => {
expect(mockMatchMedia).toHaveBeenCalledWith('(orientation: landscape)')
})
- it('useTouchDevice should query pointer: coarse', () => {
+ it('useTouchDevice should query hover: none', () => {
mockMatchMedia.mockReturnValue(setup())
const { result } = renderHook(() => useTouchDevice())
expect(result.current).toBe(true)
- expect(mockMatchMedia).toHaveBeenCalledWith('(pointer: coarse)')
+ expect(mockMatchMedia).toHaveBeenCalledWith('(hover: none)')
})
})
diff --git a/web-app/src/hooks/useMediaQuery.ts b/web-app/src/hooks/useMediaQuery.ts
index dd41e1417..9e828c5df 100644
--- a/web-app/src/hooks/useMediaQuery.ts
+++ b/web-app/src/hooks/useMediaQuery.ts
@@ -103,7 +103,11 @@ export const useLandscape = (): boolean => {
return useMediaQuery('(orientation: landscape)')
}
-// Touch device detection
+// Devices whose primary input cannot hover (touch screens), so hover-revealed
+// controls must be shown outright. Read synchronously so the first paint is
+// already right instead of fading controls in on mount.
export const useTouchDevice = (): boolean => {
- return useMediaQuery('(pointer: coarse)')
+ return useMediaQuery('(hover: none)', undefined, {
+ getInitialValueInEffect: false,
+ })
}
diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.json
index 23e48fe74..64cff68ac 100644
--- a/web-app/src/locales/en/settings.json
+++ b/web-app/src/locales/en/settings.json
@@ -92,7 +92,7 @@
"notificationPositionBottomRight": "Bottom right",
"notificationPositionBottomLeft": "Bottom left",
"showTokenSpeed": "Show token speed",
- "showTokenSpeedDesc": "Display tokens/sec and token count inline below assistant messages. When off, a compact icon shows the details on click.",
+ "showTokenSpeedDesc": "Display tokens/s and token count in the assistant message footer (shown on hover). When off, a compact icon shows the details on click.",
"coloredUserBubble": "Colored user message bubble",
"coloredUserBubbleDesc": "Use the accent color as the background of your messages. When off, they match assistant messages with plain text on a neutral background.",
"renderHtmlArtifacts": "Render HTML & SVG artifacts",
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index ecf2ab6ad..6730879f0 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -1637,7 +1637,8 @@ function CoworkPage() {
)}
</div>
- <div className="py-4 shrink-0">
+ {/* pb-only: the scroll area runs right up to the composer. */}
+ <div className="pb-4 shrink-0">
<div className={cn('mx-auto w-full px-6', !dockedRail && 'md:w-4/5 xl:w-4/6')}>
{/* The card rises in when a question arrives and folds away once
answered, so the chat box glides instead of jumping. A card
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index a6cbf45b1..bf18a4d40 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -2305,7 +2305,7 @@ function ThreadDetail() {
>
<Conversation className="absolute inset-0 text-start">
<ConversationContent
- className={cn('mx-auto w-full px-6 md:w-4/5 xl:w-4/6')}
+ className={cn('mx-auto w-full px-6 pb-4 md:w-4/5 xl:w-4/6')}
>
{chatMessages.map((message, index) => {
const isLastMessage = index === chatMessages.length - 1
@@ -2454,8 +2454,10 @@ function ThreadDetail() {
</Conversation>
</div>
- {/* Chat Input - Fixed at bottom */}
- <div className="py-4 px-6 mx-auto w-full md:w-4/5 xl:w-4/6">
+ {/* Chat Input - Fixed at bottom. No top padding: the scroll area (and
+ its fade) runs right up to the composer, with the resting gap kept
+ inside the scroll content as pb-4. */}
+ <div className="pb-4 px-6 mx-auto w-full md:w-4/5 xl:w-4/6">
<ChatInput
model={threadModel}
onSubmit={handleSubmit}
diff --git a/web-app/src/utils/__tests__/formatDate.test.ts b/web-app/src/utils/__tests__/formatDate.test.ts
index 9d559f66f..d9a0145d5 100644
--- a/web-app/src/utils/__tests__/formatDate.test.ts
+++ b/web-app/src/utils/__tests__/formatDate.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { formatDate } from '../formatDate'
+import { formatDate, formatMessageTime } from '../formatDate'
describe('formatDate', () => {
it('formats Date objects correctly', () => {
@@ -101,3 +101,27 @@ describe('formatDate', () => {
expect(formatted).not.toMatch(/(AM|PM)/i)
})
})
+
+describe('formatMessageTime', () => {
+ const now = new Date(2026, 9, 30, 12, 0, 0)
+
+ it('shows only the time on the same day', () => {
+ const out = formatMessageTime(new Date(2026, 9, 30, 15, 30), now)
+ expect(out).toBe('3:30 PM')
+ })
+
+ it('drops the year within the same year', () => {
+ const out = formatMessageTime(new Date(2026, 9, 29, 17, 32), now)
+ expect(out).toBe('Oct 29, 5:32 PM')
+ })
+
+ it('keeps the year and drops the time for an earlier year', () => {
+ const out = formatMessageTime(new Date(2025, 11, 25, 9, 5), now)
+ expect(out).toBe('Dec 25, 2025')
+ })
+
+ it('treats the day boundary by local calendar date, not 24 hours', () => {
+ const out = formatMessageTime(new Date(2026, 9, 29, 23, 59), now)
+ expect(out).toBe('Oct 29, 11:59 PM')
+ })
+})
diff --git a/web-app/src/utils/formatDate.ts b/web-app/src/utils/formatDate.ts
index 9422f03e2..8cebb84d6 100644
--- a/web-app/src/utils/formatDate.ts
+++ b/web-app/src/utils/formatDate.ts
@@ -31,3 +31,34 @@ export const formatDate = (
month: 'long',
})
}
+
+/**
+ * Compact timestamp for a message footer.
+ *
+ * - Same calendar day: just the time ("3:30 PM").
+ * - Same year: month and day, no year ("Oct 29, 5:32 PM").
+ * - Any other year: the date with its year, no time ("Oct 29, 2025"); the
+ * full timestamp is still in the footer's hover title.
+ *
+ * `now` is a parameter so the day and year boundaries are testable.
+ */
+export const formatMessageTime = (
+ date: string | number | Date,
+ now: Date = new Date()
+): string => {
+ const d = new Date(date)
+ const time: Intl.DateTimeFormatOptions = {
+ hour: 'numeric',
+ minute: 'numeric',
+ hour12: true,
+ }
+ if (d.toDateString() === now.toDateString()) {
+ return d.toLocaleTimeString('en-US', time)
+ }
+ const sameYear = d.getFullYear() === now.getFullYear()
+ return d.toLocaleString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ ...(sameYear ? time : { year: 'numeric' }),
+ })
+}