Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: fix prompt timestamp layout, accessibility, and imported times (#12173)

Michael Han501b15fb6f50
diff --git a/studio/frontend/src/components/assistant-ui/message-menu-time.tsx b/studio/frontend/src/components/assistant-ui/message-menu-time.tsx
index 3fe3f8ed953..3a35b711165 100644
--- a/studio/frontend/src/components/assistant-ui/message-menu-time.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-menu-time.tsx
@@ -11,6 +11,7 @@ import {
} from "@/components/ui/tooltip";
import { useLocale, useT } from "@/i18n";
import { formatMessageDate } from "@/lib/format-message-date";
+import { messageTimestamp } from "@/lib/message-timestamp";
import type { FC } from "react";
/** When the message was written, heading the More menu, with the details button beside it.
@@ -20,7 +21,7 @@ export const MessageMenuTime: FC<{ onShowDetails: () => void }> = ({
}) => {
const t = useT();
const locale = useLocale();
- const createdAt = useAuiState(({ message }) => message.createdAt?.getTime());
+ const createdAt = useAuiState(({ message }) => messageTimestamp(message));
const date =
createdAt !== undefined && Number.isFinite(createdAt)
? new Date(createdAt)
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 076b02f383c..5f1d6bfa0ff 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -27,7 +27,8 @@ import { PromptQueueList } from "@/components/assistant-ui/lazy-prompt-queue-lis
import { QueueResumeIcon } from "@/components/assistant-ui/queue-resume-icon";
import { ProgressiveMessages } from "@/components/assistant-ui/progressive-messages";
import { MessageMenuTime } from "@/components/assistant-ui/message-menu-time";
-import { UserMessageTime } from "@/components/assistant-ui/user-message-time";
+import { UserMessageActionBar, UserMessageFooter } from "@/components/assistant-ui/user-message-actions";
+import { useActionBarFocusReveal } from "@/components/assistant-ui/use-action-bar-focus-reveal";
import { MessageTiming } from "@/components/assistant-ui/message-timing";
import { attachThreadFastCopy } from "@/components/assistant-ui/thread-fast-copy";
import { threadHasResearchMessage } from "@/components/assistant-ui/thread-research-presence";
@@ -370,7 +371,6 @@ import {
type FC,
type KeyboardEvent,
type DragEvent as ReactDragEvent,
- type FocusEvent as ReactFocusEvent,
type ReactNode,
type RefObject,
Fragment,
@@ -7716,152 +7716,6 @@ const DiffusionCanvas: FC = () => {
);
};
-/**
- * Mounts an autohidden action bar while focus is inside the message, the way hovering it does.
- *
- * `autohide="not-last"` UNMOUNTS every bar but the newest reply's, so Copy, Edit, Refresh,
- * Delete, Read aloud and More leave the tab order on older messages and a keyboard or screen
- * reader user has no way back: `:focus-within` in CSS cannot help, there is nothing to style.
- * The reveal has to be JS, and it drives `message.setIsHovering`, the same flag the library's
- * own `mouseenter`/`mouseleave` (MessagePrimitive.Root) writes and the only input to
- * `useActionBarFloatStatus` besides the More menu's interaction lock. Reusing it rather than
- * layering a second visibility source is what keeps the two from disagreeing.
- *
- * One flag, two writers, so the two clobber each other unless this hook covers both crossings:
- * - pointer leaves while focus is inside (a Tab that scrolls the message under a parked
- * cursor does exactly this): the library clears the flag, which would unmount the element
- * that currently has focus. `reassert` below sets it back inside the same event.
- * - focus leaves while the pointer is still over the message: clearing would unmount a bar
- * the user is pointing at, and no second `mouseenter` is coming. The `:hover` test defers
- * to the library's own `mouseleave` instead.
- */
-function useActionBarFocusReveal() {
- const aui = useAui();
- const rootRef = useRef<HTMLDivElement | null>(null);
- const focusWithinRef = useRef(false);
- const clearFrameRef = useRef<number | null>(null);
-
- // The More menu is portaled OUTSIDE the message, so focus entering it looks like a blur.
- // Its own interaction lock keeps the bar mounted meanwhile, but the trigger this hook has to
- // hand focus back to lives in that bar, so a popup this message owns counts as engaged.
- // Scoped to the action bar, NOT to every expanded descendant. Reasoning and tool cards are
- // Radix CollapsibleTriggers and render aria-expanded="true" while open, which is the resting
- // state of a message whose tool output the reader has expanded. An unscoped lookup treated
- // those as an open popup, so `decide` rescheduled itself every frame for as long as the
- // disclosure stayed open, held focusWithinRef and the synthetic hover set, and left the bar
- // mounted: a per-frame DOM query per such message, which is the slowdown this branch removes.
- const openPopupTrigger = useCallback(
- () =>
- rootRef.current?.querySelector(
- '.aui-assistant-action-bar-root [aria-expanded="true"]',
- ) ?? null,
- [],
- );
-
- const isEngaged = useCallback(() => {
- const el = rootRef.current;
- if (!el) return false;
- const active = document.activeElement;
- if (active && el.contains(active)) return true;
- return openPopupTrigger() !== null;
- }, [openPopupTrigger]);
-
- const cancelPendingClear = useCallback(() => {
- if (clearFrameRef.current !== null) {
- cancelAnimationFrame(clearFrameRef.current);
- clearFrameRef.current = null;
- }
- }, []);
-
- /**
- * Decide, a frame from now, whether focus has really left, and keep asking until it has.
- *
- * Deferred rather than read off `relatedTarget`: that is null both for focus going to the
- * browser chrome and for focus entering a portal, and it says nothing at all when the
- * focused element is REMOVED, which is how a menu closes and which Chrome reports with no
- * focusout event whatsoever. Reading `document.activeElement` a frame later answers all of
- * them. Clearing late costs a frame of a mounted bar; clearing early destroys the element
- * the user is on, so late is the safe direction.
- */
- const scheduleClear = useCallback(
- (restart: boolean) => {
- if (clearFrameRef.current !== null) {
- if (!restart) return;
- cancelAnimationFrame(clearFrameRef.current);
- }
- const decide = () => {
- clearFrameRef.current = null;
- const el = rootRef.current;
- if (!el || !focusWithinRef.current) return;
- const active = document.activeElement;
- if (active && el.contains(active)) return;
- if (openPopupTrigger()) {
- // Focus is in this message's own portaled menu, whose interaction lock is holding
- // the bar open anyway. Deciding now would be wrong and deciding never would pin the
- // bar open for good, so ask again next frame; the loop lasts only as long as the
- // menu is open on this one message.
- clearFrameRef.current = requestAnimationFrame(decide);
- return;
- }
- focusWithinRef.current = false;
- if (!el.matches(":hover")) {
- aui.message().setIsHovering(false);
- }
- };
- clearFrameRef.current = requestAnimationFrame(decide);
- },
- [aui, openPopupTrigger],
- );
-
- // onFocus/onBlur on a container are focusin/focusout in React, so they give focus-within.
- const handleFocus = useCallback(
- (event: ReactFocusEvent<HTMLDivElement>) => {
- const el = rootRef.current;
- const target = event.target as Node | null;
- if (el && target && !el.contains(target)) {
- // React bubbles focus events out of PORTALS along the React tree, so this is this
- // message's own menu, rendered into document.body. Focus is not in the subtree, so do
- // not cancel the watchdog -- the menu will take focus with it when it unmounts, and
- // that removal fires no focusout to wake us up again.
- scheduleClear(false);
- return;
- }
- cancelPendingClear();
- if (focusWithinRef.current) return;
- focusWithinRef.current = true;
- aui.message().setIsHovering(true);
- },
- [aui, cancelPendingClear, scheduleClear],
- );
-
- const handleBlur = useCallback(() => {
- if (!focusWithinRef.current) return;
- scheduleClear(true);
- }, [scheduleClear]);
-
- useEffect(() => {
- const el = rootRef.current;
- if (!el) return;
- // From an effect on purpose: MessagePrimitive.Root binds its own mouseleave from a ref
- // callback, which commits before effects run, so this listener is registered second and
- // runs second on the same element. Both writes land in one dispatch, the store settles on
- // `true`, and React never renders the intermediate `false` -- so the bar does not unmount
- // and the focused control is not destroyed under the user.
- const reassert = () => {
- if (focusWithinRef.current && isEngaged()) {
- aui.message().setIsHovering(true);
- }
- };
- el.addEventListener("mouseleave", reassert);
- return () => {
- el.removeEventListener("mouseleave", reassert);
- cancelPendingClear();
- };
- }, [aui, isEngaged, cancelPendingClear]);
-
- return { ref: rootRef, onFocus: handleFocus, onBlur: handleBlur };
-}
-
const ResearchMessageRunIdContext = createContext<string | null>(null);
/**
@@ -8698,28 +8552,39 @@ const UserMessageAudio: FC = () => {
};
const UserMessage: FC = () => {
+ const focusReveal = useActionBarFocusReveal();
return (
<MessagePrimitive.Root
className="aui-user-message-root fade-in slide-in-from-bottom-1 mx-auto flex w-full max-w-(--thread-content-max-width) animate-in flex-col items-end gap-y-2 pt-6 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em] duration-150"
data-role="user"
+ tabIndex={0}
+ {...focusReveal}
>
<UserMessageAttachments />
<UserMessageAudio />
- <div className="aui-user-message-content-wrapper flex max-w-[80%] min-w-0 flex-col items-end">
- <div className="aui-user-message-content wrap-break-word w-fit max-w-full rounded-[24px] bg-[#f5f5f5] px-4 py-2.5 text-[#0d0d0d] dark:text-foreground dark:bg-card">
+ <div className="aui-user-message-content-wrapper flex w-full min-w-0 flex-col items-end">
+ <div className="aui-user-message-content wrap-break-word w-fit max-w-[80%] rounded-[24px] bg-[#f5f5f5] px-4 py-2.5 text-[#0d0d0d] dark:text-foreground dark:bg-card">
<MessagePrimitive.Parts />
</div>
- <div className="mt-1 -mr-[var(--icon-btn-inset)] flex min-h-8 items-center">
+ <UserMessageFooter>
<UserActionBar />
- <BranchPicker className="aui-user-branch-picker ml-0.5" />
- </div>
+ <BranchPicker className="aui-user-branch-picker ml-0.5 shrink-0" />
+ </UserMessageFooter>
</div>
{/* The other half of the pair: last is a user message while a reply is
still to come, or once one has been deleted. */}
<MessagePrimitive.If last={true}>
<ForkChatShortcut />
</MessagePrimitive.If>
+ {/* Reverse traversal reaches a trailing stop before the root. Focusing it
+ mounts the autohidden controls, so the next Shift+Tab enters Delete
+ instead of skipping the action bar and leaving the message. */}
+ <span
+ className="aui-user-reveal-sentinel"
+ tabIndex={0}
+ aria-label="Message actions"
+ />
</MessagePrimitive.Root>
);
};
@@ -8728,11 +8593,7 @@ const UserActionBar: FC = () => {
const ownsResearchMessage = useOwnsResearchMessage();
const researchActive = useThreadResearchActive();
return (
- <ActionBarPrimitive.Root
- autohide="always"
- className="aui-user-action-bar-root flex gap-1 text-chat-icon-fg [&_button]:size-8 [&_button]:!rounded-full [&_button:hover]:bg-chat-icon-bg-hover [&_button:hover]:text-chat-icon-fg-hover"
- >
- <UserMessageTime />
+ <UserMessageActionBar>
<CopyButton />
{!ownsResearchMessage && !researchActive && (
<ActionBarPrimitive.Edit asChild={true}>
@@ -8748,7 +8609,7 @@ const UserActionBar: FC = () => {
<ForkCountBadge />
<ForkMessageButton />
<DeleteMessageButton />
- </ActionBarPrimitive.Root>
+ </UserMessageActionBar>
);
};
diff --git a/studio/frontend/src/components/assistant-ui/use-action-bar-focus-reveal.ts b/studio/frontend/src/components/assistant-ui/use-action-bar-focus-reveal.ts
new file mode 100644
index 00000000000..a2c22944e4b
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/use-action-bar-focus-reveal.ts
@@ -0,0 +1,179 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useAui } from "@assistant-ui/react";
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ type FocusEvent as ReactFocusEvent,
+ type MouseEvent as ReactMouseEvent,
+} from "react";
+import { isTouchClick } from "@/components/ui/touch-click";
+
+/**
+ * Mounts an autohidden action bar while focus is inside the message, the way hovering it does.
+ *
+ * `autohide="not-last"` UNMOUNTS every bar but the newest reply's, so Copy, Edit, Refresh,
+ * Delete, Read aloud and More leave the tab order on older messages and a keyboard or screen
+ * reader user has no way back: `:focus-within` in CSS cannot help, there is nothing to style.
+ * The reveal has to be JS, and it drives `message.setIsHovering`, the same flag the library's
+ * own `mouseenter`/`mouseleave` (MessagePrimitive.Root) writes and the only input to
+ * `useActionBarFloatStatus` besides the More menu's interaction lock. Reusing it rather than
+ * layering a second visibility source is what keeps the two from disagreeing.
+ *
+ * One flag, two writers, so the two clobber each other unless this hook covers both crossings:
+ * - pointer leaves while focus is inside (a Tab that scrolls the message under a parked
+ * cursor does exactly this): the library clears the flag, which would unmount the element
+ * that currently has focus. `reassert` below sets it back inside the same event.
+ * - focus leaves while the pointer is still over the message: clearing would unmount a bar
+ * the user is pointing at, and no second `mouseenter` is coming. The `:hover` test defers
+ * to the library's own `mouseleave` instead.
+ */
+export function useActionBarFocusReveal() {
+ const aui = useAui();
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const focusWithinRef = useRef(false);
+ const clearFrameRef = useRef<number | null>(null);
+
+ // The More menu is portaled OUTSIDE the message, so focus entering it looks like a blur.
+ // Its own interaction lock keeps the bar mounted meanwhile, but the trigger this hook has to
+ // hand focus back to lives in that bar, so a popup this message owns counts as engaged.
+ // Scoped to the action bar, NOT to every expanded descendant. Reasoning and tool cards are
+ // Radix CollapsibleTriggers and render aria-expanded="true" while open, which is the resting
+ // state of a message whose tool output the reader has expanded. An unscoped lookup treated
+ // those as an open popup, so `decide` rescheduled itself every frame for as long as the
+ // disclosure stayed open, held focusWithinRef and the synthetic hover set, and left the bar
+ // mounted: a per-frame DOM query per such message, which is the slowdown this branch removes.
+ const openPopupTrigger = useCallback(
+ () =>
+ rootRef.current?.querySelector(
+ ':is(.aui-assistant-action-bar-root, .aui-user-action-bar-root) [aria-expanded="true"]',
+ ) ?? null,
+ [],
+ );
+
+ const isEngaged = useCallback(() => {
+ const el = rootRef.current;
+ if (!el) return false;
+ const active = document.activeElement;
+ if (active && el.contains(active)) return true;
+ return openPopupTrigger() !== null;
+ }, [openPopupTrigger]);
+
+ const cancelPendingClear = useCallback(() => {
+ if (clearFrameRef.current !== null) {
+ cancelAnimationFrame(clearFrameRef.current);
+ clearFrameRef.current = null;
+ }
+ }, []);
+
+ /**
+ * Decide, a frame from now, whether focus has really left, and keep asking until it has.
+ *
+ * Deferred rather than read off `relatedTarget`: that is null both for focus going to the
+ * browser chrome and for focus entering a portal, and it says nothing at all when the
+ * focused element is REMOVED, which is how a menu closes and which Chrome reports with no
+ * focusout event whatsoever. Reading `document.activeElement` a frame later answers all of
+ * them. Clearing late costs a frame of a mounted bar; clearing early destroys the element
+ * the user is on, so late is the safe direction.
+ */
+ const scheduleClear = useCallback(
+ (restart: boolean) => {
+ if (clearFrameRef.current !== null) {
+ if (!restart) return;
+ cancelAnimationFrame(clearFrameRef.current);
+ }
+ const decide = () => {
+ clearFrameRef.current = null;
+ const el = rootRef.current;
+ if (!el || !focusWithinRef.current) return;
+ const active = document.activeElement;
+ if (active && el.contains(active)) return;
+ if (openPopupTrigger()) {
+ // Focus is in this message's own portaled menu, whose interaction lock is holding
+ // the bar open anyway. Deciding now would be wrong and deciding never would pin the
+ // bar open for good, so ask again next frame; the loop lasts only as long as the
+ // menu is open on this one message.
+ clearFrameRef.current = requestAnimationFrame(decide);
+ return;
+ }
+ focusWithinRef.current = false;
+ if (!el.matches(":hover")) {
+ aui.message().setIsHovering(false);
+ }
+ };
+ clearFrameRef.current = requestAnimationFrame(decide);
+ },
+ [aui, openPopupTrigger],
+ );
+
+ // onFocus/onBlur on a container are focusin/focusout in React, so they give focus-within.
+ const handleFocus = useCallback(
+ (event: ReactFocusEvent<HTMLDivElement>) => {
+ const el = rootRef.current;
+ const target = event.target as Node | null;
+ if (el && target && !el.contains(target)) {
+ // React bubbles focus events out of PORTALS along the React tree, so this is this
+ // message's own menu, rendered into document.body. Focus is not in the subtree, so do
+ // not cancel the watchdog -- the menu will take focus with it when it unmounts, and
+ // that removal fires no focusout to wake us up again.
+ scheduleClear(false);
+ return;
+ }
+ cancelPendingClear();
+ if (focusWithinRef.current) return;
+ focusWithinRef.current = true;
+ aui.message().setIsHovering(true);
+ },
+ [aui, cancelPendingClear, scheduleClear],
+ );
+
+ const handleBlur = useCallback(() => {
+ if (!focusWithinRef.current) return;
+ scheduleClear(true);
+ }, [scheduleClear]);
+
+ useEffect(() => {
+ const el = rootRef.current;
+ if (!el) return;
+ // From an effect on purpose: MessagePrimitive.Root binds its own mouseleave from a ref
+ // callback, which commits before effects run, so this listener is registered second and
+ // runs second on the same element. Both writes land in one dispatch, the store settles on
+ // `true`, and React never renders the intermediate `false` -- so the bar does not unmount
+ // and the focused control is not destroyed under the user.
+ const reassert = () => {
+ if (focusWithinRef.current && isEngaged()) {
+ aui.message().setIsHovering(true);
+ }
+ };
+ el.addEventListener("mouseleave", reassert);
+ return () => {
+ el.removeEventListener("mouseleave", reassert);
+ cancelPendingClear();
+ };
+ }, [aui, isEngaged, cancelPendingClear]);
+
+ return {
+ ref: rootRef,
+ onFocus: handleFocus,
+ onBlur: handleBlur,
+ onClick: focusMessageOnTouch,
+ };
+}
+
+function focusMessageOnTouch(event: ReactMouseEvent<HTMLDivElement>) {
+ // Touch has no hover. Focus the existing message tab stop after a tap on
+ // its prose, without stealing a link/button action or a text selection.
+ if (event.defaultPrevented || !isTouchClick(event)) return;
+ const target = event.target as Element;
+ if (!event.currentTarget.contains(target)) return;
+ if (
+ target.closest(
+ 'button, a, input, textarea, select, [role="button"], [contenteditable="true"]',
+ )
+ )
+ return;
+ if (window.getSelection()?.isCollapsed === false) return;
+ event.currentTarget.focus({ preventScroll: true });
+}
diff --git a/studio/frontend/src/components/assistant-ui/user-message-actions.tsx b/studio/frontend/src/components/assistant-ui/user-message-actions.tsx
new file mode 100644
index 00000000000..e46ba8db2f4
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/user-message-actions.tsx
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { ActionBarPrimitive } from "@assistant-ui/react";
+import type { FC, PropsWithChildren } from "react";
+import { UserMessageTime } from "./user-message-time";
+
+/** Use the message's full width, independently of the bubble's 80% limit. */
+export const UserMessageFooter: FC<PropsWithChildren> = ({ children }) => (
+ <div className="aui-user-message-footer mt-1 -mr-[var(--icon-btn-inset)] flex min-h-8 w-full min-w-0 flex-wrap items-center justify-end gap-y-1">
+ {children}
+ </div>
+);
+
+export const UserMessageActionBar: FC<PropsWithChildren> = ({ children }) => (
+ <ActionBarPrimitive.Root
+ autohide="always"
+ className="aui-user-action-bar-root contents text-chat-icon-fg"
+ >
+ <UserMessageTime />
+ {/* The date can shrink; the action targets retain their size. On very
+ narrow panes the footer can wrap the branch picker onto another row. */}
+ <div className="aui-user-action-controls flex shrink-0 gap-1 [&_button]:size-8 [&_button]:!rounded-full [&_button:hover]:bg-chat-icon-bg-hover [&_button:hover]:text-chat-icon-fg-hover">
+ {children}
+ </div>
+ </ActionBarPrimitive.Root>
+);
diff --git a/studio/frontend/src/components/assistant-ui/user-message-time.tsx b/studio/frontend/src/components/assistant-ui/user-message-time.tsx
index b1f9a62c487..eea78c6060f 100644
--- a/studio/frontend/src/components/assistant-ui/user-message-time.tsx
+++ b/studio/frontend/src/components/assistant-ui/user-message-time.tsx
@@ -3,32 +3,51 @@
import { useLocale, useT } from "@/i18n";
import { formatMessageDate } from "@/lib/format-message-date";
+import { messageTimestamp } from "@/lib/message-timestamp";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import { useAuiState } from "@assistant-ui/react";
import type { FC } from "react";
-/** When a prompt was sent, left of its action bar. That bar mounts only while hovered, so no timer. */
+/** Mounted only while the prompt's actions are revealed, with no clock subscription. */
export const UserMessageTime: FC = () => {
const t = useT();
const locale = useLocale();
- const createdAt = useAuiState(({ message }) => message.createdAt?.getTime());
- if (createdAt === undefined || !Number.isFinite(createdAt)) {
+ const createdAt = useAuiState(({ message }) => messageTimestamp(message));
+ if (createdAt === undefined) {
return null;
}
const date = new Date(createdAt);
+ const fullDate = date.toLocaleString(locale, {
+ dateStyle: "full",
+ timeStyle: "short",
+ });
return (
- <time
- dateTime={date.toISOString()}
- title={date.toLocaleString(locale, {
- dateStyle: "full",
- timeStyle: "short",
- })}
- className="aui-user-message-time mr-1 self-center whitespace-nowrap select-none text-ui-13 text-muted-foreground tabular-nums"
- >
- {formatMessageDate(createdAt, Date.now(), locale, {
- // Today reads as just the time.
- today: (time) => time,
- yesterday: (time) => t("common.yesterdayAt", { time }),
- })}
- </time>
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={fullDate}
+ className="aui-user-message-time-trigger mr-2 h-8 min-w-8 flex-1 cursor-pointer self-center rounded-sm text-right text-ui-13 text-muted-foreground tabular-nums"
+ >
+ <time
+ dateTime={date.toISOString()}
+ className="aui-user-message-time block truncate select-none"
+ >
+ {formatMessageDate(createdAt, Date.now(), locale, {
+ // Today reads as just the time.
+ today: (time) => time,
+ yesterday: (time) => t("common.yesterdayAt", { time }),
+ })}
+ </time>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" align="end">
+ {fullDate}
+ </TooltipContent>
+ </Tooltip>
);
};
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 8765d8d7295..4fb1bd7db79 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -1091,7 +1091,9 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {
role: "user" as const,
content: content as Extract<ThreadMessage, { role: "user" }>["content"],
attachments: cloneAttachments(m.attachments),
- metadata: { custom: {} },
+ metadata: {
+ custom: m.metadata?.createdAtEstimated === true ? { createdAtEstimated: true } : {},
+ },
};
}
const custom = (m.metadata as Record<string, unknown>) ?? {};
diff --git a/studio/frontend/src/features/chat/utils/chat-import.ts b/studio/frontend/src/features/chat/utils/chat-import.ts
index fbc4b5b7129..ce30f862aba 100644
--- a/studio/frontend/src/features/chat/utils/chat-import.ts
+++ b/studio/frontend/src/features/chat/utils/chat-import.ts
@@ -219,6 +219,8 @@ function oaiMessagesToRecords(
role: (role === "developer" ? "system" : role) as MessageRecord["role"],
content: content as MessageRecord["content"],
createdAt: baseTs + idx,
+ // Ordering only: these formats do not carry a per-message send time.
+ metadata: { createdAtEstimated: true },
});
prevId = id;
idx++;
@@ -262,6 +264,8 @@ function sharegptToRecords(
role,
content: [{ type: "text", text: value }] as MessageRecord["content"],
createdAt: baseTs + idx,
+ // Ordering only: these formats do not carry a per-message send time.
+ metadata: { createdAtEstimated: true },
});
prevId = id;
idx++;
@@ -289,6 +293,8 @@ function csvToRecords(csvText: string, threadId: string, baseTs: number): Messag
role: validRole as MessageRecord["role"],
content: [{ type: "text", text: content }] as MessageRecord["content"],
createdAt: baseTs + idx,
+ // Ordering only: these formats do not carry a per-message send time.
+ metadata: { createdAtEstimated: true },
});
prevId = id;
idx++;
diff --git a/studio/frontend/src/features/chat/utils/openwebui-import.ts b/studio/frontend/src/features/chat/utils/openwebui-import.ts
index cbaa5d8df94..b08812d28fe 100644
--- a/studio/frontend/src/features/chat/utils/openwebui-import.ts
+++ b/studio/frontend/src/features/chat/utils/openwebui-import.ts
@@ -626,7 +626,8 @@ export function openWebUIRecordToConversation(
const id = crypto.randomUUID();
keptIdByOriginal.set(node.id, id);
- const ts = Math.max(previousTs + 1, epochMs(node.raw.timestamp) ?? 0);
+ const sourceTimestamp = epochMs(node.raw.timestamp);
+ const ts = Math.max(previousTs + 1, sourceTimestamp ?? 0);
previousTs = ts;
messages.push({
@@ -639,6 +640,9 @@ export function openWebUIRecordToConversation(
? { attachments: attachments as MessageRecord["attachments"] }
: {}),
createdAt: ts,
+ ...((sourceTimestamp === null || ts !== sourceTimestamp) && {
+ metadata: { createdAtEstimated: true },
+ }),
});
}
diff --git a/studio/frontend/src/features/chat/utils/studio-backup-import.ts b/studio/frontend/src/features/chat/utils/studio-backup-import.ts
index b9556df127e..58e3d9ed6cf 100644
--- a/studio/frontend/src/features/chat/utils/studio-backup-import.ts
+++ b/studio/frontend/src/features/chat/utils/studio-backup-import.ts
@@ -206,6 +206,9 @@ export function studioBackupToConversations(
record.attachments = raw.attachments as MessageRecord["attachments"];
}
if (isDict(raw.metadata)) record.metadata = detachMetadata(raw.metadata);
+ if (num(raw.createdAt) === null) {
+ record.metadata = { ...record.metadata, createdAtEstimated: true };
+ }
return record;
});
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index e86bbdd5376..f0543b2cadb 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -2143,7 +2143,7 @@ html[data-chat-font] .aui-root {
outline-offset: -1px;
}
- /* The backward-traversal reveal sentinel in thread.tsx is a real tab stop, so it needs a
+ /* The backward-traversal reveal sentinels in thread.tsx are real tab stops, so they need a
real focus indicator. The rule above is scoped to :where(div, main, ...) and never
matched a span, so focus visibly disappeared for one stop before the next Shift+Tab
reached the action bar, which is a focus-visible failure rather than a cosmetic one.
@@ -2152,14 +2152,16 @@ html[data-chat-font] .aui-root {
in layout, so the indicator appears without shifting the message the way giving the span
dimensions on focus would. Nothing is drawn at rest, and :focus-visible means a mouse
click never draws it either. */
- .aui-assistant-reveal-sentinel {
+ .aui-assistant-reveal-sentinel,
+ .aui-user-reveal-sentinel {
display: inline-block;
width: 0;
height: 0;
vertical-align: middle;
}
- .aui-assistant-reveal-sentinel:focus-visible {
+ .aui-assistant-reveal-sentinel:focus-visible,
+ .aui-user-reveal-sentinel:focus-visible {
outline: 1px solid var(--ring-soft);
outline-offset: 6px;
border-radius: 2px;
diff --git a/studio/frontend/src/lib/message-timestamp.ts b/studio/frontend/src/lib/message-timestamp.ts
new file mode 100644
index 00000000000..2f4ca1860cb
--- /dev/null
+++ b/studio/frontend/src/lib/message-timestamp.ts
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Importers may need a synthetic ordering key when no send time is known. */
+export function messageTimestamp(message: {
+ createdAt?: Date;
+ metadata?: { custom?: Record<string, unknown> };
+}): number | undefined {
+ if (message.metadata?.custom?.createdAtEstimated === true) return undefined;
+ const time = message.createdAt?.getTime();
+ return time !== undefined && Number.isFinite(time) ? time : undefined;
+}
diff --git a/studio/frontend/tests/fixtures/user-message-time/index.html b/studio/frontend/tests/fixtures/user-message-time/index.html
new file mode 100644
index 00000000000..4dfc4885c6d
--- /dev/null
+++ b/studio/frontend/tests/fixtures/user-message-time/index.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <script src="/crypto-boot.js"></script>
+ <title>User message time regression</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/tests/fixtures/user-message-time/main.tsx b/studio/frontend/tests/fixtures/user-message-time/main.tsx
new file mode 100644
index 00000000000..8632cc36af9
--- /dev/null
+++ b/studio/frontend/tests/fixtures/user-message-time/main.tsx
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Real runtime, focus handling, footer, timestamp and stylesheet. Only message
+// data and the unrelated action handlers are fixtures; no backend is needed.
+import {
+ AssistantRuntimeProvider,
+ MessagePrimitive,
+ ThreadPrimitive,
+ useExternalStoreRuntime,
+ type ThreadMessage,
+} from "@assistant-ui/react";
+import { useState, type CSSProperties } from "react";
+import { createRoot } from "react-dom/client";
+import {
+ UserMessageActionBar,
+ UserMessageFooter,
+} from "@/components/assistant-ui/user-message-actions";
+import { useActionBarFocusReveal } from "@/components/assistant-ui/use-action-bar-focus-reveal";
+import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { setLocale, type Locale } from "@/i18n";
+import "./styles.css";
+
+const params = new URLSearchParams(location.search);
+const now = new Date();
+const createdAt = params.has("invalid")
+ ? new Date(NaN)
+ : params.has("today")
+ ? now
+ : new Date(now.getFullYear() - 1, 8, 11, 23, 22);
+const initial: ThreadMessage[] = Array.from(
+ { length: Number(params.get("count") ?? 1) },
+ (_, i) => ({
+ id: `user-${i}`,
+ role: "user",
+ createdAt,
+ content: [{ type: "text", text: "Hello" }],
+ attachments: [],
+ metadata: {
+ custom: params.has("estimated") ? { createdAtEstimated: true } : {},
+ },
+ }),
+);
+initial.push({
+ id: "assistant",
+ role: "assistant",
+ createdAt: now,
+ content: [{ type: "text", text: "Reply" }],
+ status: { type: "running" },
+ metadata: {
+ custom: {},
+ unstable_state: null,
+ steps: [],
+ unstable_annotations: [],
+ unstable_data: [],
+ },
+});
+
+function User() {
+ const reveal = useActionBarFocusReveal();
+ return (
+ <MessagePrimitive.Root
+ className="aui-user-message-root mx-auto flex w-full min-w-0 flex-col items-end py-4"
+ tabIndex={0}
+ {...reveal}
+ >
+ <div className="rounded-2xl bg-muted px-4 py-2">Hello</div>
+ <UserMessageFooter>
+ <UserMessageActionBar>
+ {["Copy", "Edit", "Fork", "Delete"].map((label) => (
+ <TooltipIconButton key={label} tooltip={label}>
+ <span aria-hidden="true">{label[0]}</span>
+ </TooltipIconButton>
+ ))}
+ </UserMessageActionBar>
+ {params.has("branches") && (
+ <div className="aui-user-branch-picker ml-0.5 inline-flex shrink-0 items-center text-ui-13">
+ <button className="aui-branch-chevron-btn" aria-label="Previous">
+ ‹
+ </button>
+ <span className="font-mono tabular-nums">1/2</span>
+ <button className="aui-branch-chevron-btn" aria-label="Next">
+ ›
+ </button>
+ </div>
+ )}
+ </UserMessageFooter>
+ <span
+ className="aui-user-reveal-sentinel"
+ tabIndex={0}
+ aria-label="Message actions"
+ />
+ </MessagePrimitive.Root>
+ );
+}
+function Assistant() {
+ return (
+ <MessagePrimitive.Root>
+ <MessagePrimitive.Parts />
+ </MessagePrimitive.Root>
+ );
+}
+declare global {
+ interface Window {
+ messageTimeFixture: {
+ updateReply: () => void;
+ setLocale: typeof setLocale;
+ };
+ }
+}
+function App() {
+ const [messages, setMessages] = useState(initial);
+ const runtime = useExternalStoreRuntime({
+ messages,
+ isRunning: true,
+ onNew: async () => {},
+ });
+ window.messageTimeFixture = {
+ setLocale,
+ updateReply: () =>
+ setMessages((previous) =>
+ previous.map((message) =>
+ message.role === "assistant"
+ ? {
+ ...message,
+ content: [{ type: "text", text: `Streaming ${Math.random()}` }],
+ }
+ : message,
+ ),
+ ),
+ };
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <TooltipProvider>
+ <button id="before">Before chat</button>
+ <ThreadPrimitive.Root
+ className="aui-root flex flex-col overflow-hidden"
+ style={
+ {
+ height: 500,
+ "--thread-content-max-width": "46rem",
+ } as CSSProperties
+ }
+ >
+ <ThreadPrimitive.Viewport
+ autoScroll={false}
+ className="aui-thread-viewport min-w-0 overflow-auto px-5"
+ >
+ <ThreadPrimitive.Messages
+ components={{ UserMessage: User, AssistantMessage: Assistant }}
+ />
+ </ThreadPrimitive.Viewport>
+ </ThreadPrimitive.Root>
+ <button id="after">After chat</button>
+ </TooltipProvider>
+ </AssistantRuntimeProvider>
+ );
+}
+await setLocale((params.get("locale") ?? "en") as Locale);
+if (params.has("scale"))
+ document.documentElement.style.setProperty(
+ "--ui-font-size-scale",
+ params.get("scale")!,
+ );
+createRoot(document.getElementById("root")!).render(<App />);
diff --git a/studio/frontend/tests/fixtures/user-message-time/styles.css b/studio/frontend/tests/fixtures/user-message-time/styles.css
new file mode 100644
index 00000000000..ac1bfbb216a
--- /dev/null
+++ b/studio/frontend/tests/fixtures/user-message-time/styles.css
@@ -0,0 +1,6 @@
+/* SPDX-License-Identifier: AGPL-3.0-only */
+/* Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 */
+
+@import "../../../src/index.css";
+@source "../../../src";
+@source "./";
diff --git a/studio/frontend/tests/fixtures/user-message-time/vite.config.ts b/studio/frontend/tests/fixtures/user-message-time/vite.config.ts
new file mode 100644
index 00000000000..812354e4a9f
--- /dev/null
+++ b/studio/frontend/tests/fixtures/user-message-time/vite.config.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Isolated message/footer rendering; no backend or model required.
+
+// biome-ignore lint/correctness/noNodejsModules: Vite configs execute in Node.
+import path from "node:path";
+import tailwindcss from "@tailwindcss/vite";
+import react from "@vitejs/plugin-react";
+import { defineConfig } from "vite";
+
+const frontendRoot = path.resolve(__dirname, "../../..");
+const sourceFrontend = path.resolve(
+ process.env.PW_SOURCE_FRONTEND_DIR ?? frontendRoot,
+);
+
+// biome-ignore lint/style/noDefaultExport: Vite loads its config as a default export.
+export default defineConfig({
+ root: __dirname,
+ publicDir: path.resolve(frontendRoot, "public"),
+ plugins: [react(), tailwindcss()],
+ css: { postcss: { plugins: [] } },
+ server: {
+ host: "127.0.0.1",
+ fs: { allow: [frontendRoot, sourceFrontend] },
+ },
+ resolve: {
+ // Source files live in a second worktree during the negative control. Keep
+ // one React runtime even when that checkout has its own dependency tree.
+ dedupe: ["react", "react-dom"],
+ alias: {
+ "@": path.resolve(sourceFrontend, "src"),
+ "@dagrejs/dagre": path.resolve(
+ frontendRoot,
+ "node_modules/@dagrejs/dagre/dist/dagre.cjs.js",
+ ),
+ },
+ },
+ optimizeDeps: { include: ["@dagrejs/dagre", "@dagrejs/graphlib"] },
+});
diff --git a/studio/frontend/tests/message-jsonl-import.test.ts b/studio/frontend/tests/message-jsonl-import.test.ts
index 2ff84311537..766195e13c1 100644
--- a/studio/frontend/tests/message-jsonl-import.test.ts
+++ b/studio/frontend/tests/message-jsonl-import.test.ts
@@ -190,3 +190,15 @@ test("assistant images are represented explicitly in JSONL exports", () => {
[{ role: "assistant", content: "Chart\n\n[image attachment]" }],
);
});
+
+test("imports without message send times mark their ordering timestamps as estimated", () => {
+ for (const [filename, source] of [
+ ["messages.jsonl", '{"messages":[{"role":"user","content":"Hello"}]}'],
+ ["sharegpt.jsonl", '{"created_at":1700000000000,"conversations":[{"from":"human","value":"Hello"}]}'],
+ ["messages.csv", "role,content\nuser,Hello"],
+ ]) {
+ const conversation = parseImportText(source, filename)[0];
+ assert.ok(conversation, filename);
+ assert.equal(conversation.messages[0].metadata?.createdAtEstimated, true, filename);
+ }
+});
diff --git a/studio/frontend/tests/openwebui-import.test.ts b/studio/frontend/tests/openwebui-import.test.ts
index 7d88c8b1251..97683e62b39 100644
--- a/studio/frontend/tests/openwebui-import.test.ts
+++ b/studio/frontend/tests/openwebui-import.test.ts
@@ -93,6 +93,10 @@ test("the branch the user had open is imported last, so the thread reopens where
const stamps = conversation.messages.map((message) => message.createdAt);
assert.deepEqual([...stamps].sort((a, b) => a - b), stamps);
assert.equal(new Set(stamps).size, stamps.length);
+ // The selected sibling was imported after a later sibling, so preserving
+ // traversal order moved its timestamp. Do not present that synthetic value
+ // as the original send time.
+ assert.equal(conversation.messages[3].metadata?.createdAtEstimated, true);
});
test("a parent cycle and a dangling currentId are imported instead of hanging or dropping the chat", () => {
@@ -1049,3 +1053,13 @@ test("reasoning survives an empty summary next to populated content", () => {
assert.ok(both);
assert.deepEqual(parts(both, 0), [{ type: "reasoning", text: "the summary" }]);
});
+
+test("missing send times are distinguished from real Open WebUI timestamps", () => {
+ const conversation = openWebUIRecordToConversation(recordOf([
+ { id: "u", role: "user", content: "unknown", parentId: null },
+ { id: "a", role: "assistant", content: "known", parentId: "u", timestamp: 1_700_000_100 },
+ ], "a"), "Imported");
+ assert.ok(conversation);
+ assert.equal(conversation.messages[0].metadata?.createdAtEstimated, true);
+ assert.notEqual(conversation.messages[1].metadata?.createdAtEstimated, true);
+});
diff --git a/studio/frontend/tests/studio-backup-import.test.ts b/studio/frontend/tests/studio-backup-import.test.ts
index cee91339162..d2fad30e157 100644
--- a/studio/frontend/tests/studio-backup-import.test.ts
+++ b/studio/frontend/tests/studio-backup-import.test.ts
@@ -669,3 +669,16 @@ test("a message whose content was stored as a plain string keeps its text", asyn
[],
]);
});
+
+test("backup import preserves estimated-time provenance and marks missing dates", async () => {
+ const data = backup();
+ delete (data.messages[0] as Partial<MessageRecord>).createdAt;
+ data.messages[1].metadata = { createdAtEstimated: true };
+ const { module, messages } = harness();
+ await module.importConversationsFromSource(sourceOf("backup.json", data));
+ const restored = [...messages.values()].flat();
+ const byText = (text: string) => restored.find(({ content }) => (content[0] as { text: string }).text === text);
+ assert.equal(byText("Where to?")?.metadata?.createdAtEstimated, true);
+ assert.equal(byText("Lisbon")?.metadata?.createdAtEstimated, true);
+ assert.notEqual(byText("Porto")?.metadata?.createdAtEstimated, true);
+});
diff --git a/studio/frontend/tests/user-message-time.test.ts b/studio/frontend/tests/user-message-time.test.ts
index 029bb3f0e0f..b31f82756d4 100644
--- a/studio/frontend/tests/user-message-time.test.ts
+++ b/studio/frontend/tests/user-message-time.test.ts
@@ -1,31 +1,57 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// A prompt's send time shows on hover, left of its action bar. It must stay inside that
-// autohide bar, which mounts only while the message is hovered, so an idle thread renders
-// no timestamps and runs no timers.
-
+// Rendered hover, focus, touch, layout and streaming coverage lives in
+// tests/studio/playwright_user_message_time.py. These checks pin the production
+// call sites to those tested components and cover invalid/estimated dates.
import assert from "node:assert/strict";
import test from "node:test";
-
import { readSrc } from "./helpers/kit.ts";
+import { messageTimestamp } from "../src/lib/message-timestamp.ts";
const THREAD = readSrc("components/assistant-ui/thread.tsx");
+const ACTIONS = readSrc("components/assistant-ui/user-message-actions.tsx");
const TIME = readSrc("components/assistant-ui/user-message-time.tsx");
-test("the time is the first child of the hover-only user action bar", () => {
- const start = THREAD.indexOf("const UserActionBar: FC = () => {");
- assert.notEqual(
+test("user messages use the tested footer and focus/touch reveal", () => {
+ const start = THREAD.indexOf("const UserMessage: FC = () => {");
+ assert.notEqual(start, -1);
+ const message = THREAD.slice(
start,
- -1,
- "UserActionBar is gone; this test needs rewriting",
+ THREAD.indexOf("const EditComposer:", start),
);
- const bar = THREAD.slice(start, THREAD.indexOf("\n};", start));
- assert.match(bar, /autohide="always"/);
- assert.match(bar, /<UserMessageTime \/>\s*<CopyButton \/>/);
+ assert.match(message, /useActionBarFocusReveal\(\)/);
+ assert.match(message, /tabIndex=\{0\}/);
+ assert.match(message, /\{\.\.\.focusReveal\}/);
+ assert.match(message, /<UserMessageFooter>/);
+ assert.match(message, /<UserMessageActionBar>/);
+ assert.match(message, /aui-user-reveal-sentinel/);
+ assert.match(message, /aui-user-message-content-wrapper flex w-full/);
+ assert.match(ACTIONS, /autohide="always"/);
+ assert.match(ACTIONS, /<UserMessageTime \/>/);
});
-test("the time renders once per hover, with no timer or interval", () => {
+test("the timestamp has no periodic clock work", () => {
assert.doesNotMatch(TIME, /setInterval|setTimeout|useEffect/);
- assert.match(TIME, /formatMessageDate\(/);
+});
+
+test("only known, valid message times are displayed", () => {
+ const createdAt = new Date("2025-09-11T23:22:00Z");
+ assert.equal(messageTimestamp({ createdAt }), createdAt.getTime());
+ assert.equal(messageTimestamp({}), undefined);
+ assert.equal(messageTimestamp({ createdAt: new Date(NaN) }), undefined);
+ assert.equal(
+ messageTimestamp({
+ createdAt,
+ metadata: { custom: { createdAtEstimated: true } },
+ }),
+ undefined,
+ );
+ assert.equal(
+ messageTimestamp({
+ createdAt,
+ metadata: { custom: { createdAtEstimated: false } },
+ }),
+ createdAt.getTime(),
+ );
});
diff --git a/tests/studio/playwright_user_message_time.py b/tests/studio/playwright_user_message_time.py
new file mode 100644
index 00000000000..3fb6efa5cf1
--- /dev/null
+++ b/tests/studio/playwright_user_message_time.py
@@ -0,0 +1,241 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Timestamp behavior against real assistant-ui primitives and application CSS.
+
+Run: python tests/studio/playwright_user_message_time.py
+Requires frontend npm dependencies and Python Playwright/Chromium. No backend
+or GPU is needed. PW_CHROMIUM_EXECUTABLE may select an installed browser.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import shutil
+import socket
+import subprocess
+import tempfile
+from pathlib import Path
+from urllib.request import urlopen
+
+from playwright.async_api import async_playwright
+
+FRONTEND = Path(__file__).resolve().parents[2] / "studio" / "frontend"
+
+
+async def paint(page):
+ await page.evaluate("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
+
+
+async def check(url):
+ async with async_playwright() as playwright:
+ launch = {"headless": True}
+ if os.environ.get("PW_CHROMIUM_EXECUTABLE"):
+ launch["executable_path"] = os.environ["PW_CHROMIUM_EXECUTABLE"]
+ browser = await playwright.chromium.launch(**launch)
+ try:
+ page = await browser.new_page(viewport = {"width": 800, "height": 650})
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ await page.add_init_script("""
+ window.formatCalls = 0;
+ for (const name of ['toLocaleString', 'toLocaleTimeString']) {
+ const original = Date.prototype[name];
+ Date.prototype[name] = function(...args) {
+ window.formatCalls++;
+ return original.apply(this, args);
+ };
+ }
+ """)
+ await page.goto(url + "?count=500&today")
+ await page.locator(".aui-user-message-root").first.wait_for()
+ await page.mouse.move(799, 640)
+ await paint(page)
+ assert await page.locator("time").count() == 0
+ assert await page.evaluate("window.formatCalls") == 0
+ first = page.locator(".aui-user-message-root").first
+ await first.hover()
+ await page.locator("time").wait_for()
+ print("Hover mounted; checking streaming", flush = True)
+ calls = await page.evaluate("window.formatCalls")
+ assert calls == 2, calls
+ for _ in range(120):
+ await page.evaluate("window.messageTimeFixture.updateReply()")
+ await paint(page)
+ assert await page.evaluate("window.formatCalls") == calls
+ assert await page.locator("time").count() == 1
+ await page.mouse.move(799, 640)
+ await paint(page)
+ assert await page.locator("time").count() == 0
+
+ print("Streaming passed; checking keyboard", flush = True)
+ # Keyboard focus mounts the bar and exposes the full date. Leaving
+ # the message with the mouse must not unmount a focused control.
+ await page.goto(url + "?branches")
+ await page.locator("#before").focus()
+ await page.keyboard.press("Tab")
+ await page.locator("time").wait_for()
+ await page.keyboard.press("Tab")
+ trigger = page.locator(".aui-user-message-time-trigger")
+ assert await trigger.evaluate("(e) => e === document.activeElement")
+ await page.get_by_role("tooltip").wait_for()
+ assert (
+ await trigger.get_attribute("aria-label")
+ == await page.get_by_role("tooltip").inner_text()
+ )
+ await page.locator(".aui-user-message-root").hover(position = {"x": 4, "y": 4})
+ await page.mouse.move(799, 640)
+ await paint(page)
+ assert await trigger.evaluate("(e) => e === document.activeElement")
+ await page.locator("#after").focus()
+ await paint(page)
+ assert await page.locator("time").count() == 0
+
+ # Reverse traversal first reveals the message, then enters the
+ # controls instead of skipping them for the preceding page button.
+ await page.goto(url)
+ await page.locator(".aui-user-message-root").wait_for()
+ await page.locator("#after").focus()
+ await page.keyboard.press("Shift+Tab")
+ sentinel = page.locator(".aui-user-reveal-sentinel")
+ assert await sentinel.evaluate("(e) => e === document.activeElement")
+ sentinel_style = await sentinel.evaluate(
+ "e => ({ display: getComputedStyle(e).display, "
+ "width: getComputedStyle(e).width, "
+ "height: getComputedStyle(e).height, "
+ "outlineStyle: getComputedStyle(e).outlineStyle, "
+ "outlineWidth: getComputedStyle(e).outlineWidth })"
+ )
+ expected_sentinel_style = {
+ "display": "block",
+ "width": "0px",
+ "height": "0px",
+ "outlineStyle": "solid",
+ "outlineWidth": "1px",
+ }
+ assert sentinel_style == expected_sentinel_style, sentinel_style
+ delete = page.get_by_role("button", name = "Delete", exact = True)
+ await delete.wait_for()
+ await page.keyboard.press("Shift+Tab")
+ assert await delete.evaluate("(e) => e === document.activeElement")
+
+ print("Keyboard passed; checking layout", flush = True)
+ # Long dates, translations and font scaling must fit the viewport;
+ # Copy/Edit/Fork/Delete and branch targets must retain their size.
+ layouts = []
+ for width, locale, scale in [
+ (375, "en", ".9375"),
+ (320, "en", ".9375"),
+ (375, "ru", "1.25"),
+ (320, "ar", "1.25"),
+ ]:
+ await page.set_viewport_size({"width": width, "height": 650})
+ await page.goto(f"{url}?branches&locale={locale}&scale={scale}")
+ await page.locator(".aui-user-message-root").hover(position = {"x": 4, "y": 4})
+ await page.locator("time").wait_for()
+ await page.evaluate("document.fonts.ready")
+ geometry = await page.evaluate("""() => {
+ const viewport = document.querySelector('.aui-thread-viewport').getBoundingClientRect();
+ const rects = [...document.querySelectorAll('.aui-user-message-footer button')].map(e => {
+ const r = e.getBoundingClientRect();
+ return {x:r.x, right:r.right, width:r.width, timestamp:e.classList.contains('aui-user-message-time-trigger')};
+ });
+ return {left:viewport.left, right:viewport.right, rects};
+ }""")
+ for rect in geometry["rects"]:
+ assert rect["x"] >= geometry["left"] - 1, geometry
+ assert rect["right"] <= geometry["right"] + 1, geometry
+ if not rect["timestamp"]:
+ assert rect["width"] >= 24, geometry
+ layouts.append({"width": width, "locale": locale, "scale": scale})
+
+ # Invalid or synthetic timestamps leave the controls usable.
+ for query in ["invalid", "estimated"]:
+ await page.goto(url + "?" + query)
+ await page.locator(".aui-user-message-root").hover(position = {"x": 4, "y": 4})
+ await page.get_by_role("button", name = "Copy", exact = True).wait_for()
+ assert await page.locator("time").count() == 0
+
+ touch = await browser.new_page(
+ viewport = {"width": 375, "height": 650}, has_touch = True, is_mobile = True
+ )
+ touch.on("pageerror", lambda error: errors.append(str(error)))
+ await touch.goto(url + "?branches")
+ await touch.get_by_text("Hello", exact = True).tap()
+ await touch.locator("time").wait_for()
+ await touch.locator(".aui-user-message-time-trigger").tap()
+ await touch.get_by_role("tooltip").wait_for()
+ assert await touch.get_by_role("tooltip").inner_text() == await touch.locator(
+ ".aui-user-message-time-trigger"
+ ).get_attribute("aria-label")
+ await touch.locator("#after").tap()
+ await paint(touch)
+ assert await touch.locator("time").count() == 0
+ assert not errors, errors
+ print(
+ json.dumps(
+ {
+ "streamUpdates": 120,
+ "messages": 500,
+ "extraFormatCalls": 0,
+ "layouts": layouts,
+ "keyboard": "passed",
+ "touch": "passed",
+ "invalidAndEstimated": "passed",
+ },
+ indent = 2,
+ )
+ )
+ finally:
+ await browser.close()
+
+
+async def main():
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ url = f"http://127.0.0.1:{port}/"
+ node = shutil.which("node")
+ assert node, "Node.js is required"
+ with tempfile.TemporaryFile(mode = "w+") as log:
+ server = subprocess.Popen(
+ [
+ node,
+ "node_modules/vite/bin/vite.js",
+ "--config",
+ "tests/fixtures/user-message-time/vite.config.ts",
+ "--port",
+ str(port),
+ "--strictPort",
+ ],
+ cwd = FRONTEND,
+ stdout = log,
+ stderr = subprocess.STDOUT,
+ )
+ try:
+ for _ in range(150):
+ if server.poll() is not None:
+ log.seek(0)
+ raise RuntimeError(log.read())
+ try:
+ with urlopen(url, timeout = 1) as response:
+ if response.status == 200:
+ break
+ except OSError:
+ await asyncio.sleep(0.2)
+ else:
+ raise RuntimeError("Vite did not start")
+ await check(url)
+ finally:
+ server.terminate()
+ try:
+ server.wait(timeout = 5)
+ except subprocess.TimeoutExpired:
+ server.kill()
+ server.wait()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())