feat(webui): streamline contextual message controls (#5831)
This commit is contained in:
1 parent
99a7ec256f
commit
920efd00b8
24 files changed
+1776
-955
No files matched your search
@@ -5,10 +5,10 @@ import {
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentPropsWithoutRef,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
Activity,
|
||||
Check,
|
||||
ChevronRight,
|
||||
CircleAlert,
|
||||
@@ -23,7 +23,7 @@ import { DisclosureContent } from "@/components/ui/disclosure";
|
||||
|
||||
import { AttachmentTile } from "@/components/AttachmentTile";
|
||||
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
||||
import { ResponseSourceBadge } from "@/components/ResponseSourceBadge";
|
||||
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { MarkdownText } from "@/components/MarkdownText";
|
||||
import { SlashCommandText } from "@/components/SlashCommandText";
|
||||
@@ -38,10 +38,7 @@ import {
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import {
|
||||
fmtDateTime,
|
||||
formatMessageEndTime,
|
||||
} from "@/lib/format";
|
||||
import { formatMessageEndTime } from "@/lib/format";
|
||||
import { toMediaAttachment } from "@/lib/media";
|
||||
import { matchingSlashCommand } from "@/lib/slash-command";
|
||||
import { sessionHandleColor } from "@/lib/session-handle";
|
||||
@@ -61,19 +58,14 @@ import type {
|
||||
|
||||
interface MessageBubbleProps {
|
||||
message: UIMessage;
|
||||
/** The containing agent turn has not received turn_end yet. */
|
||||
isTurnStreaming?: boolean;
|
||||
/** Give temporary-chat user turns the dashed private-mode treatment. */
|
||||
temporary?: boolean;
|
||||
/** When false, hide this message's copy button. Default true. */
|
||||
showCopyAction?: boolean;
|
||||
/** Whether this message is the final display unit in the thread. */
|
||||
isThreadTail?: boolean;
|
||||
cliApps?: CliAppInfo[];
|
||||
mcpPresets?: McpPresetInfo[];
|
||||
slashCommands?: SlashCommand[];
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
onForkFromHere?: () => void;
|
||||
/** Context-menu trigger positioned against this message's visual block. */
|
||||
contextMenu?: ReactNode;
|
||||
}
|
||||
|
||||
function ForkArrowIcon({ className }: { className?: string }) {
|
||||
@@ -96,43 +88,7 @@ function ForkArrowIcon({ className }: { className?: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
type MessageTimestampProps = Omit<
|
||||
ComponentPropsWithoutRef<"time">,
|
||||
"dateTime" | "title"
|
||||
> & {
|
||||
timestamp: number;
|
||||
tooltipLabel: string;
|
||||
};
|
||||
|
||||
function MessageTimestamp({
|
||||
timestamp,
|
||||
tooltipLabel,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: MessageTimestampProps) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<time
|
||||
{...props}
|
||||
dateTime={new Date(timestamp).toISOString()}
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
"cursor-help text-[11px] leading-none text-muted-foreground/70 tabular-nums",
|
||||
"focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</time>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">{tooltipLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageCopyButton({ content }: { content: string }) {
|
||||
function useMessageCopy(content: string) {
|
||||
const { t } = useTranslation();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copyResetRef = useRef<number | null>(null);
|
||||
@@ -160,28 +116,199 @@ function MessageCopyButton({ content }: { content: string }) {
|
||||
}, [content]);
|
||||
|
||||
const label = copied ? t("message.copiedReply") : t("message.copyReply");
|
||||
return { copied, label, onCopy };
|
||||
}
|
||||
|
||||
interface MessageBlockMenuActivity {
|
||||
label: string;
|
||||
expanded: boolean;
|
||||
controls: string;
|
||||
onToggle: () => void;
|
||||
}
|
||||
|
||||
interface MessageBlockMenuActionsProps {
|
||||
message: UIMessage;
|
||||
isTurnStreaming?: boolean;
|
||||
onForkFromHere?: () => void;
|
||||
activity?: MessageBlockMenuActivity;
|
||||
}
|
||||
|
||||
/** Actions and metadata shown after opening a visual message block's context panel. */
|
||||
export function MessageBlockMenuActions({
|
||||
message,
|
||||
isTurnStreaming = false,
|
||||
onForkFromHere,
|
||||
activity,
|
||||
}: MessageBlockMenuActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const content = message.role === "assistant"
|
||||
? message.compactReply === "empty"
|
||||
? t("thread.compaction.empty")
|
||||
: message.compactReply === "failed"
|
||||
? t("thread.compaction.failed")
|
||||
: message.content
|
||||
: message.content;
|
||||
const hasText = content.trim().length > 0;
|
||||
const { copied, label: copyLabel, onCopy } = useMessageCopy(content);
|
||||
const showFork = message.role === "assistant"
|
||||
&& !message.isStreaming
|
||||
&& !isTurnStreaming
|
||||
&& hasText
|
||||
&& onForkFromHere !== undefined;
|
||||
const timestamp = message.role === "assistant"
|
||||
&& typeof message.completedAt === "number"
|
||||
&& Number.isFinite(message.completedAt)
|
||||
? message.completedAt
|
||||
: message.createdAt;
|
||||
const timestampLabel = typeof timestamp === "number" && Number.isFinite(timestamp)
|
||||
? formatMessageEndTime(timestamp)
|
||||
: "";
|
||||
const automationSourceLabel = message.role === "assistant"
|
||||
&& ["cron", "local_trigger", "trigger"].includes(message.source?.kind ?? "")
|
||||
? message.source?.label?.trim() || t("message.automationSourceFallback")
|
||||
: "";
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCopy}
|
||||
aria-label={label}
|
||||
className={cn(
|
||||
"touch-target inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
|
||||
"transition-colors hover:bg-muted/55 hover:text-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
)}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-4 w-4" aria-hidden />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" aria-hidden />
|
||||
)}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
<TooltipProvider>
|
||||
<div
|
||||
data-message-block-menu-actions
|
||||
className="flex w-max max-w-full flex-col items-start gap-1"
|
||||
>
|
||||
{hasText || showFork || activity ? (
|
||||
<div
|
||||
data-message-block-toolbar
|
||||
className="flex w-full flex-wrap items-center gap-x-1 gap-y-1"
|
||||
>
|
||||
{hasText || showFork ? (
|
||||
<div className="flex min-h-[var(--message-block-control-size)] items-center gap-0.5">
|
||||
{hasText ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
data-message-block-copy-action
|
||||
data-assistant-copy-action={message.role === "assistant" || undefined}
|
||||
onClick={onCopy}
|
||||
aria-label={copyLabel}
|
||||
className={cn(
|
||||
"inline-flex h-[var(--message-block-control-size)] w-[var(--message-block-action-width)] items-center justify-center rounded-control",
|
||||
"text-muted-foreground transition-[color,background-color,scale]",
|
||||
"hover:bg-muted/70 hover:text-foreground active:scale-[0.96]",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
"motion-reduce:transform-none",
|
||||
)}
|
||||
>
|
||||
{copied ? (
|
||||
<Check
|
||||
className="h-3.5 w-3.5 -translate-x-px"
|
||||
strokeWidth={1.75}
|
||||
aria-hidden
|
||||
/>
|
||||
) : (
|
||||
<Copy
|
||||
className="h-3.5 w-3.5 -translate-x-px"
|
||||
strokeWidth={1.75}
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">{copyLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{showFork ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
data-message-block-fork-action
|
||||
data-assistant-fork-action
|
||||
onClick={onForkFromHere}
|
||||
aria-label={t("message.forkFromHere")}
|
||||
className={cn(
|
||||
"inline-flex h-[var(--message-block-control-size)] w-[var(--message-block-action-width)] items-center justify-center rounded-control",
|
||||
"text-muted-foreground transition-[color,background-color,scale]",
|
||||
"hover:bg-muted/70 hover:text-foreground active:scale-[0.96]",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
"motion-reduce:transform-none",
|
||||
)}
|
||||
>
|
||||
<ForkArrowIcon className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">
|
||||
{t("message.forkFromHere")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{activity ? (
|
||||
<button
|
||||
type="button"
|
||||
data-message-block-activity-action
|
||||
onClick={activity.onToggle}
|
||||
aria-expanded={activity.expanded}
|
||||
aria-controls={activity.controls}
|
||||
className={cn(
|
||||
"group inline-flex min-h-[var(--message-block-control-size)] self-start items-center gap-1.5 whitespace-nowrap",
|
||||
"text-start text-[11px] leading-4",
|
||||
"text-muted-foreground transition-colors hover:text-foreground",
|
||||
"focus-visible:outline-none",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
data-message-block-activity-icon
|
||||
className={cn(
|
||||
"inline-flex h-[var(--message-block-control-size)] w-[var(--message-block-action-width)] shrink-0 items-center justify-center rounded-control",
|
||||
"transition-[background-color,box-shadow,scale]",
|
||||
"group-hover:bg-muted/70 group-active:scale-[0.96]",
|
||||
"group-focus-visible:ring-2 group-focus-visible:ring-ring",
|
||||
"motion-reduce:transform-none",
|
||||
)}
|
||||
>
|
||||
<Activity className="h-3.5 w-3.5" strokeWidth={1.5} aria-hidden />
|
||||
</span>
|
||||
<span>{activity.label}</span>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<FallbackResponseSources
|
||||
sources={message.role === "assistant" ? message.responseSources : undefined}
|
||||
className="min-h-[var(--message-block-control-size)] gap-1"
|
||||
badgeClassName="h-[var(--message-block-control-size)] min-h-[var(--message-block-control-size)]"
|
||||
/>
|
||||
{timestampLabel || automationSourceLabel ? (
|
||||
<div
|
||||
data-message-block-metadata
|
||||
className="mt-0.5 w-full border-t border-border/45 px-1.5 pt-1 text-[10px] leading-4 text-muted-foreground/45"
|
||||
>
|
||||
{timestampLabel ? (
|
||||
<time
|
||||
data-message-timestamp
|
||||
data-message-created-at={message.role === "user" || undefined}
|
||||
data-assistant-completed-at={
|
||||
message.role === "assistant" && timestamp === message.completedAt || undefined
|
||||
}
|
||||
dateTime={new Date(timestamp).toISOString()}
|
||||
className="flex min-h-[var(--message-block-control-size)] items-center tabular-nums"
|
||||
>
|
||||
{timestampLabel}
|
||||
</time>
|
||||
) : null}
|
||||
{automationSourceLabel ? (
|
||||
<span
|
||||
data-automation-trigger
|
||||
className="flex min-h-[var(--message-block-control-size)] items-center break-words"
|
||||
>
|
||||
{t("message.automationTriggered")} · {automationSourceLabel}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -272,24 +399,24 @@ function UserDeliveryStatus({
|
||||
|
||||
function IncomingSessionMessage({
|
||||
message,
|
||||
showCopyAction,
|
||||
contextMenu,
|
||||
onOpenFilePreview,
|
||||
}: {
|
||||
message: UIMessage;
|
||||
showCopyAction: boolean;
|
||||
contextMenu?: ReactNode;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
}) {
|
||||
const handle = message.sessionMessage!.session;
|
||||
const color = sessionHandleColor(handle.id);
|
||||
const createdAtLabel = formatMessageEndTime(message.createdAt);
|
||||
const handleName = `@${handle.name}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-session-message
|
||||
className="group w-full text-[15px]"
|
||||
className="group relative w-full text-[15px]"
|
||||
style={{ lineHeight: "var(--cjk-line-height)" }}
|
||||
>
|
||||
{contextMenu}
|
||||
<div
|
||||
className="min-w-0 rounded-es-[16px] border-s-2 bg-background pb-1 ps-2.5"
|
||||
style={{ borderInlineStartColor: color }}
|
||||
@@ -306,23 +433,6 @@ function IncomingSessionMessage({
|
||||
</MarkdownText>
|
||||
</div>
|
||||
</div>
|
||||
{createdAtLabel || showCopyAction ? (
|
||||
<TooltipProvider>
|
||||
<div
|
||||
className="message-actions mt-1 flex min-h-8 items-center gap-1.5 text-muted-foreground"
|
||||
>
|
||||
{showCopyAction ? <MessageCopyButton content={message.content} /> : null}
|
||||
{createdAtLabel ? (
|
||||
<MessageTimestamp
|
||||
timestamp={message.createdAt}
|
||||
tooltipLabel={fmtDateTime(message.createdAt)}
|
||||
>
|
||||
{createdAtLabel}
|
||||
</MessageTimestamp>
|
||||
) : null}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -330,15 +440,12 @@ function IncomingSessionMessage({
|
||||
/** Render user turns as compact bubbles and assistant turns as document-like prose. */
|
||||
export function MessageBubble({
|
||||
message,
|
||||
isTurnStreaming = false,
|
||||
temporary = false,
|
||||
showCopyAction = true,
|
||||
isThreadTail = true,
|
||||
cliApps = [],
|
||||
mcpPresets = [],
|
||||
slashCommands = [],
|
||||
onOpenFilePreview,
|
||||
onForkFromHere,
|
||||
contextMenu,
|
||||
}: MessageBubbleProps) {
|
||||
const { t } = useTranslation();
|
||||
const mentionCliApps = useMemo(
|
||||
@@ -362,7 +469,7 @@ export function MessageBubble({
|
||||
return (
|
||||
<IncomingSessionMessage
|
||||
message={message}
|
||||
showCopyAction={showCopyAction}
|
||||
contextMenu={contextMenu}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
/>
|
||||
);
|
||||
@@ -378,9 +485,6 @@ export function MessageBubble({
|
||||
const hasText = userContent.trim().length > 0;
|
||||
const showDeliveryStatus =
|
||||
message.deliveryStatus === "sending" || message.deliveryStatus === "failed";
|
||||
const createdAtLabel = formatMessageEndTime(message.createdAt);
|
||||
const showCreatedAt = createdAtLabel.length > 0;
|
||||
const createdAtTitle = showCreatedAt ? fmtDateTime(message.createdAt) : "";
|
||||
const quotedContext = parsedMessage.quotedContext;
|
||||
const slashCommand = matchingSlashCommand(userContent, slashCommands);
|
||||
const messageText = slashCommand ? (
|
||||
@@ -402,7 +506,11 @@ export function MessageBubble({
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<div className="group ml-auto flex max-w-[min(85%,36rem)] flex-col items-end gap-1.5">
|
||||
<div
|
||||
data-user-text-bubble={hasText && !hasImages && !hasMedia && !quotedContext || undefined}
|
||||
className="group relative ml-auto flex w-fit max-w-[min(85%,36rem)] flex-col items-end gap-1.5"
|
||||
>
|
||||
{contextMenu}
|
||||
{hasImages ? <UserImages images={images} align="right" /> : null}
|
||||
{!hasImages && hasMedia ? (
|
||||
<MessageMedia media={media} align="right" />
|
||||
@@ -427,23 +535,13 @@ export function MessageBubble({
|
||||
{messageText}
|
||||
</p>
|
||||
) : null}
|
||||
{showDeliveryStatus || showCreatedAt || (hasText && showCopyAction) ? (
|
||||
{showDeliveryStatus ? (
|
||||
<TooltipProvider>
|
||||
<div className="flex min-h-8 items-center justify-end gap-1.5 text-muted-foreground">
|
||||
{showCreatedAt ? (
|
||||
<MessageTimestamp
|
||||
data-message-created-at
|
||||
timestamp={message.createdAt}
|
||||
tooltipLabel={createdAtTitle}
|
||||
>
|
||||
{createdAtLabel}
|
||||
</MessageTimestamp>
|
||||
) : null}
|
||||
<UserDeliveryStatus
|
||||
status={message.deliveryStatus}
|
||||
errorKind={message.deliveryErrorKind}
|
||||
/>
|
||||
{hasText && showCopyAction ? <MessageCopyButton content={message.content} /> : null}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
) : null}
|
||||
@@ -461,54 +559,13 @@ export function MessageBubble({
|
||||
const reasoning = message.role === "assistant" ? message.reasoning ?? "" : "";
|
||||
const reasoningStreaming = !!(message.role === "assistant" && message.reasoningStreaming);
|
||||
const hasReasoning = reasoning.length > 0 || reasoningStreaming;
|
||||
const automationSourceKind = message.source?.kind;
|
||||
const automationSourceName = message.source?.label?.trim();
|
||||
const automationSourceLabel = (
|
||||
automationSourceKind === "cron"
|
||||
|| automationSourceKind === "local_trigger"
|
||||
|| automationSourceKind === "trigger"
|
||||
)
|
||||
? (automationSourceName || t("message.automationSourceFallback"))
|
||||
: "";
|
||||
const automationTriggeredLabel = t("message.automationTriggered");
|
||||
|
||||
const showAssistantActions =
|
||||
message.role === "assistant" && !message.isStreaming && !isTurnStreaming && !empty;
|
||||
const showCopyButton = showCopyAction && showAssistantActions;
|
||||
const showForkButton = showAssistantActions && !!onForkFromHere;
|
||||
const forkLabel = t("message.forkFromHere");
|
||||
const completedAt = message.completedAt;
|
||||
const completedAtLabel =
|
||||
message.role === "assistant" && !message.isStreaming
|
||||
? formatMessageEndTime(completedAt)
|
||||
: "";
|
||||
const assistantTimestamp =
|
||||
typeof completedAt === "number" && Number.isFinite(completedAt)
|
||||
? completedAt
|
||||
: message.createdAt;
|
||||
const assistantTimestampLabel =
|
||||
message.role === "assistant" && !message.isStreaming && !isTurnStreaming
|
||||
? formatMessageEndTime(assistantTimestamp)
|
||||
: "";
|
||||
const showCompletedAt =
|
||||
completedAtLabel.length > 0
|
||||
&& (!empty || hasReasoning || media.length > 0);
|
||||
const showAssistantTimestamp =
|
||||
assistantTimestampLabel.length > 0
|
||||
&& (!empty || hasReasoning || media.length > 0);
|
||||
const assistantTimestampTitle = showAssistantTimestamp ? fmtDateTime(assistantTimestamp) : "";
|
||||
const showAutomationTrigger = showAssistantTimestamp && automationSourceLabel.length > 0;
|
||||
const fallbackSources = message.responseSources?.filter((source) => source.fallback === true) ?? [];
|
||||
const showAssistantFooterRow =
|
||||
showCopyButton || showForkButton || showAssistantTimestamp || fallbackSources.length > 0;
|
||||
const hasAssistantFooterContent =
|
||||
message.role === "assistant"
|
||||
&& (!empty || hasReasoning || media.length > 0);
|
||||
const showAssistantFooterSlot =
|
||||
hasAssistantFooterContent
|
||||
&& (showAssistantFooterRow || ((message.isStreaming || isTurnStreaming) && isThreadTail));
|
||||
return (
|
||||
<div className="w-full text-[15px]" style={{ lineHeight: "var(--cjk-line-height)" }}>
|
||||
<div
|
||||
data-assistant-message
|
||||
className="group/assistant relative w-full text-[15px]"
|
||||
style={{ lineHeight: "var(--cjk-line-height)" }}
|
||||
>
|
||||
{contextMenu}
|
||||
{hasReasoning ? (
|
||||
<ReasoningBubble
|
||||
text={reasoning}
|
||||
@@ -533,68 +590,6 @@ export function MessageBubble({
|
||||
{media.length > 0 ? <MessageMedia media={media} align="left" /> : null}
|
||||
</>
|
||||
)}
|
||||
{showAssistantFooterSlot ? (
|
||||
<TooltipProvider>
|
||||
<div
|
||||
data-assistant-footer
|
||||
data-state={showAssistantFooterRow ? "visible" : "reserved"}
|
||||
aria-hidden={showAssistantFooterRow ? undefined : true}
|
||||
className={cn(
|
||||
"message-actions mt-2 flex min-h-8 flex-wrap items-center gap-x-2 gap-y-1 text-muted-foreground",
|
||||
"transition-opacity duration-300 ease-out motion-reduce:transition-none",
|
||||
showAssistantFooterRow
|
||||
? "opacity-100"
|
||||
: "pointer-events-none opacity-0",
|
||||
)}
|
||||
>
|
||||
{showCopyButton ? (
|
||||
<MessageCopyButton content={assistantContent} />
|
||||
) : null}
|
||||
{showForkButton ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onForkFromHere}
|
||||
aria-label={forkLabel}
|
||||
className={cn(
|
||||
"touch-target inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
|
||||
"transition-colors hover:bg-muted/55 hover:text-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
)}
|
||||
>
|
||||
<ForkArrowIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">{forkLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{showAssistantTimestamp ? (
|
||||
<MessageTimestamp
|
||||
{...(showCompletedAt ? { "data-assistant-completed-at": true } : {})}
|
||||
data-message-timestamp
|
||||
timestamp={assistantTimestamp}
|
||||
tooltipLabel={assistantTimestampTitle}
|
||||
>
|
||||
{assistantTimestampLabel}
|
||||
</MessageTimestamp>
|
||||
) : null}
|
||||
{fallbackSources.length > 0 ? (
|
||||
<div className="flex min-w-0 max-w-full flex-wrap items-center gap-x-2 gap-y-1">
|
||||
{fallbackSources.map((source) => (
|
||||
<ResponseSourceBadge key={JSON.stringify(source)} source={source} />
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{showAutomationTrigger ? (
|
||||
<AutomationTriggerMeta
|
||||
label={automationTriggeredLabel}
|
||||
sourceLabel={automationSourceLabel}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -616,26 +611,6 @@ function UserQuotedContext({ text, label }: { text: string; label: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function AutomationTriggerMeta({ label, sourceLabel }: { label: string; sourceLabel: string }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
data-automation-trigger
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
"shrink-0 cursor-help text-[11px] leading-none text-muted-foreground/70 tabular-nums",
|
||||
"focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">{sourceLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function mergeMcpMentionPresets(
|
||||
presets: McpPresetInfo[],
|
||||
attachments: UIMcpPresetAttachment[] | undefined,
|
||||
|
||||
@@ -2,14 +2,42 @@ import { useState } from "react";
|
||||
import { ArrowRightLeft, Hexagon } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { providerBrand } from "@/lib/provider-brand";
|
||||
import type { ResponseSource } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function FallbackResponseSources({
|
||||
sources,
|
||||
className,
|
||||
badgeClassName,
|
||||
}: {
|
||||
sources?: ResponseSource[];
|
||||
className?: string;
|
||||
badgeClassName?: string;
|
||||
}) {
|
||||
const fallbacks = sources?.filter((source) => source.fallback === true) ?? [];
|
||||
if (fallbacks.length === 0) return null;
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className={cn("flex min-w-0 max-w-full flex-wrap items-center gap-x-2 gap-y-1", className)}>
|
||||
{fallbacks.map((source) => (
|
||||
<ResponseSourceBadge key={JSON.stringify(source)} source={source} className={badgeClassName} />
|
||||
))}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
/** A persisted invocation identity; deliberately independent of live settings. */
|
||||
export function ResponseSourceBadge({ source }: { source: ResponseSource }) {
|
||||
export function ResponseSourceBadge({
|
||||
source,
|
||||
className,
|
||||
}: {
|
||||
source: ResponseSource;
|
||||
className?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const description = t("message.fallbackResponse", { preset: source.preset });
|
||||
@@ -25,6 +53,7 @@ export function ResponseSourceBadge({ source }: { source: ResponseSource }) {
|
||||
"touch-target inline-flex min-h-8 min-w-0 max-w-full items-center gap-1.5 rounded-control px-1.5 text-xs",
|
||||
"transition-colors hover:bg-muted/55 hover:text-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
className,
|
||||
)}>
|
||||
<ArrowRightLeft aria-hidden className="size-3 shrink-0 opacity-70" />
|
||||
<span aria-hidden className={cn(
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
@@ -68,7 +67,6 @@ import type {
|
||||
UIMessage,
|
||||
} from "@/lib/types";
|
||||
|
||||
const ACTIVITY_SCROLL_NEAR_BOTTOM_PX = 24;
|
||||
const EMPTY_CLI_APPS: CliAppInfo[] = [];
|
||||
const EMPTY_MCP_PRESETS: McpPresetInfo[] = [];
|
||||
|
||||
@@ -164,6 +162,13 @@ interface AgentActivityClusterProps {
|
||||
traceDetailScope?: string | null;
|
||||
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
/** Optional controlled expansion state for a completed inline activity block. */
|
||||
expanded?: boolean;
|
||||
onExpandedChange?: (expanded: boolean) => void;
|
||||
/** Render only the controlled details; another control owns the disclosure label. */
|
||||
hideHeader?: boolean;
|
||||
/** Stable id used by an external disclosure control. */
|
||||
detailsId?: string;
|
||||
}
|
||||
|
||||
export function AgentActivityCluster(props: AgentActivityClusterProps) {
|
||||
@@ -173,7 +178,7 @@ export function AgentActivityCluster(props: AgentActivityClusterProps) {
|
||||
() => summarizeFileEditsByMessage(messages, props.isTurnStreaming),
|
||||
[messages, props.isTurnStreaming],
|
||||
);
|
||||
if (displayMode === "summary" || !editsByMessage.size) {
|
||||
if (props.expanded !== undefined || displayMode === "summary" || !editsByMessage.size) {
|
||||
return <FoldedAgentActivity {...props} />;
|
||||
}
|
||||
|
||||
@@ -237,6 +242,10 @@ function FoldedAgentActivity({
|
||||
traceDetailScope = null,
|
||||
onLoadTraceDetails,
|
||||
onOpenFilePreview,
|
||||
expanded,
|
||||
onExpandedChange,
|
||||
hideHeader = false,
|
||||
detailsId,
|
||||
}: AgentActivityClusterProps) {
|
||||
const { t } = useTranslation();
|
||||
const fileEditDisplayMode = useFileEditDisplayMode();
|
||||
@@ -275,17 +284,14 @@ function FoldedAgentActivity({
|
||||
const [completionHoldOpen, setCompletionHoldOpen] = useState(false);
|
||||
const [failedTraceDetailKey, setFailedTraceDetailKey] = useState<string | null>(null);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [activityScrollFade, setActivityScrollFade] = useState({ top: false, bottom: false });
|
||||
const activityScrollRef = useRef<HTMLDivElement>(null);
|
||||
const activityContentRef = useRef<HTMLDivElement>(null);
|
||||
const autoFollowActivityRef = useRef(true);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const wasTurnStreamingRef = useRef(isTurnStreaming);
|
||||
const wasTurnStreaming = wasTurnStreamingRef.current;
|
||||
/** Live work stays open; completed work briefly shows the done state, then tucks away. */
|
||||
const outerExpanded = userToggledOuter
|
||||
? outerOpenLocal
|
||||
: isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming);
|
||||
const outerExpanded = expanded ?? (
|
||||
userToggledOuter
|
||||
? outerOpenLocal
|
||||
: isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming)
|
||||
);
|
||||
const deferredTraceRefs = useMemo(
|
||||
() => Array.from(new Set(
|
||||
messages
|
||||
@@ -319,6 +325,7 @@ function FoldedAgentActivity({
|
||||
startedAtMs,
|
||||
);
|
||||
const activityDuration = formatActivityDuration(durationMs);
|
||||
const isCompletedDisclosure = !isTurnStreaming && expanded !== undefined;
|
||||
const retryError = retryStatus?.error_kind === "connection"
|
||||
? t("message.retryConnection", { defaultValue: "Connection failed" })
|
||||
: retryStatus?.error_kind === "timeout"
|
||||
@@ -358,76 +365,16 @@ function FoldedAgentActivity({
|
||||
defaultValue: "Worked for {{duration}}",
|
||||
});
|
||||
|
||||
const cancelActivityScrollFrame = useCallback(() => {
|
||||
if (scrollFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(scrollFrameRef.current);
|
||||
scrollFrameRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const syncActivityScrollFade = useCallback(() => {
|
||||
const el = activityScrollRef.current;
|
||||
if (!el) return;
|
||||
const maxScrollTop = Math.max(0, el.scrollHeight - el.clientHeight);
|
||||
const scrollTop = Math.min(maxScrollTop, Math.max(0, el.scrollTop));
|
||||
const next = {
|
||||
top: scrollTop > 1,
|
||||
bottom: maxScrollTop - scrollTop > 1,
|
||||
};
|
||||
setActivityScrollFade((current) =>
|
||||
current.top === next.top && current.bottom === next.bottom ? current : next,
|
||||
);
|
||||
}, []);
|
||||
|
||||
const scrollActivityToBottom = useCallback(() => {
|
||||
const el = activityScrollRef.current;
|
||||
if (!el) return;
|
||||
el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight);
|
||||
syncActivityScrollFade();
|
||||
}, [syncActivityScrollFade]);
|
||||
|
||||
const scheduleActivityScrollToBottom = useCallback(() => {
|
||||
cancelActivityScrollFrame();
|
||||
scrollFrameRef.current = window.requestAnimationFrame(() => {
|
||||
scrollFrameRef.current = null;
|
||||
scrollActivityToBottom();
|
||||
});
|
||||
}, [cancelActivityScrollFrame, scrollActivityToBottom]);
|
||||
|
||||
const toggleOuter = () => {
|
||||
const nextOpen = userToggledOuter ? !outerOpenLocal : !outerExpanded;
|
||||
if (nextOpen) {
|
||||
autoFollowActivityRef.current = true;
|
||||
if (expanded !== undefined) {
|
||||
onExpandedChange?.(!expanded);
|
||||
return;
|
||||
}
|
||||
const nextOpen = userToggledOuter ? !outerOpenLocal : !outerExpanded;
|
||||
setUserToggledOuter(true);
|
||||
setOuterOpenLocal(nextOpen);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!outerExpanded || !autoFollowActivityRef.current) return;
|
||||
scheduleActivityScrollToBottom();
|
||||
}, [outerExpanded, activityMessages, isTurnStreaming, scheduleActivityScrollToBottom]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!outerExpanded) {
|
||||
autoFollowActivityRef.current = true;
|
||||
return;
|
||||
}
|
||||
const target = activityContentRef.current;
|
||||
if (!target || typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (autoFollowActivityRef.current) {
|
||||
scheduleActivityScrollToBottom();
|
||||
} else {
|
||||
syncActivityScrollFade();
|
||||
}
|
||||
});
|
||||
observer.observe(target);
|
||||
return () => observer.disconnect();
|
||||
}, [outerExpanded, scheduleActivityScrollToBottom, syncActivityScrollFade]);
|
||||
|
||||
useEffect(() => cancelActivityScrollFrame, [cancelActivityScrollFrame]);
|
||||
|
||||
useEffect(() => {
|
||||
if (outerExpanded && deferredTraceRefs.length > 0) {
|
||||
void requestTraceDetails(deferredTraceRefs);
|
||||
@@ -454,17 +401,9 @@ function FoldedAgentActivity({
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [isTurnStreaming, userToggledOuter]);
|
||||
|
||||
const onActivityScroll = useCallback(() => {
|
||||
const el = activityScrollRef.current;
|
||||
if (!el) return;
|
||||
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||
autoFollowActivityRef.current = distance < ACTIVITY_SCROLL_NEAR_BOTTOM_PX;
|
||||
syncActivityScrollFade();
|
||||
}, [syncActivityScrollFade]);
|
||||
|
||||
if (!hasVisibleActivity && !isTurnStreaming) return null;
|
||||
|
||||
if (hasOnlyFileActivity) {
|
||||
if (hasOnlyFileActivity && expanded === undefined) {
|
||||
return (
|
||||
<div className={cn("w-full", hasBodyBelow && "mb-2")}>
|
||||
<FileEditGroup
|
||||
@@ -477,18 +416,17 @@ function FoldedAgentActivity({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("w-full", hasBodyBelow && "mb-2")}>
|
||||
<div className={cn("w-full", hasBodyBelow && expanded !== false && "mb-2")}>
|
||||
<ThinkingReasoningShell
|
||||
active={isTurnStreaming}
|
||||
expanded={outerExpanded}
|
||||
contextual={isCompletedDisclosure}
|
||||
showHeader={!hideHeader || outerExpanded}
|
||||
collapseLabel={t("message.collapseActivity")}
|
||||
contentId={detailsId}
|
||||
label={activityLabel}
|
||||
viewportRef={activityScrollRef}
|
||||
contentRef={activityContentRef}
|
||||
fadeTop={activityScrollFade.top}
|
||||
fadeBottom={activityScrollFade.bottom}
|
||||
hasDetails={hasVisibleActivity}
|
||||
onToggle={toggleOuter}
|
||||
onScroll={onActivityScroll}
|
||||
>
|
||||
{traceDetailLoadFailed ? (
|
||||
<div role="alert" className="flex items-center gap-2 py-1 text-[12px] text-destructive">
|
||||
@@ -550,7 +488,14 @@ function activityDurationMs(
|
||||
return Math.max(0, last - first);
|
||||
}
|
||||
|
||||
function formatActivityDuration(ms: number): string {
|
||||
export function completedActivityDurationMs(
|
||||
messages: UIMessage[],
|
||||
completedLatencyMs?: number,
|
||||
): number {
|
||||
return activityDurationMs(messages, false, 0, completedLatencyMs);
|
||||
}
|
||||
|
||||
export function formatActivityDuration(ms: number): string {
|
||||
const seconds = ms > 0 && ms < 1000 ? 1 : Math.max(0, Math.round(ms / 1000));
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { MoreHorizontal } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
|
||||
import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
|
||||
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
|
||||
import {
|
||||
AgentActivityCluster,
|
||||
completedActivityDurationMs,
|
||||
formatActivityDuration,
|
||||
} from "@/components/thread/AgentActivityCluster";
|
||||
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
|
||||
|
||||
interface ThreadMessagesProps {
|
||||
@@ -25,6 +33,7 @@ interface ThreadMessagesProps {
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
onForkFromMessage?: (beforeUserIndex: number) => void;
|
||||
onQuoteSelection?: (text: string) => void;
|
||||
onActivityToggle?: () => void;
|
||||
}
|
||||
|
||||
export type DisplayUnit = TurnUnit;
|
||||
@@ -77,6 +86,7 @@ export function ThreadMessages({
|
||||
onOpenFilePreview,
|
||||
onForkFromMessage,
|
||||
onQuoteSelection,
|
||||
onActivityToggle,
|
||||
}: ThreadMessagesProps) {
|
||||
const { t } = useTranslation();
|
||||
const messageListRef = useRef<HTMLDivElement>(null);
|
||||
@@ -109,6 +119,44 @@ export function ThreadMessages({
|
||||
? activeTurnStartIndex(units, activeTurnId)
|
||||
: units.length;
|
||||
const unitKeys = useMemo(() => unitKeysForDisplay(units), [units]);
|
||||
const messageBlocks = useMemo(
|
||||
() => completedMessageBlocks(
|
||||
units,
|
||||
unitKeys,
|
||||
isStreaming,
|
||||
activeTurnId,
|
||||
currentTurnStartIndex,
|
||||
),
|
||||
[activeTurnId, currentTurnStartIndex, isStreaming, unitKeys, units],
|
||||
);
|
||||
const [expandedActivityKeys, setExpandedActivityKeys] = useState<Set<string>>(() => new Set());
|
||||
const [activeContextBlockKey, setActiveContextBlockKey] = useState<string | null>(null);
|
||||
const [openContextBlockKey, setOpenContextBlockKey] = useState<string | null>(null);
|
||||
const pointedContextBlockRef = useRef<string | null>(null);
|
||||
const setActivityExpanded = useCallback((key: string, expanded: boolean) => {
|
||||
onActivityToggle?.();
|
||||
setExpandedActivityKeys((current) => {
|
||||
if (current.has(key) === expanded) return current;
|
||||
const next = new Set(current);
|
||||
if (expanded) next.add(key);
|
||||
else next.delete(key);
|
||||
return next;
|
||||
});
|
||||
}, [onActivityToggle]);
|
||||
const setContextBlockActive = useCallback((key: string | null) => {
|
||||
setActiveContextBlockKey((current) => current === key ? current : key);
|
||||
setOpenContextBlockKey((current) => current !== null && current !== key ? null : current);
|
||||
}, []);
|
||||
const setContextBlockPointed = useCallback((key: string | null) => {
|
||||
pointedContextBlockRef.current = key;
|
||||
setContextBlockActive(key);
|
||||
}, [setContextBlockActive]);
|
||||
const setContextBlockFocused = useCallback((key: string | null) => {
|
||||
setContextBlockActive(key ?? pointedContextBlockRef.current);
|
||||
}, [setContextBlockActive]);
|
||||
const setContextBlockMenuOpen = useCallback((key: string, open: boolean) => {
|
||||
setOpenContextBlockKey((current) => open ? key : current === key ? null : current);
|
||||
}, []);
|
||||
let nextUserIndex = hiddenUserMessageCount;
|
||||
|
||||
return (
|
||||
@@ -118,16 +166,28 @@ export function ThreadMessages({
|
||||
onQuoteSelection={onQuoteSelection}
|
||||
/>
|
||||
{units.map((unit, index) => {
|
||||
const prev = units[index - 1];
|
||||
const marginTop =
|
||||
index > 0
|
||||
? marginAfterPrevUnit(prev)
|
||||
: "";
|
||||
const next = units[index + 1];
|
||||
const hasBodyBelow =
|
||||
unit.type === "activity"
|
||||
&& next?.type === "message"
|
||||
&& next.message.role === "assistant";
|
||||
const contextBlockKey = messageBlocks.blockKeys[index]
|
||||
?? (unit.type === "message" && unit.message.role === "user"
|
||||
? `message-block-${unitKeys[index]}`
|
||||
: undefined);
|
||||
const showBlockContext = messageBlocks.blockIndices.has(index);
|
||||
const blockActivity = messageBlocks.activityByBlock.get(index);
|
||||
const suppressActivity = messageBlocks.suppressedActivityIndices.has(index);
|
||||
const previousVisibleIndex = previousVisibleUnitIndex(
|
||||
index,
|
||||
messageBlocks.suppressedActivityIndices,
|
||||
);
|
||||
const marginTop = suppressActivity || previousVisibleIndex < 0
|
||||
? ""
|
||||
: marginAfterPrevUnit(units[previousVisibleIndex]);
|
||||
const blockActivityExpanded = showBlockContext
|
||||
&& contextBlockKey !== undefined
|
||||
&& expandedActivityKeys.has(contextBlockKey);
|
||||
const deferOffscreenRender =
|
||||
index < units.length - 1
|
||||
&& (
|
||||
@@ -150,7 +210,6 @@ export function ThreadMessages({
|
||||
? unit.message.turnId === activeTurnId
|
||||
: index > currentTurnStartIndex
|
||||
);
|
||||
const isThreadTail = index === units.length - 1;
|
||||
if (
|
||||
unit.type === "message"
|
||||
&& unit.message.role === "user"
|
||||
@@ -165,9 +224,18 @@ export function ThreadMessages({
|
||||
marginTop={marginTop}
|
||||
userPromptId={userPromptId}
|
||||
hasBodyBelow={hasBodyBelow}
|
||||
suppressActivity={suppressActivity}
|
||||
showBlockContext={showBlockContext}
|
||||
blockActivity={blockActivity}
|
||||
blockActivityExpanded={blockActivityExpanded}
|
||||
contextBlockKey={contextBlockKey}
|
||||
contextBlockActive={
|
||||
contextBlockKey !== undefined
|
||||
&& contextBlockKey === (openContextBlockKey ?? activeContextBlockKey)
|
||||
}
|
||||
contextBlockMenuOpen={contextBlockKey === openContextBlockKey}
|
||||
deferOffscreenRender={deferOffscreenRender}
|
||||
isTurnStreaming={unitTurnStreaming}
|
||||
isThreadTail={isThreadTail}
|
||||
retryStatus={
|
||||
unit.type === "activity" && liveActivityClusterIndices.has(index)
|
||||
? retryStatus
|
||||
@@ -184,11 +252,15 @@ export function ThreadMessages({
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
onForkFromMessage={onForkFromMessage}
|
||||
onActivityExpandedChange={setActivityExpanded}
|
||||
onContextBlockActiveChange={setContextBlockPointed}
|
||||
onContextBlockFocusChange={setContextBlockFocused}
|
||||
onContextBlockMenuOpenChange={setContextBlockMenuOpen}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{pendingActivity ? (
|
||||
<div className={units.length > 0 ? "mt-5" : undefined}>
|
||||
<div className={cn("thread-message-row", units.length > 0 && "mt-5")}>
|
||||
<AgentActivityCluster
|
||||
messages={[]}
|
||||
isTurnStreaming
|
||||
@@ -255,9 +327,15 @@ interface ThreadDisplayUnitProps {
|
||||
marginTop: string;
|
||||
userPromptId?: string;
|
||||
hasBodyBelow: boolean;
|
||||
suppressActivity: boolean;
|
||||
showBlockContext: boolean;
|
||||
blockActivity?: Extract<DisplayUnit, { type: "activity" }>;
|
||||
blockActivityExpanded: boolean;
|
||||
contextBlockKey?: string;
|
||||
contextBlockActive: boolean;
|
||||
contextBlockMenuOpen: boolean;
|
||||
deferOffscreenRender: boolean;
|
||||
isTurnStreaming: boolean;
|
||||
isThreadTail: boolean;
|
||||
retryStatus: RetryStatus | null;
|
||||
forkIndex?: number;
|
||||
showForkBoundary: boolean;
|
||||
@@ -270,6 +348,133 @@ interface ThreadDisplayUnitProps {
|
||||
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
onForkFromMessage?: (beforeUserIndex: number) => void;
|
||||
onActivityExpandedChange: (key: string, expanded: boolean) => void;
|
||||
onContextBlockActiveChange: (key: string | null) => void;
|
||||
onContextBlockFocusChange: (key: string | null) => void;
|
||||
onContextBlockMenuOpenChange: (key: string, open: boolean) => void;
|
||||
}
|
||||
|
||||
interface MessageBlockMenuProps {
|
||||
message: UIMessage;
|
||||
isTurnStreaming: boolean;
|
||||
contextBlockKey: string;
|
||||
contextActive: boolean;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onContextActiveChange: (key: string | null) => void;
|
||||
onForkFromHere?: () => void;
|
||||
activity?: {
|
||||
label: string;
|
||||
expanded: boolean;
|
||||
controls: string;
|
||||
onToggle: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
function MessageBlockMenu({
|
||||
message,
|
||||
isTurnStreaming,
|
||||
contextBlockKey,
|
||||
contextActive,
|
||||
open,
|
||||
onOpenChange,
|
||||
onContextActiveChange,
|
||||
onForkFromHere,
|
||||
activity,
|
||||
}: MessageBlockMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [triggerHeight, setTriggerHeight] = useState(28);
|
||||
useLayoutEffect(() => {
|
||||
const trigger = triggerRef.current;
|
||||
if (!open || !trigger) return;
|
||||
const measure = () => setTriggerHeight(trigger.getBoundingClientRect().height || 28);
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(trigger);
|
||||
return () => observer.disconnect();
|
||||
}, [open]);
|
||||
const contextActiveRef = useRef(contextActive);
|
||||
contextActiveRef.current = contextActive;
|
||||
const label = t("message.actions");
|
||||
return (
|
||||
<Popover open={open} onOpenChange={onOpenChange}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
data-message-block-menu-trigger
|
||||
aria-label={label}
|
||||
className={cn(
|
||||
"message-block-menu-trigger group touch-target absolute -start-[var(--message-block-trigger-offset)] top-0 z-20",
|
||||
"inline-flex h-[var(--message-block-control-size)] w-[var(--message-block-control-size)] items-center justify-center text-muted-foreground/70",
|
||||
"transition-[color,opacity] hover:text-foreground focus-visible:outline-none",
|
||||
"motion-reduce:transform-none motion-reduce:transition-none",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
data-message-block-menu-highlight
|
||||
className={cn(
|
||||
"inline-flex h-4 w-7 items-center justify-center rounded-full",
|
||||
"transition-[background-color,box-shadow,scale]",
|
||||
"group-hover:bg-muted/70 group-active:scale-[0.96]",
|
||||
"group-focus-visible:ring-2 group-focus-visible:ring-ring",
|
||||
"motion-reduce:transform-none motion-reduce:transition-none",
|
||||
)}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" strokeWidth={1.75} aria-hidden />
|
||||
</span>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
ref={contentRef}
|
||||
data-message-block-menu
|
||||
data-message-context-menu-block={contextBlockKey}
|
||||
side="bottom"
|
||||
align="end"
|
||||
sideOffset={-triggerHeight}
|
||||
collisionPadding={12}
|
||||
tabIndex={-1}
|
||||
aria-label={label}
|
||||
onKeyDownCapture={(event) => {
|
||||
if (event.key !== "Escape"
|
||||
|| !(event.target instanceof Node)
|
||||
|| !event.currentTarget.contains(event.target)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onOpenChange(false);
|
||||
}}
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
contentRef.current?.focus({ preventScroll: true });
|
||||
}}
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (!contextActiveRef.current || activity?.expanded) event.preventDefault();
|
||||
}}
|
||||
onPointerEnter={(event) => {
|
||||
if (event.pointerType === "touch") return;
|
||||
onContextActiveChange(contextBlockKey);
|
||||
}}
|
||||
onPointerLeave={(event) => {
|
||||
if (event.pointerType === "touch") return;
|
||||
onContextActiveChange(contextBlockKeyForTarget(event.relatedTarget) ?? null);
|
||||
}}
|
||||
className={cn(
|
||||
"w-max max-w-64 overflow-y-auto outline-none",
|
||||
"shadow-[0_2px_10px_rgba(0,0,0,0.08)] dark:shadow-[0_2px_10px_rgba(0,0,0,0.24)]",
|
||||
)}
|
||||
>
|
||||
<MessageBlockMenuActions
|
||||
message={message}
|
||||
isTurnStreaming={isTurnStreaming}
|
||||
onForkFromHere={onForkFromHere}
|
||||
activity={activity}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
||||
@@ -278,9 +483,15 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
||||
marginTop,
|
||||
userPromptId,
|
||||
hasBodyBelow,
|
||||
suppressActivity,
|
||||
showBlockContext,
|
||||
blockActivity,
|
||||
blockActivityExpanded,
|
||||
contextBlockKey,
|
||||
contextBlockActive,
|
||||
contextBlockMenuOpen,
|
||||
deferOffscreenRender,
|
||||
isTurnStreaming,
|
||||
isThreadTail,
|
||||
retryStatus,
|
||||
forkIndex,
|
||||
showForkBoundary,
|
||||
@@ -293,8 +504,14 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
||||
onLoadTraceDetails,
|
||||
onOpenFilePreview,
|
||||
onForkFromMessage,
|
||||
onActivityExpandedChange,
|
||||
onContextBlockActiveChange,
|
||||
onContextBlockFocusChange,
|
||||
onContextBlockMenuOpenChange,
|
||||
}: ThreadDisplayUnitProps) {
|
||||
const { t } = useTranslation();
|
||||
const elementRef = useRef<HTMLDivElement>(null);
|
||||
const activityDetailsId = useId();
|
||||
const heightRef = useRef(0);
|
||||
const [nearViewport, setNearViewport] = useState(true);
|
||||
const [interacted, setInteracted] = useState(false);
|
||||
@@ -317,43 +534,151 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
||||
const onForkFromHere = useCallback(() => {
|
||||
if (forkIndex !== undefined) onForkFromMessage?.(forkIndex);
|
||||
}, [forkIndex, onForkFromMessage]);
|
||||
const onBlockActivityExpandedChange = useCallback((expanded: boolean) => {
|
||||
if (contextBlockKey !== undefined) {
|
||||
onActivityExpandedChange(contextBlockKey, expanded);
|
||||
window.setTimeout(() => {
|
||||
const focusTarget = elementRef.current?.querySelector<HTMLElement>(
|
||||
expanded
|
||||
? "[data-contextual-activity-collapse]"
|
||||
: "[data-message-block-menu-trigger]",
|
||||
);
|
||||
focusTarget?.focus({ preventScroll: true });
|
||||
}, 0);
|
||||
}
|
||||
}, [contextBlockKey, onActivityExpandedChange]);
|
||||
const activityDurationMs = blockActivity
|
||||
? completedActivityDurationMs(blockActivity.messages, blockActivity.turnLatencyMs)
|
||||
: 0;
|
||||
const activityLabel = blockActivity
|
||||
? activityDurationMs <= 0
|
||||
? t("message.activityWorked")
|
||||
: t("message.activityWorkedFor", {
|
||||
duration: formatActivityDuration(activityDurationMs),
|
||||
})
|
||||
: undefined;
|
||||
const onActivityMenuToggle = useCallback(() => {
|
||||
onBlockActivityExpandedChange(!blockActivityExpanded);
|
||||
if (contextBlockKey !== undefined) {
|
||||
onContextBlockMenuOpenChange(contextBlockKey, false);
|
||||
}
|
||||
}, [
|
||||
blockActivityExpanded,
|
||||
contextBlockKey,
|
||||
onBlockActivityExpandedChange,
|
||||
onContextBlockMenuOpenChange,
|
||||
]);
|
||||
const blockMenu = unit.type === "message" && contextBlockKey !== undefined ? (
|
||||
<MessageBlockMenu
|
||||
message={unit.message}
|
||||
isTurnStreaming={isTurnStreaming}
|
||||
contextBlockKey={contextBlockKey}
|
||||
contextActive={contextBlockActive}
|
||||
open={contextBlockMenuOpen}
|
||||
onOpenChange={(open) => onContextBlockMenuOpenChange(contextBlockKey, open)}
|
||||
onContextActiveChange={onContextBlockActiveChange}
|
||||
onForkFromHere={forkIndex !== undefined ? onForkFromHere : undefined}
|
||||
activity={activityLabel ? {
|
||||
label: activityLabel,
|
||||
expanded: blockActivityExpanded,
|
||||
controls: activityDetailsId,
|
||||
onToggle: onActivityMenuToggle,
|
||||
} : undefined}
|
||||
/>
|
||||
) : null;
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={elementRef}
|
||||
className={marginTop}
|
||||
className={cn(
|
||||
"thread-message-row",
|
||||
marginTop,
|
||||
contextBlockKey !== undefined && "message-context-hit-area relative",
|
||||
)}
|
||||
style={retainContent ? undefined : { height: heightRef.current }}
|
||||
onPointerDownCapture={() => setInteracted(true)}
|
||||
onFocusCapture={() => setInteracted(true)}
|
||||
onPointerDownCapture={() => {
|
||||
setInteracted(true);
|
||||
onContextBlockActiveChange(contextBlockKey ?? null);
|
||||
}}
|
||||
data-thread-display-unit={unitKey}
|
||||
data-user-prompt-id={userPromptId}
|
||||
data-message-context-block={contextBlockKey}
|
||||
data-context-block-active={contextBlockActive || undefined}
|
||||
data-message-context-menu-open={contextBlockMenuOpen || undefined}
|
||||
onPointerEnter={(event) => {
|
||||
if (event.pointerType === "touch") return;
|
||||
onContextBlockActiveChange(contextBlockKey ?? null);
|
||||
}}
|
||||
onPointerLeave={(event) => {
|
||||
if (event.pointerType === "touch") return;
|
||||
onContextBlockActiveChange(contextBlockKeyForTarget(event.relatedTarget) ?? null);
|
||||
}}
|
||||
onFocusCapture={() => {
|
||||
setInteracted(true);
|
||||
onContextBlockFocusChange(contextBlockKey ?? null);
|
||||
}}
|
||||
onBlurCapture={(event) => {
|
||||
onContextBlockFocusChange(contextBlockKeyForTarget(event.relatedTarget) ?? null);
|
||||
}}
|
||||
>
|
||||
{retainContent ? unit.type === "activity" ? (
|
||||
<AgentActivityCluster
|
||||
messages={unit.messages}
|
||||
isTurnStreaming={isTurnStreaming}
|
||||
retryStatus={retryStatus}
|
||||
hasBodyBelow={hasBodyBelow}
|
||||
turnLatencyMs={unit.turnLatencyMs}
|
||||
startedAtMs={unit.startedAtMs}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
traceDetailScope={traceDetailScope}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
/>
|
||||
suppressActivity ? null : (
|
||||
<AgentActivityCluster
|
||||
messages={unit.messages}
|
||||
isTurnStreaming={isTurnStreaming}
|
||||
retryStatus={retryStatus}
|
||||
hasBodyBelow={hasBodyBelow}
|
||||
turnLatencyMs={unit.turnLatencyMs}
|
||||
startedAtMs={unit.startedAtMs}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
traceDetailScope={traceDetailScope}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<MessageBubble
|
||||
message={unit.message}
|
||||
isTurnStreaming={isTurnStreaming}
|
||||
isThreadTail={isThreadTail}
|
||||
temporary={temporary}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
slashCommands={slashCommands}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
onForkFromHere={forkIndex !== undefined ? onForkFromHere : undefined}
|
||||
/>
|
||||
<div className={unit.message.role === "assistant" ? "relative" : undefined}>
|
||||
{unit.message.role === "assistant" ? blockMenu : null}
|
||||
{showBlockContext && blockActivity ? (
|
||||
<div className={blockActivityExpanded ? "mb-2" : undefined}>
|
||||
<AgentActivityCluster
|
||||
messages={blockActivity.messages}
|
||||
isTurnStreaming={false}
|
||||
retryStatus={null}
|
||||
hasBodyBelow={false}
|
||||
expanded={blockActivityExpanded}
|
||||
onExpandedChange={onBlockActivityExpandedChange}
|
||||
hideHeader
|
||||
detailsId={activityDetailsId}
|
||||
turnLatencyMs={blockActivity.turnLatencyMs}
|
||||
startedAtMs={blockActivity.startedAtMs}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
traceDetailScope={traceDetailScope}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<MessageBubble
|
||||
message={unit.message}
|
||||
temporary={temporary}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
slashCommands={slashCommands}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
contextMenu={unit.message.role === "user" ? blockMenu : undefined}
|
||||
/>
|
||||
{unit.message.role === "assistant"
|
||||
&& unit.message.kind !== "compaction"
|
||||
&& contextBlockKey === undefined ? (
|
||||
<FallbackResponseSources
|
||||
sources={unit.message.responseSources}
|
||||
className="relative mt-0.5 text-muted-foreground"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{showForkBoundary ? <ForkBoundaryDivider label={forkBoundaryLabel} /> : null}
|
||||
@@ -370,9 +695,15 @@ function threadDisplayUnitPropsEqual(
|
||||
&& previous.marginTop === next.marginTop
|
||||
&& previous.userPromptId === next.userPromptId
|
||||
&& previous.hasBodyBelow === next.hasBodyBelow
|
||||
&& previous.suppressActivity === next.suppressActivity
|
||||
&& previous.showBlockContext === next.showBlockContext
|
||||
&& previous.blockActivity === next.blockActivity
|
||||
&& previous.blockActivityExpanded === next.blockActivityExpanded
|
||||
&& previous.contextBlockKey === next.contextBlockKey
|
||||
&& previous.contextBlockActive === next.contextBlockActive
|
||||
&& previous.contextBlockMenuOpen === next.contextBlockMenuOpen
|
||||
&& previous.deferOffscreenRender === next.deferOffscreenRender
|
||||
&& previous.isTurnStreaming === next.isTurnStreaming
|
||||
&& previous.isThreadTail === next.isThreadTail
|
||||
&& previous.retryStatus === next.retryStatus
|
||||
&& previous.forkIndex === next.forkIndex
|
||||
&& previous.showForkBoundary === next.showForkBoundary
|
||||
@@ -385,9 +716,21 @@ function threadDisplayUnitPropsEqual(
|
||||
&& previous.onLoadTraceDetails === next.onLoadTraceDetails
|
||||
&& previous.onOpenFilePreview === next.onOpenFilePreview
|
||||
&& previous.onForkFromMessage === next.onForkFromMessage
|
||||
&& previous.onActivityExpandedChange === next.onActivityExpandedChange
|
||||
&& previous.onContextBlockActiveChange === next.onContextBlockActiveChange
|
||||
&& previous.onContextBlockFocusChange === next.onContextBlockFocusChange
|
||||
&& previous.onContextBlockMenuOpenChange === next.onContextBlockMenuOpenChange
|
||||
);
|
||||
}
|
||||
|
||||
function contextBlockKeyForTarget(target: EventTarget | null): string | undefined {
|
||||
if (!(target instanceof Element)) return undefined;
|
||||
const owner = target.closest<HTMLElement>(
|
||||
"[data-message-context-block], [data-message-context-menu-block]",
|
||||
);
|
||||
return owner?.dataset.messageContextBlock ?? owner?.dataset.messageContextMenuBlock;
|
||||
}
|
||||
|
||||
function activeTurnStartIndex(units: DisplayUnit[], activeTurnId: string | null): number {
|
||||
if (activeTurnId) {
|
||||
const index = units.findIndex((unit) => (
|
||||
@@ -452,7 +795,7 @@ function unitIndexAfterMessageCount(
|
||||
|
||||
function ForkBoundaryDivider({ label }: { label: string }) {
|
||||
return (
|
||||
<div className="my-5 flex items-center gap-3 text-[11px] text-muted-foreground/80">
|
||||
<div className="thread-message-row my-5 flex items-center gap-3 text-[11px] text-muted-foreground/80">
|
||||
<span aria-hidden className="h-px flex-1 bg-border/70" />
|
||||
<span className="shrink-0">{label}</span>
|
||||
<span aria-hidden className="h-px flex-1 bg-border/70" />
|
||||
@@ -528,7 +871,9 @@ function stableTurnMessageKey(message: UIMessage | undefined, fallbackPhase?: st
|
||||
return `turn-${message.turnId}-${phase}`;
|
||||
}
|
||||
|
||||
function marginAfterPrevUnit(prev: DisplayUnit): string {
|
||||
function marginAfterPrevUnit(
|
||||
prev: DisplayUnit,
|
||||
): string {
|
||||
if (prev.type === "activity") {
|
||||
return "mt-4";
|
||||
}
|
||||
@@ -543,5 +888,119 @@ function marginAfterPrevUnit(prev: DisplayUnit): string {
|
||||
if (denseP) {
|
||||
return "mt-2";
|
||||
}
|
||||
if (p.role === "assistant" && !p.isStreaming && p.content.trim().length > 0) {
|
||||
return "mt-5";
|
||||
}
|
||||
return "mt-5";
|
||||
}
|
||||
|
||||
interface CompletedMessageBlocks {
|
||||
blockKeys: Array<string | undefined>;
|
||||
blockIndices: Set<number>;
|
||||
suppressedActivityIndices: Set<number>;
|
||||
activityByBlock: Map<number, Extract<DisplayUnit, { type: "activity" }>>;
|
||||
}
|
||||
|
||||
function completedMessageBlocks(
|
||||
units: DisplayUnit[],
|
||||
unitKeys: string[],
|
||||
isStreaming: boolean,
|
||||
activeTurnId: string | null,
|
||||
currentTurnStartIndex: number,
|
||||
): CompletedMessageBlocks {
|
||||
const result: CompletedMessageBlocks = {
|
||||
blockKeys: new Array<string | undefined>(units.length),
|
||||
blockIndices: new Set<number>(),
|
||||
suppressedActivityIndices: new Set<number>(),
|
||||
activityByBlock: new Map(),
|
||||
};
|
||||
let groupStart = 0;
|
||||
let groupTurnId: string | undefined;
|
||||
|
||||
const flushGroup = (end: number) => {
|
||||
if (groupStart >= end) return;
|
||||
const indices = Array.from({ length: end - groupStart }, (_, offset) => groupStart + offset);
|
||||
const groupIsStreaming = isStreaming && indices.some((index) => {
|
||||
const unit = units[index];
|
||||
const turnId = displayUnitTurnId(unit);
|
||||
if (activeTurnId && turnId) return turnId === activeTurnId;
|
||||
return index > currentTurnStartIndex;
|
||||
});
|
||||
if (groupIsStreaming) return;
|
||||
|
||||
const blockIndices = indices.filter((index) => {
|
||||
const unit = units[index];
|
||||
return unit.type === "message"
|
||||
&& unit.message.role === "assistant"
|
||||
&& unit.message.kind !== "compaction";
|
||||
});
|
||||
for (const index of blockIndices) {
|
||||
result.blockIndices.add(index);
|
||||
result.blockKeys[index] = `message-block-${unitKeys[index]}`;
|
||||
}
|
||||
|
||||
const activityByBlock = new Map<number, Array<Extract<DisplayUnit, { type: "activity" }>>>();
|
||||
for (const index of indices) {
|
||||
const unit = units[index];
|
||||
if (unit.type !== "activity") continue;
|
||||
const blockIndex = blockIndices.find((candidate) => candidate > index) ?? blockIndices.at(-1);
|
||||
if (blockIndex === undefined) continue;
|
||||
result.suppressedActivityIndices.add(index);
|
||||
const activityUnits = activityByBlock.get(blockIndex) ?? [];
|
||||
activityUnits.push(unit);
|
||||
activityByBlock.set(blockIndex, activityUnits);
|
||||
}
|
||||
for (const [blockIndex, activityUnits] of activityByBlock) {
|
||||
result.activityByBlock.set(blockIndex, mergeActivityUnits(activityUnits));
|
||||
}
|
||||
};
|
||||
|
||||
for (let index = 0; index < units.length; index += 1) {
|
||||
const unit = units[index];
|
||||
if (unit.type === "message" && unit.message.role === "user") {
|
||||
flushGroup(index);
|
||||
groupStart = index + 1;
|
||||
groupTurnId = unit.message.turnId;
|
||||
continue;
|
||||
}
|
||||
const turnId = displayUnitTurnId(unit);
|
||||
if (turnId && groupTurnId && turnId !== groupTurnId) {
|
||||
flushGroup(index);
|
||||
groupStart = index;
|
||||
groupTurnId = turnId;
|
||||
} else if (turnId && !groupTurnId) {
|
||||
groupTurnId = turnId;
|
||||
}
|
||||
}
|
||||
flushGroup(units.length);
|
||||
return result;
|
||||
}
|
||||
|
||||
function mergeActivityUnits(
|
||||
units: Array<Extract<DisplayUnit, { type: "activity" }>>,
|
||||
): Extract<DisplayUnit, { type: "activity" }> {
|
||||
return {
|
||||
type: "activity",
|
||||
messages: units.flatMap((unit) => unit.messages),
|
||||
sourceMessageCount: units.reduce((count, unit) => count + unit.sourceMessageCount, 0),
|
||||
turnLatencyMs: [...units].reverse().find((unit) => unit.turnLatencyMs !== undefined)
|
||||
?.turnLatencyMs,
|
||||
startedAtMs: units.find((unit) => unit.startedAtMs !== undefined)?.startedAtMs,
|
||||
};
|
||||
}
|
||||
|
||||
function displayUnitTurnId(unit: DisplayUnit): string | undefined {
|
||||
return unit.type === "activity"
|
||||
? unit.messages.find((message) => message.turnId)?.turnId
|
||||
: unit.message.turnId;
|
||||
}
|
||||
|
||||
function previousVisibleUnitIndex(
|
||||
index: number,
|
||||
suppressedActivityIndices: ReadonlySet<number>,
|
||||
): number {
|
||||
for (let previous = index - 1; previous >= 0; previous -= 1) {
|
||||
if (!suppressedActivityIndices.has(previous)) return previous;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -867,7 +867,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
className={cn(
|
||||
"thread-layout mx-auto grid min-h-full w-full",
|
||||
hasMessages
|
||||
? "h-full max-w-[64rem]"
|
||||
? "h-full"
|
||||
: "max-w-[72rem] px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-6 sm:px-4 sm:py-12",
|
||||
)}
|
||||
>
|
||||
@@ -877,13 +877,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
data-testid="thread-message-region"
|
||||
className={cn(
|
||||
"thread-message-viewport thread-viewport-scrollbar row-start-1 flex min-h-0 min-w-0 flex-col",
|
||||
"scroll-auto justify-start overflow-x-hidden px-3 pb-0 pt-[var(--thread-prompt-inset,3rem)] sm:px-4",
|
||||
"scroll-auto justify-start overflow-x-hidden pb-0 pt-[var(--thread-prompt-inset,3rem)]",
|
||||
"[overflow-anchor:none] [scrollbar-width:none]",
|
||||
"[&::-webkit-scrollbar]:hidden",
|
||||
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
|
||||
)}
|
||||
>
|
||||
<div ref={messageContentRef} className="mx-auto w-full max-w-[var(--content-column-width)]">
|
||||
<div ref={messageContentRef} className="w-full">
|
||||
<ThreadMessages
|
||||
messages={visibleMessages}
|
||||
temporary={temporary}
|
||||
@@ -901,6 +901,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
onForkFromMessage={onForkFromMessage}
|
||||
onQuoteSelection={onQuoteSelection}
|
||||
onActivityToggle={yieldCameraToUser}
|
||||
/>
|
||||
</div>
|
||||
<div aria-hidden className="thread-message-end-gap shrink-0" />
|
||||
|
||||
@@ -1,133 +1,117 @@
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { useState, type ReactNode, type Ref } from "react";
|
||||
import { useId, useState, type ReactNode } from "react";
|
||||
import { Activity } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ThinkingReasoningShellProps {
|
||||
active: boolean;
|
||||
expanded: boolean;
|
||||
contextual?: boolean;
|
||||
showHeader?: boolean;
|
||||
collapseLabel?: string;
|
||||
contentId?: string;
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
viewportRef: Ref<HTMLDivElement>;
|
||||
contentRef: Ref<HTMLDivElement>;
|
||||
fadeTop: boolean;
|
||||
fadeBottom: boolean;
|
||||
hasDetails?: boolean;
|
||||
onToggle: () => void;
|
||||
onScroll: () => void;
|
||||
}
|
||||
|
||||
export function ThinkingReasoningShell({
|
||||
active,
|
||||
expanded,
|
||||
contextual = false,
|
||||
showHeader = true,
|
||||
collapseLabel,
|
||||
contentId: providedContentId,
|
||||
label,
|
||||
children,
|
||||
viewportRef,
|
||||
contentRef,
|
||||
fadeTop,
|
||||
fadeBottom,
|
||||
hasDetails = true,
|
||||
onToggle,
|
||||
onScroll,
|
||||
}: ThinkingReasoningShellProps) {
|
||||
const generatedContentId = useId();
|
||||
const contentId = providedContentId ?? generatedContentId;
|
||||
const [hasExpanded, setHasExpanded] = useState(expanded);
|
||||
if (expanded && !hasExpanded) setHasExpanded(true);
|
||||
const headerClassName = "touch-target inline-flex h-7 min-w-0 items-center gap-1.5 rounded-md px-1.5";
|
||||
const headerContent = (
|
||||
<>
|
||||
<Activity className="h-3.5 w-3.5 shrink-0" strokeWidth={1.5} aria-hidden />
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 truncate text-[12px] font-normal leading-4 text-muted-foreground/65",
|
||||
active && "animate-pulse motion-reduce:animate-none",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className="flex w-full max-w-[45rem] animate-in flex-col fade-in duration-300 motion-reduce:animate-none"
|
||||
data-state={active ? "thinking" : "done"}
|
||||
data-contextual-activity={contextual || undefined}
|
||||
data-block-context-rail={contextual && showHeader || undefined}
|
||||
data-block-context-expanded={contextual && expanded ? true : undefined}
|
||||
>
|
||||
{hasDetails ? (
|
||||
<button
|
||||
type="button"
|
||||
data-thread-disclosure=""
|
||||
className="group inline-flex min-h-5 items-center self-start gap-1.5 bg-transparent p-0"
|
||||
onClick={onToggle}
|
||||
aria-expanded={expanded}
|
||||
aria-label={label}
|
||||
aria-live={active ? "polite" : undefined}
|
||||
>
|
||||
<span
|
||||
{showHeader ? <div className="flex min-h-7 items-center gap-1.5">
|
||||
{hasDetails ? (
|
||||
<button
|
||||
type="button"
|
||||
data-thread-disclosure=""
|
||||
data-contextual-activity-disclosure
|
||||
data-contextual-activity-collapse={expanded || undefined}
|
||||
className={cn(
|
||||
"min-w-0 truncate text-[13px] font-medium leading-[18px] text-muted-foreground/70",
|
||||
active && "animate-pulse motion-reduce:animate-none",
|
||||
headerClassName,
|
||||
"bg-transparent transition-colors hover:bg-muted/60 hover:text-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
)}
|
||||
onClick={onToggle}
|
||||
aria-expanded={expanded}
|
||||
aria-controls={contentId}
|
||||
aria-label={expanded && collapseLabel ? `${label} · ${collapseLabel}` : label}
|
||||
aria-live={active ? "polite" : undefined}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex shrink-0 transition-transform [transition-duration:220ms] ease-out",
|
||||
"motion-reduce:transition-none",
|
||||
expanded && "rotate-180",
|
||||
)}
|
||||
{headerContent}
|
||||
</button>
|
||||
) : (
|
||||
<div
|
||||
className={headerClassName}
|
||||
role="status"
|
||||
aria-label={label}
|
||||
aria-live={active ? "polite" : undefined}
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"h-3 w-3 text-muted-foreground/60 transition-colors duration-200",
|
||||
"group-hover:text-muted-foreground motion-reduce:transition-none",
|
||||
)}
|
||||
strokeWidth={1.8}
|
||||
aria-hidden
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div
|
||||
className="inline-flex min-h-5 items-center self-start"
|
||||
role="status"
|
||||
aria-label={label}
|
||||
aria-live={active ? "polite" : undefined}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 truncate text-[13px] font-medium leading-[18px] text-muted-foreground/70",
|
||||
active && "animate-pulse motion-reduce:animate-none",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{headerContent}
|
||||
</div>
|
||||
)}
|
||||
</div> : null}
|
||||
|
||||
{hasDetails ? (
|
||||
<div
|
||||
id={contentId}
|
||||
{...(!expanded ? { inert: "" } : {})}
|
||||
aria-hidden={!expanded}
|
||||
className={cn(
|
||||
"grid transition-[grid-template-rows,opacity] [transition-duration:220ms] ease-out motion-reduce:transition-none",
|
||||
"grid transition-[grid-template-rows,opacity] duration-150 ease-out motion-reduce:transition-none",
|
||||
expanded
|
||||
? "grid-rows-[1fr] opacity-100"
|
||||
: "pointer-events-none grid-rows-[0fr] opacity-0",
|
||||
)}
|
||||
>
|
||||
<div className="relative min-h-0 overflow-hidden">
|
||||
{expanded ? (
|
||||
<span
|
||||
data-contextual-activity-guide
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-y-1 start-[13px] w-px rounded-full bg-border"
|
||||
/>
|
||||
) : null}
|
||||
<div
|
||||
ref={viewportRef}
|
||||
data-testid={expanded ? "agent-activity-scroll" : undefined}
|
||||
data-fade-top={fadeTop}
|
||||
data-fade-bottom={fadeBottom}
|
||||
onScroll={onScroll}
|
||||
className="mt-1.5 max-h-[180px] overflow-y-auto pr-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||
data-testid={expanded ? "agent-activity-content" : undefined}
|
||||
className="mt-1 flex flex-col gap-0.5 pe-1 ps-6"
|
||||
>
|
||||
<div ref={contentRef} className="flex flex-col gap-0.5">
|
||||
{hasExpanded ? children : null}
|
||||
</div>
|
||||
{hasExpanded ? children : null}
|
||||
</div>
|
||||
{fadeTop ? (
|
||||
<span
|
||||
data-testid="activity-scroll-fade-top"
|
||||
className="pointer-events-none absolute inset-x-0 top-1.5 z-10 h-3.5 bg-gradient-to-b from-background to-transparent"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
{fadeBottom ? (
|
||||
<span
|
||||
data-testid="activity-scroll-fade-bottom"
|
||||
className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-3.5 bg-gradient-to-t from-background to-transparent"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
+59
-4
@@ -757,13 +757,68 @@
|
||||
}
|
||||
}
|
||||
|
||||
.message-actions > button:first-child {
|
||||
margin-inline-start: -0.5rem;
|
||||
.thread-message-row,
|
||||
.message-block-menu-trigger,
|
||||
[data-message-block-menu] {
|
||||
--message-block-control-size: 1.75rem;
|
||||
--message-block-action-width: 1.75rem;
|
||||
--message-block-trigger-offset: 2rem;
|
||||
}
|
||||
|
||||
.thread-message-row {
|
||||
padding-inline-start: max(
|
||||
calc(var(--message-block-trigger-offset) + 0.75rem),
|
||||
calc((100% - var(--content-column-width)) / 2)
|
||||
);
|
||||
padding-inline-end: max(0.75rem, calc((100% - var(--content-column-width)) / 2));
|
||||
}
|
||||
|
||||
.message-block-menu-trigger {
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
[data-user-text-bubble] > .message-block-menu-trigger {
|
||||
/* The first text line is 28px tall, with py-2 around the bubble. */
|
||||
top: calc((1rem + 28px - var(--message-block-control-size)) / 2);
|
||||
}
|
||||
|
||||
[data-context-block-active] .message-block-menu-trigger,
|
||||
[data-message-context-menu-open] .message-block-menu-trigger,
|
||||
.message-block-menu-trigger:focus-visible {
|
||||
pointer-events: auto;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
[data-block-context-rail] {
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 120ms ease-out;
|
||||
}
|
||||
|
||||
[data-context-block-active] [data-block-context-rail],
|
||||
[data-block-context-rail][data-block-context-expanded] {
|
||||
pointer-events: auto;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.message-block-menu-trigger {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
[data-block-context-rail] {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (pointer: coarse) {
|
||||
.message-actions > button:first-child {
|
||||
margin-inline-start: -0.875rem;
|
||||
.thread-message-row,
|
||||
.message-block-menu-trigger,
|
||||
[data-message-block-menu] {
|
||||
--message-block-control-size: 2.75rem;
|
||||
--message-block-action-width: 2rem;
|
||||
--message-block-trigger-offset: 3rem;
|
||||
}
|
||||
|
||||
.touch-target {
|
||||
|
||||
@@ -1783,6 +1783,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "Message actions",
|
||||
"streaming": "streaming",
|
||||
"delivery": {
|
||||
"sending": "Sending…",
|
||||
@@ -1808,6 +1809,10 @@
|
||||
"activityWorkingFor": "Working for {{duration}}",
|
||||
"activityWorked": "Worked",
|
||||
"activityWorkedFor": "Worked for {{duration}}",
|
||||
"collapseActivity": "Collapse activity details",
|
||||
"activityShow": "View activity",
|
||||
"activityShowFor": "View activity {{duration}}",
|
||||
"activityHide": "Hide activity",
|
||||
"traceDetailsLoadFailed": "Full activity details could not be loaded.",
|
||||
"retryTraceDetails": "Retry",
|
||||
"retryConnection": "Connection failed",
|
||||
|
||||
@@ -1584,6 +1584,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "Acciones del mensaje",
|
||||
"streaming": "transmitiendo",
|
||||
"delivery": {
|
||||
"sending": "Enviando…",
|
||||
@@ -1637,6 +1638,10 @@
|
||||
"activityWorkingFor": "Trabajando durante {{duration}}",
|
||||
"activityWorked": "Trabajo completado",
|
||||
"activityWorkedFor": "Trabajó durante {{duration}}",
|
||||
"collapseActivity": "Contraer detalles de actividad",
|
||||
"activityShow": "Ver actividad",
|
||||
"activityShowFor": "Ver actividad {{duration}}",
|
||||
"activityHide": "Ocultar actividad",
|
||||
"traceDetailsLoadFailed": "No se pudieron cargar los detalles completos de la actividad.",
|
||||
"retryTraceDetails": "Reintentar",
|
||||
"retryConnection": "Error de conexión",
|
||||
|
||||
@@ -1583,6 +1583,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "Actions du message",
|
||||
"streaming": "en cours de génération",
|
||||
"delivery": {
|
||||
"sending": "Envoi…",
|
||||
@@ -1636,6 +1637,10 @@
|
||||
"activityWorkingFor": "Travail en cours depuis {{duration}}",
|
||||
"activityWorked": "Travail terminé",
|
||||
"activityWorkedFor": "Travail terminé en {{duration}}",
|
||||
"collapseActivity": "Réduire les détails de l’activité",
|
||||
"activityShow": "Voir l’activité",
|
||||
"activityShowFor": "Voir l’activité {{duration}}",
|
||||
"activityHide": "Masquer l’activité",
|
||||
"traceDetailsLoadFailed": "Impossible de charger les détails complets de l’activité.",
|
||||
"retryTraceDetails": "Réessayer",
|
||||
"retryConnection": "Échec de la connexion",
|
||||
|
||||
@@ -1583,6 +1583,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "Tindakan pesan",
|
||||
"streaming": "sedang mengalir",
|
||||
"delivery": {
|
||||
"sending": "Mengirim…",
|
||||
@@ -1636,6 +1637,10 @@
|
||||
"activityWorkingFor": "Memproses selama {{duration}}",
|
||||
"activityWorked": "Selesai memproses",
|
||||
"activityWorkedFor": "Diproses selama {{duration}}",
|
||||
"collapseActivity": "Ciutkan detail aktivitas",
|
||||
"activityShow": "Lihat aktivitas",
|
||||
"activityShowFor": "Lihat aktivitas {{duration}}",
|
||||
"activityHide": "Sembunyikan aktivitas",
|
||||
"traceDetailsLoadFailed": "Detail aktivitas lengkap tidak dapat dimuat.",
|
||||
"retryTraceDetails": "Coba lagi",
|
||||
"retryConnection": "Koneksi gagal",
|
||||
|
||||
@@ -1583,6 +1583,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "メッセージ操作",
|
||||
"streaming": "生成中",
|
||||
"delivery": {
|
||||
"sending": "送信中…",
|
||||
@@ -1636,6 +1637,10 @@
|
||||
"activityWorkingFor": "{{duration}}作業中",
|
||||
"activityWorked": "作業しました",
|
||||
"activityWorkedFor": "{{duration}}作業しました",
|
||||
"collapseActivity": "アクティビティの詳細を折りたたむ",
|
||||
"activityShow": "処理過程を表示",
|
||||
"activityShowFor": "処理過程を表示 {{duration}}",
|
||||
"activityHide": "処理過程を非表示",
|
||||
"traceDetailsLoadFailed": "アクティビティの詳細を読み込めませんでした。",
|
||||
"retryTraceDetails": "再試行",
|
||||
"retryConnection": "接続に失敗しました",
|
||||
|
||||
@@ -1583,6 +1583,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "메시지 작업",
|
||||
"streaming": "생성 중",
|
||||
"delivery": {
|
||||
"sending": "전송 중…",
|
||||
@@ -1636,6 +1637,10 @@
|
||||
"activityWorkingFor": "{{duration}} 동안 작업 중",
|
||||
"activityWorked": "작업함",
|
||||
"activityWorkedFor": "{{duration}} 동안 작업함",
|
||||
"collapseActivity": "활동 세부 정보 접기",
|
||||
"activityShow": "작업 과정 보기",
|
||||
"activityShowFor": "작업 과정 보기 {{duration}}",
|
||||
"activityHide": "작업 과정 숨기기",
|
||||
"traceDetailsLoadFailed": "전체 활동 세부 정보를 불러올 수 없습니다.",
|
||||
"retryTraceDetails": "다시 시도",
|
||||
"retryConnection": "연결 실패",
|
||||
|
||||
@@ -1597,6 +1597,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "Ações da mensagem",
|
||||
"streaming": "transmitindo",
|
||||
"delivery": {
|
||||
"sending": "Enviando…",
|
||||
@@ -1622,6 +1623,10 @@
|
||||
"activityWorkingFor": "Trabalhando por {{duration}}",
|
||||
"activityWorked": "Trabalhou",
|
||||
"activityWorkedFor": "Trabalhou por {{duration}}",
|
||||
"collapseActivity": "Recolher detalhes da atividade",
|
||||
"activityShow": "Ver atividade",
|
||||
"activityShowFor": "Ver atividade {{duration}}",
|
||||
"activityHide": "Ocultar atividade",
|
||||
"traceDetailsLoadFailed": "Não foi possível carregar os detalhes completos da atividade.",
|
||||
"retryTraceDetails": "Tentar novamente",
|
||||
"retryConnection": "Falha na conexão",
|
||||
|
||||
@@ -1583,6 +1583,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "Thao tác tin nhắn",
|
||||
"streaming": "đang truyền",
|
||||
"delivery": {
|
||||
"sending": "Đang gửi…",
|
||||
@@ -1636,6 +1637,10 @@
|
||||
"activityWorkingFor": "Đang xử lý trong {{duration}}",
|
||||
"activityWorked": "Đã xử lý",
|
||||
"activityWorkedFor": "Đã xử lý trong {{duration}}",
|
||||
"collapseActivity": "Thu gọn chi tiết hoạt động",
|
||||
"activityShow": "Xem quá trình",
|
||||
"activityShowFor": "Xem quá trình {{duration}}",
|
||||
"activityHide": "Ẩn quá trình",
|
||||
"traceDetailsLoadFailed": "Không thể tải đầy đủ chi tiết hoạt động.",
|
||||
"retryTraceDetails": "Thử lại",
|
||||
"retryConnection": "Kết nối thất bại",
|
||||
|
||||
@@ -1783,6 +1783,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "消息操作",
|
||||
"streaming": "流式输出中",
|
||||
"delivery": {
|
||||
"sending": "发送中…",
|
||||
@@ -1807,7 +1808,11 @@
|
||||
"activityThoughtFor": "思考了 {{duration}}",
|
||||
"activityWorkingFor": "处理中 {{duration}}",
|
||||
"activityWorked": "已处理",
|
||||
"activityWorkedFor": "处理了 {{duration}}",
|
||||
"activityWorkedFor": "已处理 {{duration}}",
|
||||
"collapseActivity": "收起处理过程",
|
||||
"activityShow": "查看过程",
|
||||
"activityShowFor": "查看过程 {{duration}}",
|
||||
"activityHide": "收起过程",
|
||||
"traceDetailsLoadFailed": "无法加载完整活动详情。",
|
||||
"retryTraceDetails": "重试",
|
||||
"retryConnection": "连接失败",
|
||||
|
||||
@@ -1583,6 +1583,7 @@
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"actions": "訊息操作",
|
||||
"streaming": "串流輸出中",
|
||||
"delivery": {
|
||||
"sending": "傳送中…",
|
||||
@@ -1635,6 +1636,10 @@
|
||||
"activityWorkingFor": "處理中,已 {{duration}}",
|
||||
"activityWorked": "已處理",
|
||||
"activityWorkedFor": "已處理 {{duration}}",
|
||||
"collapseActivity": "收合處理過程",
|
||||
"activityShow": "查看過程",
|
||||
"activityShowFor": "查看過程 {{duration}}",
|
||||
"activityHide": "收合過程",
|
||||
"traceDetailsLoadFailed": "無法載入完整活動詳情。",
|
||||
"retryTraceDetails": "重試",
|
||||
"retryConnection": "連線失敗",
|
||||
|
||||
@@ -76,49 +76,6 @@ function activityMessages(extraReasoning = "", extraTool?: UIMessage): UIMessage
|
||||
return rows;
|
||||
}
|
||||
|
||||
function installAnimationFrameQueue() {
|
||||
const originalRequest = window.requestAnimationFrame;
|
||||
const originalCancel = window.cancelAnimationFrame;
|
||||
const callbacks = new Map<number, FrameRequestCallback>();
|
||||
let nextId = 1;
|
||||
|
||||
window.requestAnimationFrame = ((callback: FrameRequestCallback) => {
|
||||
const id = nextId;
|
||||
nextId += 1;
|
||||
callbacks.set(id, callback);
|
||||
return id;
|
||||
}) as typeof window.requestAnimationFrame;
|
||||
window.cancelAnimationFrame = ((id: number) => {
|
||||
callbacks.delete(id);
|
||||
}) as typeof window.cancelAnimationFrame;
|
||||
|
||||
return {
|
||||
flush() {
|
||||
const pending = Array.from(callbacks.entries());
|
||||
callbacks.clear();
|
||||
for (const [, callback] of pending) callback(0);
|
||||
},
|
||||
restore() {
|
||||
window.requestAnimationFrame = originalRequest;
|
||||
window.cancelAnimationFrame = originalCancel;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function setScrollGeometry(
|
||||
element: HTMLElement,
|
||||
geometry: { scrollHeight: number; clientHeight: number; scrollTop?: number },
|
||||
) {
|
||||
Object.defineProperties(element, {
|
||||
scrollHeight: { configurable: true, value: geometry.scrollHeight },
|
||||
clientHeight: { configurable: true, value: geometry.clientHeight },
|
||||
scrollTop: {
|
||||
configurable: true,
|
||||
value: geometry.scrollTop ?? element.scrollTop,
|
||||
writable: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function installReducedMotion() {
|
||||
const original = window.matchMedia;
|
||||
@@ -219,186 +176,39 @@ describe("AgentActivityCluster", () => {
|
||||
expect(screen.queryByTestId("activity-step")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("jumps to the latest activity when opened", () => {
|
||||
const raf = installAnimationFrameQueue();
|
||||
try {
|
||||
render(
|
||||
<AgentActivityCluster
|
||||
messages={activityMessages()}
|
||||
isTurnStreaming
|
||||
hasBodyBelow={false}
|
||||
/>,
|
||||
);
|
||||
it.each([false, true])("uses one activity layout without nested scrolling (streaming: %s)", (isTurnStreaming) => {
|
||||
const onExpandedChange = vi.fn();
|
||||
const props = {
|
||||
messages: activityMessages(),
|
||||
isTurnStreaming,
|
||||
hasBodyBelow: false,
|
||||
...(isTurnStreaming ? {} : { expanded: true, hideHeader: true }),
|
||||
onExpandedChange,
|
||||
};
|
||||
const view = render(<AgentActivityCluster {...props} />);
|
||||
const header = screen.getByRole("button", { name: /^(Working|Worked)/ });
|
||||
const content = screen.getByTestId("agent-activity-content");
|
||||
|
||||
const scrollport = screen.getByTestId("agent-activity-scroll");
|
||||
setScrollGeometry(scrollport, {
|
||||
scrollHeight: 1000,
|
||||
clientHeight: 120,
|
||||
scrollTop: 0,
|
||||
});
|
||||
expect(header).toHaveClass("h-7", "gap-1.5", "px-1.5");
|
||||
expect(header.querySelector("svg")).toHaveClass("lucide-activity");
|
||||
expect(header).toHaveAttribute("aria-expanded", "true");
|
||||
expect(view.container.querySelector("[data-contextual-activity-guide]")).toBeInTheDocument();
|
||||
expect(content).toHaveClass("ps-6");
|
||||
expect(content).not.toHaveClass("max-h-[180px]");
|
||||
expect(content).not.toHaveClass("overflow-y-auto");
|
||||
expect(screen.queryByTestId("activity-scroll-fade-top")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("activity-scroll-fade-bottom")).not.toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
raf.flush();
|
||||
});
|
||||
|
||||
expect(scrollport.scrollTop).toBe(880);
|
||||
} finally {
|
||||
raf.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it("follows new reasoning and tool activity while the user is at the bottom", () => {
|
||||
const raf = installAnimationFrameQueue();
|
||||
try {
|
||||
const { rerender } = render(
|
||||
<AgentActivityCluster
|
||||
messages={activityMessages()}
|
||||
isTurnStreaming
|
||||
hasBodyBelow={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
const scrollport = screen.getByTestId("agent-activity-scroll");
|
||||
setScrollGeometry(scrollport, {
|
||||
scrollHeight: 1000,
|
||||
clientHeight: 120,
|
||||
scrollTop: 0,
|
||||
});
|
||||
act(() => {
|
||||
raf.flush();
|
||||
});
|
||||
|
||||
rerender(
|
||||
<AgentActivityCluster
|
||||
messages={activityMessages(" with more detail", {
|
||||
id: "t2",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "open_browser()",
|
||||
traces: ["open_browser()"],
|
||||
createdAt: 3,
|
||||
})}
|
||||
isTurnStreaming
|
||||
hasBodyBelow={false}
|
||||
/>,
|
||||
);
|
||||
setScrollGeometry(scrollport, {
|
||||
scrollHeight: 1500,
|
||||
clientHeight: 120,
|
||||
scrollTop: scrollport.scrollTop,
|
||||
});
|
||||
|
||||
act(() => {
|
||||
raf.flush();
|
||||
});
|
||||
|
||||
expect(scrollport.scrollTop).toBe(1380);
|
||||
} finally {
|
||||
raf.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not pull the user down after they scroll up inside the activity pane", () => {
|
||||
const raf = installAnimationFrameQueue();
|
||||
try {
|
||||
const { rerender } = render(
|
||||
<AgentActivityCluster
|
||||
messages={activityMessages()}
|
||||
isTurnStreaming
|
||||
hasBodyBelow={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
const scrollport = screen.getByTestId("agent-activity-scroll");
|
||||
setScrollGeometry(scrollport, {
|
||||
scrollHeight: 1000,
|
||||
clientHeight: 120,
|
||||
scrollTop: 0,
|
||||
});
|
||||
act(() => {
|
||||
raf.flush();
|
||||
});
|
||||
|
||||
scrollport.scrollTop = 100;
|
||||
fireEvent.scroll(scrollport);
|
||||
|
||||
rerender(
|
||||
<AgentActivityCluster
|
||||
messages={activityMessages(" still streaming")}
|
||||
isTurnStreaming
|
||||
hasBodyBelow={false}
|
||||
/>,
|
||||
);
|
||||
setScrollGeometry(scrollport, {
|
||||
scrollHeight: 1500,
|
||||
clientHeight: 120,
|
||||
scrollTop: scrollport.scrollTop,
|
||||
});
|
||||
|
||||
act(() => {
|
||||
raf.flush();
|
||||
});
|
||||
|
||||
expect(scrollport.scrollTop).toBe(100);
|
||||
} finally {
|
||||
raf.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it("feathers only the activity edges with clipped content", () => {
|
||||
const raf = installAnimationFrameQueue();
|
||||
try {
|
||||
render(
|
||||
<AgentActivityCluster
|
||||
messages={activityMessages()}
|
||||
isTurnStreaming
|
||||
hasBodyBelow={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
const scrollport = screen.getByTestId("agent-activity-scroll");
|
||||
setScrollGeometry(scrollport, {
|
||||
scrollHeight: 1000,
|
||||
clientHeight: 120,
|
||||
scrollTop: 0,
|
||||
});
|
||||
|
||||
act(() => {
|
||||
raf.flush();
|
||||
});
|
||||
expect(scrollport).toHaveAttribute("data-fade-top", "true");
|
||||
expect(scrollport).toHaveAttribute("data-fade-bottom", "false");
|
||||
const topFade = screen.getByTestId("activity-scroll-fade-top");
|
||||
expect(scrollport).not.toContainElement(topFade);
|
||||
expect(scrollport).not.toHaveClass("activity-scroll-fade");
|
||||
expect(screen.queryByTestId("activity-scroll-fade-bottom")).not.toBeInTheDocument();
|
||||
|
||||
scrollport.scrollTop = 440;
|
||||
fireEvent.scroll(scrollport);
|
||||
expect(scrollport).toHaveAttribute("data-fade-top", "true");
|
||||
expect(scrollport).toHaveAttribute("data-fade-bottom", "true");
|
||||
expect(screen.getByTestId("activity-scroll-fade-top")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("activity-scroll-fade-bottom")).toBeInTheDocument();
|
||||
|
||||
scrollport.scrollTop = 0;
|
||||
fireEvent.scroll(scrollport);
|
||||
expect(scrollport).toHaveAttribute("data-fade-top", "false");
|
||||
expect(scrollport).toHaveAttribute("data-fade-bottom", "true");
|
||||
expect(screen.queryByTestId("activity-scroll-fade-top")).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId("activity-scroll-fade-bottom")).toBeInTheDocument();
|
||||
|
||||
setScrollGeometry(scrollport, {
|
||||
scrollHeight: 100,
|
||||
clientHeight: 120,
|
||||
scrollTop: 0,
|
||||
});
|
||||
fireEvent.scroll(scrollport);
|
||||
expect(scrollport).toHaveAttribute("data-fade-top", "false");
|
||||
expect(scrollport).toHaveAttribute("data-fade-bottom", "false");
|
||||
expect(screen.queryByTestId("activity-scroll-fade-top")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("activity-scroll-fade-bottom")).not.toBeInTheDocument();
|
||||
} finally {
|
||||
raf.restore();
|
||||
view.rerender(<AgentActivityCluster {...props} messages={activityMessages(" updated", {
|
||||
id: "next-tool", role: "tool", kind: "trace", content: "open_browser()", createdAt: 3,
|
||||
})} />);
|
||||
expect(screen.getByTestId("agent-activity-content")).toBe(content);
|
||||
expect(content).toHaveTextContent("thinking updated");
|
||||
fireEvent.click(header);
|
||||
if (isTurnStreaming) {
|
||||
expect(screen.queryByTestId("agent-activity-content")).not.toBeInTheDocument();
|
||||
} else {
|
||||
expect(onExpandedChange).toHaveBeenCalledWith(false);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -459,7 +269,7 @@ describe("AgentActivityCluster", () => {
|
||||
hasBodyBelow
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId("agent-activity-scroll")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("agent-activity-content")).toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
<AgentActivityCluster
|
||||
@@ -473,11 +283,11 @@ describe("AgentActivityCluster", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("agent-activity-scroll")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("agent-activity-content")).toBeInTheDocument();
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(301);
|
||||
});
|
||||
expect(screen.queryByTestId("agent-activity-scroll")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("agent-activity-content")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Worked" })).toHaveAttribute(
|
||||
"aria-expanded",
|
||||
"false",
|
||||
@@ -487,31 +297,6 @@ describe("AgentActivityCluster", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps chevron color feedback faster than the drawer rotation", () => {
|
||||
render(
|
||||
<AgentActivityCluster
|
||||
messages={[{
|
||||
id: "r-motion",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
reasoning: "checking motion",
|
||||
createdAt: 1,
|
||||
}]}
|
||||
isTurnStreaming={false}
|
||||
hasBodyBelow
|
||||
/>,
|
||||
);
|
||||
|
||||
const button = screen.getByRole("button", { name: "Worked" });
|
||||
expect(button).toHaveAttribute("data-thread-disclosure");
|
||||
const chevron = button.querySelector("svg");
|
||||
expect(chevron).toBeInTheDocument();
|
||||
expect(chevron).toHaveClass("transition-colors", "duration-200");
|
||||
expect(chevron?.parentElement).toHaveClass(
|
||||
"transition-transform",
|
||||
"[transition-duration:220ms]",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses persisted turn latency for completed history instead of replay timestamps", () => {
|
||||
render(
|
||||
@@ -711,7 +496,7 @@ describe("AgentActivityCluster", () => {
|
||||
const assertIndependentDiff = () => {
|
||||
const diff = screen.getByTestId("file-edit-diff");
|
||||
expect(diff).toBeVisible();
|
||||
expect(diff.closest('[aria-hidden="true"], [inert], [data-testid="agent-activity-scroll"]'))
|
||||
expect(diff.closest('[aria-hidden="true"], [inert], [data-testid="agent-activity-content"]'))
|
||||
.toBeNull();
|
||||
expect(screen.getAllByTestId("activity-file-reference")).toHaveLength(1);
|
||||
};
|
||||
@@ -1140,7 +925,7 @@ describe("AgentActivityCluster", () => {
|
||||
);
|
||||
|
||||
expect(screen.queryByRole("button", { name: /edited app\.tsx/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("agent-activity-scroll")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("agent-activity-content")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Edited")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("activity-header-file-reference")).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId("activity-file-reference")).toHaveTextContent("src/app.tsx");
|
||||
|
||||
@@ -23,4 +23,19 @@ describe("chat translation resources", () => {
|
||||
expect(i18n.t(key), key).not.toBe(key);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses one Chinese work-status vocabulary with and without duration", async () => {
|
||||
const i18n = createInstance();
|
||||
await i18n.init({
|
||||
lng: "zh-CN",
|
||||
fallbackLng: false,
|
||||
resources: { "zh-CN": { translation: zhCN } },
|
||||
});
|
||||
|
||||
expect(i18n.t("message.activityWorkingFor", { duration: "15s" })).toBe("处理中 15s");
|
||||
expect(i18n.t("message.activityWorked")).toBe("已处理");
|
||||
expect(i18n.t("message.activityWorkedFor", { duration: "15s" })).toBe("已处理 15s");
|
||||
expect(i18n.t("message.activityShowFor", { duration: "15s" })).toBe("查看过程 15s");
|
||||
expect(i18n.t("message.activityHide")).toBe("收起过程");
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,11 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
|
||||
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import * as clipboard from "@/lib/clipboard";
|
||||
import { fmtDateTime, formatMessageEndTime } from "@/lib/format";
|
||||
import { formatMessageEndTime } from "@/lib/format";
|
||||
import type {
|
||||
CliAppInfo,
|
||||
McpPresetInfo,
|
||||
@@ -96,49 +97,53 @@ const SLASH_COMMANDS: SlashCommand[] = [
|
||||
},
|
||||
];
|
||||
|
||||
function menuActions(root: ParentNode = document): HTMLElement {
|
||||
const actions = root.querySelector<HTMLElement>("[data-message-block-menu-actions]");
|
||||
expect(actions).not.toBeNull();
|
||||
return actions!;
|
||||
}
|
||||
|
||||
describe("MessageBubble", () => {
|
||||
it.each([false, undefined])("hides normal and legacy source badges (fallback: %s)", (fallback) => {
|
||||
it.each([false, undefined])("keeps normal sources out of the block menu (fallback: %s)", (fallback) => {
|
||||
const message: UIMessage = { id: "primary", role: "assistant", content: "Hello", createdAt: 0,
|
||||
isStreaming: true, responseSources: [{ provider: "openai_codex", model: "gpt", preset: "codex", fallback }] };
|
||||
const { container, rerender } = render(<MessageBubble message={message} />);
|
||||
expect(screen.queryByText("codex")).not.toBeInTheDocument();
|
||||
expect(container.querySelector("[data-assistant-footer]")).toHaveAttribute("data-state", "reserved");
|
||||
rerender(<MessageBubble message={{ ...message, isStreaming: false }} />);
|
||||
expect(screen.queryByText("codex")).not.toBeInTheDocument();
|
||||
responseSources: [{ provider: "openai_codex", model: "gpt", preset: "codex", fallback }] };
|
||||
render(<MessageBlockMenuActions message={message} />);
|
||||
expect(screen.getByRole("button", { name: "Copy" })).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: /fallback/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows only fallback provider logos and preset names while streaming and after completion", () => {
|
||||
it("keeps fallback sources visible live and moves them into the completed block menu", () => {
|
||||
const message: UIMessage = { id: "actual", role: "assistant", content: "Hello", createdAt: 0,
|
||||
isStreaming: true, responseSources: [
|
||||
{ provider: "openai_codex", model: "gpt", preset: "codex", fallback: false },
|
||||
{ provider: "xai", model: "grok-4.5", preset: "grok", fallback: true },
|
||||
] };
|
||||
const { container, rerender } = render(<MessageBubble message={message} />);
|
||||
const { container, rerender } = render(<ThreadMessages messages={[message]} isStreaming />);
|
||||
expect(screen.getByText("grok")).toBeVisible();
|
||||
expect(screen.queryByText("codex")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("grok-4.5")).not.toBeInTheDocument();
|
||||
expect(container.querySelector("[data-assistant-footer]")).toHaveAttribute("data-state", "visible");
|
||||
expect(container.querySelector("img")).toHaveAttribute("alt", "");
|
||||
fireEvent.error(container.querySelector("img")!);
|
||||
expect(screen.getByText("grok")).toBeVisible();
|
||||
rerender(<MessageBubble message={{ ...message, isStreaming: false }} />);
|
||||
expect(screen.getByText("grok")).toBeVisible();
|
||||
rerender(<MessageBubble message={{ ...message, responseSources: undefined }} />);
|
||||
rerender(<ThreadMessages messages={[{ ...message, isStreaming: false }]} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
|
||||
expect(menuActions()).toContainElement(screen.getByText("grok"));
|
||||
expect(screen.getAllByText("grok")).toHaveLength(1);
|
||||
rerender(<ThreadMessages messages={[{ ...message, isStreaming: false, responseSources: undefined }]} />);
|
||||
expect(screen.queryByText("grok")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("explains fallback on focus and click, with the source directly after the timestamp", async () => {
|
||||
it("explains fallback on focus and click, with the source above static metadata", async () => {
|
||||
await setAppLanguage("zh-CN");
|
||||
const description = "本条回复已切换至备用模型,由 grok 回答。";
|
||||
const { container } = render(<MessageBubble message={{
|
||||
const { container } = render(<MessageBlockMenuActions message={{
|
||||
id: "fallback-info", role: "assistant", content: "你好", createdAt: 1,
|
||||
responseSources: [{ provider: "xai", model: "grok", preset: "grok", fallback: true }],
|
||||
}} />);
|
||||
const trigger = screen.getByRole("button", { name: description });
|
||||
const footer = container.querySelector("[data-assistant-footer]")!;
|
||||
const sourceGroup = footer.querySelector("[data-message-timestamp]")!.nextElementSibling;
|
||||
expect(sourceGroup).toContainElement(trigger);
|
||||
expect(sourceGroup).not.toHaveClass("ml-auto");
|
||||
const actions = menuActions(container);
|
||||
const metadata = actions.querySelector("[data-message-block-metadata]")!;
|
||||
expect(trigger.compareDocumentPosition(metadata) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
fireEvent.focus(trigger);
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent(description);
|
||||
fireEvent.blur(trigger);
|
||||
@@ -157,11 +162,13 @@ describe("MessageBubble", () => {
|
||||
configurable: true,
|
||||
value: { writeText },
|
||||
});
|
||||
render(<MessageBubble message={{
|
||||
const { container } = render(<ThreadMessages messages={[{
|
||||
id: "compact-empty", role: "assistant", content: "Nothing to compact.",
|
||||
compactReply: "empty", createdAt: 1,
|
||||
}} />);
|
||||
}]} />);
|
||||
expect(screen.getByText("无需压缩上下文")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "消息操作" }));
|
||||
expect(container).toHaveTextContent("无需压缩上下文");
|
||||
fireEvent.click(screen.getByRole("button", { name: "复制" }));
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalledWith("无需压缩上下文"));
|
||||
});
|
||||
@@ -202,9 +209,28 @@ describe("MessageBubble", () => {
|
||||
const pill = screen.getByText("hello");
|
||||
|
||||
expect(row).toHaveClass("ml-auto", "flex");
|
||||
expect(row).toHaveAttribute("data-user-text-bubble", "true");
|
||||
expect(pill).toHaveClass("ml-auto", "w-fit", "rounded-floating");
|
||||
expect(screen.getByRole("button", { name: "Copy" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Fork" })).not.toBeInTheDocument();
|
||||
expect(pill).toHaveTextContent("hello");
|
||||
});
|
||||
|
||||
it("aligns the context trigger to the first text line only when text leads the user block", () => {
|
||||
const message: UIMessage = {
|
||||
id: "u-alignment", role: "user", content: "first line\nsecond line", createdAt: 0,
|
||||
};
|
||||
const contextMenu = <button data-message-block-menu-trigger>Message actions</button>;
|
||||
const { container, rerender } = render(
|
||||
<MessageBubble message={message} contextMenu={contextMenu} />,
|
||||
);
|
||||
const row = container.firstElementChild!;
|
||||
expect(row).toHaveAttribute("data-user-text-bubble", "true");
|
||||
expect(screen.getByRole("button", { name: "Message actions" }).parentElement).toBe(row);
|
||||
|
||||
rerender(<MessageBubble message={{ ...message, images: [{ name: "image.png" }] }} contextMenu={contextMenu} />);
|
||||
expect(row).not.toHaveAttribute("data-user-text-bubble");
|
||||
|
||||
rerender(<MessageBubble message={{ ...message, content: "> [!QUOTE]\n> excerpt\n\nreply" }} contextMenu={contextMenu} />);
|
||||
expect(row).not.toHaveAttribute("data-user-text-bubble");
|
||||
});
|
||||
|
||||
it("renders cross-session input with its public handle", () => {
|
||||
@@ -368,7 +394,7 @@ describe("MessageBubble", () => {
|
||||
};
|
||||
|
||||
try {
|
||||
render(<MessageBubble message={message} />);
|
||||
render(<MessageBlockMenuActions message={message} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
|
||||
|
||||
@@ -499,7 +525,7 @@ describe("MessageBubble", () => {
|
||||
.toHaveTextContent("Try unknown or blocked-skill and $");
|
||||
});
|
||||
|
||||
it("renders fork control in completed assistant action rows", () => {
|
||||
it("renders fork as a contextual assistant action", () => {
|
||||
const onForkFromHere = vi.fn();
|
||||
const message: UIMessage = {
|
||||
id: "a-fork",
|
||||
@@ -509,16 +535,19 @@ describe("MessageBubble", () => {
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
render(<MessageBubble message={message} onForkFromHere={onForkFromHere} />);
|
||||
const { container } = render(
|
||||
<MessageBlockMenuActions message={message} onForkFromHere={onForkFromHere} />,
|
||||
);
|
||||
|
||||
menuActions(container);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Fork" }));
|
||||
expect(onForkFromHere).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shows the assistant completion time in the former latency slot", async () => {
|
||||
it("keeps assistant completion time in the block menu metadata", () => {
|
||||
const completedAt = Date.UTC(2026, 6, 25, 12, 34, 56);
|
||||
const { container } = render(
|
||||
<MessageBubble
|
||||
<MessageBlockMenuActions
|
||||
message={{
|
||||
id: "a-completed-at",
|
||||
role: "assistant",
|
||||
@@ -530,28 +559,35 @@ describe("MessageBubble", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Copy" })).toBeInTheDocument();
|
||||
const time = container.querySelector("[data-assistant-completed-at]");
|
||||
menuActions(container);
|
||||
const time = document.querySelector("[data-assistant-completed-at]");
|
||||
expect(time).toHaveTextContent(formatMessageEndTime(completedAt));
|
||||
expect(time).toHaveAttribute("dateTime", new Date(completedAt).toISOString());
|
||||
expect(time).not.toHaveAttribute("title");
|
||||
expect(time).toHaveAttribute("tabIndex", "0");
|
||||
expect(time).toHaveClass(
|
||||
"cursor-help",
|
||||
"text-[11px]",
|
||||
"leading-none",
|
||||
"text-muted-foreground/70",
|
||||
"tabular-nums",
|
||||
);
|
||||
expect(time).toHaveClass("tabular-nums");
|
||||
});
|
||||
|
||||
fireEvent.pointerMove(time!);
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent(fmtDateTime(completedAt));
|
||||
it("groups actions above static timestamp metadata", () => {
|
||||
const completedAt = Date.UTC(2026, 6, 25, 12, 34, 56);
|
||||
const { container } = render(<MessageBlockMenuActions
|
||||
message={{ id: "a-actions", role: "assistant", content: "Finished answer",
|
||||
completedAt, createdAt: completedAt - 1_000 }}
|
||||
onForkFromHere={vi.fn()}
|
||||
/>);
|
||||
const actions = menuActions(container);
|
||||
const copy = screen.getByRole("button", { name: "Copy" });
|
||||
const fork = screen.getByRole("button", { name: "Fork" });
|
||||
const metadata = actions.querySelector("[data-message-block-metadata]")!;
|
||||
expect(actions.querySelector("[data-message-block-toolbar]")).toContainElement(copy);
|
||||
expect(actions.querySelector("[data-message-block-toolbar]")).toContainElement(fork);
|
||||
expect(metadata).toHaveTextContent(formatMessageEndTime(completedAt));
|
||||
expect(copy.compareDocumentPosition(fork) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(fork.compareDocumentPosition(metadata) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
|
||||
it("falls back to the assistant creation time when replay has no completion time", () => {
|
||||
const createdAt = Date.UTC(2026, 6, 25, 12, 34, 56);
|
||||
const { container } = render(
|
||||
<MessageBubble
|
||||
<MessageBlockMenuActions
|
||||
message={{
|
||||
id: "a-created-at",
|
||||
role: "assistant",
|
||||
@@ -561,17 +597,17 @@ describe("MessageBubble", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const time = container.querySelector("[data-message-timestamp]");
|
||||
menuActions(container);
|
||||
const time = document.querySelector("[data-message-timestamp]");
|
||||
expect(time).toHaveTextContent(formatMessageEndTime(createdAt));
|
||||
expect(time).toHaveAttribute("dateTime", new Date(createdAt).toISOString());
|
||||
expect(time).not.toHaveAttribute("title");
|
||||
expect(time).not.toHaveAttribute("data-assistant-completed-at");
|
||||
});
|
||||
|
||||
it("renders the creation time for user messages", async () => {
|
||||
it("renders the creation time for user messages", () => {
|
||||
const createdAt = Date.UTC(2026, 6, 25, 12, 34, 56);
|
||||
const { container } = render(
|
||||
<MessageBubble
|
||||
<MessageBlockMenuActions
|
||||
message={{
|
||||
id: "u-created-at",
|
||||
role: "user",
|
||||
@@ -585,17 +621,15 @@ describe("MessageBubble", () => {
|
||||
expect(time).toHaveTextContent(formatMessageEndTime(createdAt));
|
||||
expect(time).toHaveAttribute("dateTime", new Date(createdAt).toISOString());
|
||||
expect(time).not.toHaveAttribute("title");
|
||||
expect(time).toHaveAttribute("tabIndex", "0");
|
||||
|
||||
fireEvent.pointerMove(time!);
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent(fmtDateTime(createdAt));
|
||||
expect(time).toHaveProperty("tabIndex", -1);
|
||||
expect(time?.parentElement).toHaveAttribute("data-message-block-metadata");
|
||||
});
|
||||
|
||||
it("does not infer completion time from the assistant creation timestamp", () => {
|
||||
const createdAt = Date.UTC(2026, 6, 25, 12, 34, 0);
|
||||
const latencyMs = 13_000;
|
||||
const { container } = render(
|
||||
<MessageBubble
|
||||
<MessageBlockMenuActions
|
||||
message={{
|
||||
id: "a-replayed-completion",
|
||||
role: "assistant",
|
||||
@@ -606,7 +640,11 @@ describe("MessageBubble", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.querySelector("[data-assistant-completed-at]")).not.toBeInTheDocument();
|
||||
menuActions(container);
|
||||
expect(document.querySelector("[data-assistant-completed-at]")).not.toBeInTheDocument();
|
||||
expect(document.querySelector("[data-message-timestamp]")).toHaveTextContent(
|
||||
formatMessageEndTime(createdAt),
|
||||
);
|
||||
});
|
||||
|
||||
it("renders installed CLI app mentions inside sent user messages", () => {
|
||||
@@ -634,7 +672,7 @@ describe("MessageBubble", () => {
|
||||
expect(screen.getByText(/not @krita/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("places automation metadata after the timestamp and reveals its source on hover", async () => {
|
||||
it("places automation metadata after the timestamp with its source visible", () => {
|
||||
const completedAt = Date.UTC(2026, 6, 25, 12, 34, 56);
|
||||
const message: UIMessage = {
|
||||
id: "a-cron",
|
||||
@@ -645,28 +683,15 @@ describe("MessageBubble", () => {
|
||||
createdAt: completedAt - 1_000,
|
||||
};
|
||||
|
||||
const { container } = render(<MessageBubble message={message} />);
|
||||
const { container } = render(<MessageBlockMenuActions message={message} />);
|
||||
|
||||
const footer = container.querySelector("[data-assistant-footer]")!;
|
||||
const timestamp = footer.querySelector("[data-message-timestamp]")!;
|
||||
const trigger = footer.querySelector("[data-automation-trigger]")!;
|
||||
menuActions(container);
|
||||
|
||||
const timestamp = document.querySelector("[data-message-timestamp]")!;
|
||||
const automation = document.querySelector("[data-automation-trigger]")!;
|
||||
expect(timestamp).toHaveTextContent(formatMessageEndTime(completedAt));
|
||||
expect(trigger).toHaveTextContent("Triggered automatically");
|
||||
expect(trigger.previousElementSibling).toBe(timestamp);
|
||||
expect(trigger).toHaveClass(
|
||||
"text-[11px]",
|
||||
"leading-none",
|
||||
"text-muted-foreground/70",
|
||||
"tabular-nums",
|
||||
);
|
||||
expect(trigger.className).not.toMatch(/(?:^|\s)(?:border|bg-)/);
|
||||
expect(trigger.querySelector("svg")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("drink water")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Time to drink water.")).toBeInTheDocument();
|
||||
|
||||
fireEvent.pointerMove(trigger);
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent("drink water");
|
||||
expect(automation).toHaveTextContent("Triggered automatically · drink water");
|
||||
expect(timestamp.compareDocumentPosition(automation) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders structured CLI app attachments even without the installed catalog", () => {
|
||||
@@ -751,11 +776,12 @@ describe("MessageBubble", () => {
|
||||
it("copies the original mention identifiers rather than display names", async () => {
|
||||
const copy = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(true);
|
||||
try {
|
||||
render(<MessageBubble message={{
|
||||
render(<ThreadMessages messages={[{
|
||||
id: "copy-display-name", role: "user", content: "Please use @drawio",
|
||||
cliApps: [{ name: "drawio", display_name: "Draw.io", category: "diagram", entry_point: "drawio" }],
|
||||
}} />);
|
||||
}]} />);
|
||||
expect(screen.getByTestId("message-cli-mention-drawio")).toHaveTextContent("@Draw.io");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy", exact: true }));
|
||||
await waitFor(() => expect(copy).toHaveBeenCalledWith("Please use @drawio"));
|
||||
} finally {
|
||||
@@ -800,8 +826,9 @@ describe("MessageBubble", () => {
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
render(<MessageBubble message={message} />);
|
||||
const { container } = render(<MessageBlockMenuActions message={message} />);
|
||||
|
||||
menuActions(container);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
|
||||
|
||||
expect(writeText).toHaveBeenCalledWith("I can help with the next step.");
|
||||
@@ -828,14 +855,12 @@ describe("MessageBubble", () => {
|
||||
};
|
||||
|
||||
try {
|
||||
render(<MessageBubble message={message} />);
|
||||
const { container } = render(<MessageBlockMenuActions message={message} />);
|
||||
|
||||
menuActions(container);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
|
||||
|
||||
await waitFor(() => expect(execCommand).toHaveBeenCalledWith("copy"));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument(),
|
||||
);
|
||||
} finally {
|
||||
Reflect.deleteProperty(navigator, "clipboard");
|
||||
Reflect.deleteProperty(document, "execCommand");
|
||||
@@ -861,15 +886,13 @@ describe("MessageBubble", () => {
|
||||
};
|
||||
|
||||
try {
|
||||
render(<MessageBubble message={message} />);
|
||||
const { container } = render(<MessageBlockMenuActions message={message} />);
|
||||
|
||||
menuActions(container);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
|
||||
|
||||
expect(writeText).toHaveBeenCalledWith("Rejected clipboard copy.");
|
||||
await waitFor(() => expect(execCommand).toHaveBeenCalledWith("copy"));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument(),
|
||||
);
|
||||
} finally {
|
||||
Reflect.deleteProperty(navigator, "clipboard");
|
||||
Reflect.deleteProperty(document, "execCommand");
|
||||
@@ -890,67 +913,36 @@ describe("MessageBubble", () => {
|
||||
expect(screen.queryByRole("button", { name: "Copy" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps assistant footer geometry mounted across stream completion", () => {
|
||||
const streaming: UIMessage = {
|
||||
id: "a-footer-stable",
|
||||
role: "assistant",
|
||||
content: "Stable answer",
|
||||
isStreaming: true,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const { container, rerender } = render(<MessageBubble message={streaming} />);
|
||||
|
||||
const reservedFooter = container.querySelector("[data-assistant-footer]");
|
||||
expect(reservedFooter).not.toBeNull();
|
||||
expect(reservedFooter).toHaveAttribute("data-state", "reserved");
|
||||
expect(reservedFooter).toHaveClass("mt-2", "min-h-8", "opacity-0");
|
||||
|
||||
rerender(
|
||||
<MessageBubble
|
||||
message={{
|
||||
...streaming,
|
||||
isStreaming: false,
|
||||
completedAt: Date.now(),
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
const visibleFooter = container.querySelector("[data-assistant-footer]");
|
||||
expect(visibleFooter).toBe(reservedFooter);
|
||||
expect(visibleFooter).toHaveAttribute("data-state", "visible");
|
||||
expect(visibleFooter).toHaveClass("mt-2", "min-h-8", "opacity-100");
|
||||
it("keeps the assistant body mounted when its completed block menu becomes available", () => {
|
||||
const message: UIMessage = { id: "a-stable", role: "assistant", content: "Stable answer",
|
||||
isStreaming: true, createdAt: Date.now() };
|
||||
const { container, rerender } = render(<ThreadMessages messages={[message]} isStreaming />);
|
||||
const body = container.querySelector("[data-assistant-message]");
|
||||
expect(body).toHaveClass("relative", "w-full");
|
||||
rerender(<ThreadMessages messages={[{ ...message, isStreaming: false }]} />);
|
||||
expect(container.querySelector("[data-assistant-message]")).toBe(body);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
|
||||
expect(screen.getByRole("button", { name: "Copy" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("omits footer space when an active answer is no longer the tail", () => {
|
||||
const message: UIMessage = {
|
||||
id: "a-intermediate",
|
||||
role: "assistant",
|
||||
content: "I will keep working.",
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
const { container } = render(
|
||||
<MessageBubble
|
||||
message={message}
|
||||
isTurnStreaming
|
||||
isThreadTail={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.querySelector("[data-assistant-footer]")).not.toBeInTheDocument();
|
||||
it("makes answer actions available after the containing turn completes", () => {
|
||||
const message: UIMessage = { id: "a-intermediate", role: "assistant",
|
||||
content: "I will keep working.", createdAt: Date.now() };
|
||||
const { rerender } = render(<ThreadMessages messages={[message]} isStreaming />);
|
||||
expect(screen.getByText(message.content)).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: "Message actions" })).not.toBeInTheDocument();
|
||||
rerender(<ThreadMessages messages={[message]} />);
|
||||
expect(screen.getByRole("button", { name: "Message actions" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not show copy when showCopyAction is false", () => {
|
||||
const message: UIMessage = {
|
||||
id: "a-mid",
|
||||
role: "assistant",
|
||||
content: "Mid-turn snippet.",
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
render(<MessageBubble message={message} showCopyAction={false} />);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Copy" })).not.toBeInTheDocument();
|
||||
it("keeps timestamp metadata available for a media-only message", () => {
|
||||
const createdAt = Date.UTC(2026, 6, 25, 12, 34, 56);
|
||||
const { container } = render(<MessageBlockMenuActions
|
||||
message={{ id: "a-file", role: "assistant", content: "", createdAt,
|
||||
media: [{ kind: "file", name: "report.csv", url: "/api/media/report.csv" }] }}
|
||||
/>);
|
||||
expect(container.querySelector("time")).toHaveTextContent(formatMessageEndTime(createdAt));
|
||||
expect(container.querySelector("time")).toHaveAttribute("dateTime", new Date(createdAt).toISOString());
|
||||
});
|
||||
|
||||
it("renders trace messages as collapsible tool groups", () => {
|
||||
|
||||
@@ -10,12 +10,7 @@ function renderShell(expanded: boolean) {
|
||||
active={false}
|
||||
expanded={expanded}
|
||||
label="Thought"
|
||||
viewportRef={() => undefined}
|
||||
contentRef={() => undefined}
|
||||
fadeTop={false}
|
||||
fadeBottom={false}
|
||||
onToggle={vi.fn()}
|
||||
onScroll={vi.fn()}
|
||||
>
|
||||
<button type="button">Hidden action</button>
|
||||
</ThinkingReasoningShell>,
|
||||
@@ -23,6 +18,64 @@ function renderShell(expanded: boolean) {
|
||||
}
|
||||
|
||||
describe("ThinkingReasoningShell", () => {
|
||||
it.each([false, true])("shows activity without clipping or edge fades (active: %s)", (active) => {
|
||||
render(
|
||||
<ThinkingReasoningShell
|
||||
active={active}
|
||||
expanded
|
||||
label={active ? "Working" : "Worked"}
|
||||
onToggle={vi.fn()}
|
||||
>
|
||||
{Array.from({ length: 16 }, (_, index) => <div key={index}>Activity {index + 1}</div>)}
|
||||
</ThinkingReasoningShell>
|
||||
);
|
||||
const content = screen.getByTestId("agent-activity-content");
|
||||
expect(content).not.toHaveClass("max-h-[180px]");
|
||||
expect(content).not.toHaveClass("overflow-y-auto");
|
||||
expect(screen.queryByTestId("activity-scroll-fade-top")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("activity-scroll-fade-bottom")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Activity 1")).toBeVisible();
|
||||
expect(screen.getByText("Activity 16")).toBeVisible();
|
||||
});
|
||||
|
||||
it("keeps the same header and content layout when live activity completes", () => {
|
||||
const shell = (active: boolean) => (
|
||||
<ThinkingReasoningShell active={active} expanded label={active ? "Working" : "Worked"}
|
||||
collapseLabel="Collapse activity details" onToggle={vi.fn()}>
|
||||
<p>A processing step</p>
|
||||
</ThinkingReasoningShell>
|
||||
);
|
||||
const view = render(shell(true));
|
||||
const button = screen.getByRole("button", { name: "Working · Collapse activity details" });
|
||||
const content = screen.getByTestId("agent-activity-content");
|
||||
const headerClass = button.className;
|
||||
const contentClass = content.className;
|
||||
expect(button.querySelector("svg")).toHaveClass("lucide-activity");
|
||||
expect(view.container.querySelector("[data-contextual-activity-guide]")).toBeInTheDocument();
|
||||
|
||||
view.rerender(shell(false));
|
||||
|
||||
expect(screen.getByRole("button", { name: "Worked · Collapse activity details" })).toBe(button);
|
||||
expect(button.className).toBe(headerClass);
|
||||
expect(screen.getByTestId("agent-activity-content")).toBe(content);
|
||||
expect(content.className).toBe(contentClass);
|
||||
});
|
||||
|
||||
it("aligns the waiting status with the disclosure shown when details arrive", () => {
|
||||
const shell = (hasDetails: boolean) => (
|
||||
<ThinkingReasoningShell active expanded hasDetails={hasDetails} label="Working"
|
||||
onToggle={vi.fn()}><p>A processing step</p></ThinkingReasoningShell>
|
||||
);
|
||||
const view = render(shell(false));
|
||||
const status = screen.getByRole("status", { name: "Working" });
|
||||
expect(status).toHaveClass("touch-target", "h-7", "px-1.5");
|
||||
expect(status.querySelector("svg")).toHaveClass("lucide-activity");
|
||||
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||
|
||||
view.rerender(shell(true));
|
||||
expect(screen.getByRole("button", { name: "Working" })).toHaveClass(...status.classList);
|
||||
});
|
||||
|
||||
it("mounts details on first expansion and preserves their state across folding", () => {
|
||||
const mounted = vi.fn();
|
||||
function Details() {
|
||||
@@ -31,8 +84,7 @@ describe("ThinkingReasoningShell", () => {
|
||||
}
|
||||
const shell = (expanded: boolean) => (
|
||||
<ThinkingReasoningShell active={false} expanded={expanded} label="Thought"
|
||||
viewportRef={null} contentRef={null} fadeTop={false} fadeBottom={false}
|
||||
onToggle={() => {}} onScroll={() => {}}><Details /></ThinkingReasoningShell>
|
||||
onToggle={() => {}}><Details /></ThinkingReasoningShell>
|
||||
);
|
||||
const view = render(shell(false));
|
||||
expect(mounted).toHaveBeenCalledTimes(0);
|
||||
@@ -46,7 +98,7 @@ describe("ThinkingReasoningShell", () => {
|
||||
it("makes collapsed descendants inert as well as visually hidden", () => {
|
||||
const { rerender } = renderShell(false);
|
||||
const disclosure = screen.getByRole("button", { name: "Thought" });
|
||||
const collapsible = disclosure.nextElementSibling;
|
||||
const collapsible = disclosure.parentElement?.nextElementSibling;
|
||||
|
||||
expect(collapsible).toHaveAttribute("inert");
|
||||
expect(collapsible).toHaveAttribute("aria-hidden", "true");
|
||||
@@ -56,18 +108,14 @@ describe("ThinkingReasoningShell", () => {
|
||||
active={false}
|
||||
expanded
|
||||
label="Thought"
|
||||
viewportRef={() => undefined}
|
||||
contentRef={() => undefined}
|
||||
fadeTop={false}
|
||||
fadeBottom={false}
|
||||
onToggle={vi.fn()}
|
||||
onScroll={vi.fn()}
|
||||
>
|
||||
<button type="button">Hidden action</button>
|
||||
</ThinkingReasoningShell>,
|
||||
);
|
||||
|
||||
expect(disclosure.nextElementSibling).not.toHaveAttribute("inert");
|
||||
expect(disclosure.nextElementSibling).toHaveAttribute("aria-hidden", "false");
|
||||
const expandedCollapsible = disclosure.parentElement?.nextElementSibling;
|
||||
expect(expandedCollapsible).not.toHaveAttribute("inert");
|
||||
expect(expandedCollapsible).toHaveAttribute("aria-hidden", "false");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -16,6 +16,41 @@ afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function openAssistantBlockMenu(root: ParentNode = document): HTMLElement {
|
||||
const row = root.querySelector("[data-assistant-message]")?.closest<HTMLElement>("[data-thread-display-unit]");
|
||||
expect(row).toBeTruthy();
|
||||
return openMessageBlockMenu(row!).trigger;
|
||||
}
|
||||
|
||||
function assistantActionCounts(root: ParentNode = document) {
|
||||
const counts = { copy: 0, fork: 0 };
|
||||
for (const body of root.querySelectorAll("[data-assistant-message]")) {
|
||||
const row = body.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
if (!row.querySelector("[data-message-block-menu-trigger]")) continue;
|
||||
const { menu } = openMessageBlockMenu(row);
|
||||
counts.copy += within(menu).queryAllByRole("button", { name: "Copy", exact: true }).length;
|
||||
counts.fork += within(menu).queryAllByRole("button", { name: "Fork", exact: true }).length;
|
||||
fireEvent.keyDown(menu, { key: "Escape" });
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
function openMessageBlockMenu(root: ParentNode): {
|
||||
trigger: HTMLElement;
|
||||
menu: HTMLElement;
|
||||
} {
|
||||
const trigger = root.querySelector<HTMLElement>("[data-message-block-menu-trigger]");
|
||||
expect(trigger).not.toBeNull();
|
||||
if (trigger?.getAttribute("aria-expanded") === "false") {
|
||||
fireEvent.click(trigger);
|
||||
}
|
||||
const menu = document.querySelector<HTMLElement>(
|
||||
'[data-message-block-menu][data-state="open"]',
|
||||
);
|
||||
expect(menu).not.toBeNull();
|
||||
return { trigger: trigger!, menu: menu! };
|
||||
}
|
||||
|
||||
describe("ThreadMessages", () => {
|
||||
it.each([0, -13_000, -14_000, -15_000, 15_000])(
|
||||
"keeps the optimistic timer through acknowledgement and output with %i ms server clock skew",
|
||||
@@ -74,7 +109,7 @@ describe("ThreadMessages", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Working for 1s" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /^Working for 1s/ })).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -362,11 +397,27 @@ describe("ThreadMessages", () => {
|
||||
.toBeTruthy();
|
||||
|
||||
rerender(<ThreadMessages messages={messages} isStreaming={false} activeTurnId={null} />);
|
||||
const firstRow = firstAnswer.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const finalRow = finalAnswer.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const firstActions = firstRow.querySelector<HTMLElement>("[data-message-block-menu-trigger]")!;
|
||||
const finalActions = finalRow.querySelector<HTMLElement>("[data-message-block-menu-trigger]")!;
|
||||
expect(firstRow).toContainElement(firstActions);
|
||||
expect(finalRow).toContainElement(finalActions);
|
||||
expect(firstActions).not.toBe(finalActions);
|
||||
expect(firstRow).toHaveClass("message-context-hit-area");
|
||||
expect(finalRow).toHaveClass("message-context-hit-area");
|
||||
expect(finalActions).toHaveClass("absolute", "-start-[var(--message-block-trigger-offset)]", "top-0");
|
||||
expect(finalActions.querySelector("[data-message-block-menu-highlight]")).toHaveClass(
|
||||
"h-4",
|
||||
"w-7",
|
||||
"rounded-full",
|
||||
);
|
||||
expect(screen.queryByRole("button", { name: /worked/i })).not.toBeInTheDocument();
|
||||
fireEvent.click(finalActions);
|
||||
const completedActivity = screen.getByRole("button", { name: /worked/i });
|
||||
expect(firstAnswer.compareDocumentPosition(completedActivity) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
.toBeTruthy();
|
||||
expect(completedActivity.compareDocumentPosition(finalAnswer) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
.toBeTruthy();
|
||||
expect(completedActivity).toHaveClass("min-h-[var(--message-block-control-size)]");
|
||||
expect(completedActivity).toHaveAttribute("aria-expanded", "false");
|
||||
expect(document.querySelectorAll("[data-block-context-rail]")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("ignores a completed empty answer frame without splitting contiguous activity", () => {
|
||||
@@ -467,16 +518,20 @@ describe("ThreadMessages", () => {
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
|
||||
const activityShells = screen.getAllByRole("button", { name: /worked/i });
|
||||
const ok = screen.getByText("ok");
|
||||
const final = screen.getByText("finished");
|
||||
expect(activityShells).toHaveLength(2);
|
||||
expect(activityShells[0].compareDocumentPosition(ok) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
.toBeTruthy();
|
||||
expect(ok.compareDocumentPosition(activityShells[1]) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
.toBeTruthy();
|
||||
expect(activityShells[1].compareDocumentPosition(final) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
expect(ok.compareDocumentPosition(final) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
.toBeTruthy();
|
||||
const okRow = ok.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const finalRow = final.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
openMessageBlockMenu(okRow);
|
||||
expect(screen.getByRole("button", { name: /^worked/i })).toBeInTheDocument();
|
||||
const { menu } = openMessageBlockMenu(finalRow);
|
||||
const finalActivity = menu.querySelector<HTMLElement>("[data-message-block-activity-action]")!;
|
||||
expect(finalActivity).toBeInTheDocument();
|
||||
fireEvent.click(finalActivity);
|
||||
expect(screen.getByTestId("agent-activity-content")).toHaveTextContent("Completed First");
|
||||
expect(screen.getByTestId("agent-activity-content")).toHaveTextContent("Completed Second");
|
||||
});
|
||||
|
||||
it("keeps empty frame source counts on the nearest visible unit", () => {
|
||||
@@ -568,7 +623,7 @@ describe("ThreadMessages", () => {
|
||||
expect(removeAllRanges).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("groups consecutive reasoning and tool rows into one timeline before the answer", () => {
|
||||
it("keeps one completed activity row above the final answer", async () => {
|
||||
const messages: UIMessage[] = [
|
||||
{
|
||||
id: "r1",
|
||||
@@ -577,7 +632,7 @@ describe("ThreadMessages", () => {
|
||||
reasoning: "thinking",
|
||||
reasoningStreaming: false,
|
||||
isStreaming: true,
|
||||
createdAt: Date.now(),
|
||||
createdAt: 1_000,
|
||||
},
|
||||
{
|
||||
id: "t1",
|
||||
@@ -585,7 +640,7 @@ describe("ThreadMessages", () => {
|
||||
kind: "trace",
|
||||
content: "search()",
|
||||
traces: ["search()"],
|
||||
createdAt: Date.now(),
|
||||
createdAt: 2_000,
|
||||
},
|
||||
{
|
||||
id: "r2",
|
||||
@@ -594,13 +649,14 @@ describe("ThreadMessages", () => {
|
||||
reasoning: "more thinking",
|
||||
reasoningStreaming: false,
|
||||
isStreaming: true,
|
||||
createdAt: Date.now(),
|
||||
createdAt: 3_000,
|
||||
},
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
content: "final answer",
|
||||
createdAt: Date.now(),
|
||||
latencyMs: 16_000,
|
||||
createdAt: 4_000,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -611,7 +667,381 @@ describe("ThreadMessages", () => {
|
||||
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]).not.toHaveClass("mt-2", "mt-4", "mt-5");
|
||||
expect(rows[1]).toHaveClass("mt-4");
|
||||
expect(rows[1]).not.toHaveClass("mt-4");
|
||||
const answerRow = screen.getByText("final answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const { trigger, menu } = openMessageBlockMenu(answerRow);
|
||||
const disclosure = screen.getByRole("button", { name: "Worked for 16s" });
|
||||
expect(menu).toHaveFocus();
|
||||
expect(menu.querySelector("[data-message-block-copy-action]")).not.toHaveFocus();
|
||||
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
|
||||
expect(disclosure).toHaveAttribute("aria-expanded", "false");
|
||||
expect(disclosure).toHaveAttribute("aria-controls");
|
||||
expect(disclosure).toHaveAttribute("data-message-block-activity-action", "true");
|
||||
expect(disclosure).toHaveClass("min-h-[var(--message-block-control-size)]", "group", "hover:text-foreground");
|
||||
expect(disclosure).not.toHaveClass("hover:bg-muted/60");
|
||||
expect(menu.querySelector("[data-message-block-copy-action]")).toHaveClass(
|
||||
"rounded-control",
|
||||
"h-[var(--message-block-control-size)]",
|
||||
"w-[var(--message-block-action-width)]",
|
||||
);
|
||||
expect(menu.querySelector("[data-message-block-copy-action]")).not.toHaveClass("touch-target");
|
||||
expect(disclosure.querySelector("[data-message-block-activity-icon]")).toHaveClass(
|
||||
"h-[var(--message-block-control-size)]",
|
||||
"w-[var(--message-block-action-width)]",
|
||||
"rounded-control",
|
||||
"group-hover:bg-muted/70",
|
||||
);
|
||||
expect(disclosure.querySelector("svg")).toBeInTheDocument();
|
||||
const toolbar = menu.querySelector("[data-message-block-toolbar]");
|
||||
expect(toolbar).toHaveClass("flex", "flex-wrap", "items-center");
|
||||
expect(toolbar).not.toHaveClass("flex-col");
|
||||
expect(toolbar).toContainElement(menu.querySelector("[data-message-block-copy-action]"));
|
||||
expect(toolbar).toContainElement(disclosure);
|
||||
const timestamp = menu.querySelector<HTMLElement>("[data-message-timestamp]")!;
|
||||
expect(timestamp).toBeInTheDocument();
|
||||
expect(timestamp).toHaveClass("min-h-[var(--message-block-control-size)]");
|
||||
expect(timestamp.parentElement).toHaveClass("border-t", "text-muted-foreground/45");
|
||||
expect(toolbar).not.toContainElement(timestamp);
|
||||
expect(timestamp).not.toHaveAttribute("tabindex");
|
||||
expect(timestamp.querySelector("svg")).not.toBeInTheDocument();
|
||||
expect(disclosure.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
.toBeTruthy();
|
||||
expect(menu).toHaveClass("w-max", "max-w-64", "bg-popover", "rounded-floating", "overflow-y-auto");
|
||||
expect(menu).not.toHaveClass("min-w-[8.5rem]", "bg-popover/95", "rounded-xl");
|
||||
const menuButtons = Array.from(menu.querySelectorAll("button"));
|
||||
expect(menuButtons.length).toBeGreaterThan(1);
|
||||
for (const button of menuButtons) {
|
||||
expect(button.className).toMatch(/(?:min-)?h-\[var\(--message-block-control-size\)\]/);
|
||||
}
|
||||
expect(rows[0].compareDocumentPosition(rows[1]) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
.toBeTruthy();
|
||||
|
||||
fireEvent.click(disclosure);
|
||||
|
||||
expect(trigger).toHaveAttribute("aria-expanded", "false");
|
||||
expect(answerRow.querySelector("[data-contextual-activity]")?.parentElement?.parentElement)
|
||||
.toHaveClass("mb-2");
|
||||
expect(screen.getByTestId("agent-activity-content")).toBeInTheDocument();
|
||||
const collapse = screen.getByRole("button", { name: /Collapse activity details/ });
|
||||
expect(collapse).toHaveAttribute("data-contextual-activity-collapse", "true");
|
||||
expect(collapse.querySelectorAll("svg")).toHaveLength(1);
|
||||
const guide = answerRow.querySelector("[data-contextual-activity-guide]");
|
||||
expect(guide).toBeInTheDocument();
|
||||
expect(guide).toHaveClass("start-[13px]");
|
||||
expect(screen.getByTestId("agent-activity-content")).toHaveClass("ps-6");
|
||||
await waitFor(() => expect(collapse).toHaveFocus());
|
||||
fireEvent.click(collapse);
|
||||
|
||||
expect(answerRow.querySelector("[data-contextual-activity]")?.parentElement?.parentElement)
|
||||
.not.toHaveClass("mb-2");
|
||||
expect(screen.queryByTestId("agent-activity-content")).not.toBeInTheDocument();
|
||||
expect(answerRow.querySelector("[data-contextual-activity-guide]"))
|
||||
.not.toBeInTheDocument();
|
||||
await waitFor(() => expect(trigger).toHaveFocus());
|
||||
});
|
||||
|
||||
it("activates only the hovered visual message block within one logical turn", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{
|
||||
id: "user",
|
||||
role: "user",
|
||||
content: "prompt",
|
||||
createdAt: 500,
|
||||
},
|
||||
{
|
||||
id: "tool-a",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "first command",
|
||||
traces: ["first command"],
|
||||
createdAt: 1_000,
|
||||
},
|
||||
{
|
||||
id: "answer-a",
|
||||
role: "assistant",
|
||||
content: "first answer",
|
||||
createdAt: 2_000,
|
||||
},
|
||||
{
|
||||
id: "tool-b",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "second command",
|
||||
traces: ["second command"],
|
||||
createdAt: 3_000,
|
||||
},
|
||||
{
|
||||
id: "answer-b",
|
||||
role: "assistant",
|
||||
content: "second answer",
|
||||
createdAt: 4_000,
|
||||
},
|
||||
];
|
||||
|
||||
const { container } = render(
|
||||
<ThreadMessages messages={messages} isStreaming={false} />,
|
||||
);
|
||||
const activityA = container.querySelector<HTMLElement>(
|
||||
'[data-thread-display-unit="activity-tool-a"]',
|
||||
)!;
|
||||
const answerA = screen.getByText("first answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const activityB = container.querySelector<HTMLElement>(
|
||||
'[data-thread-display-unit="activity-tool-b"]',
|
||||
)!;
|
||||
const answerB = screen.getByText("second answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
|
||||
expect(activityA).not.toHaveAttribute("data-message-context-block");
|
||||
expect(activityB).not.toHaveAttribute("data-message-context-block");
|
||||
expect(answerA.dataset.messageContextBlock).toBeTruthy();
|
||||
expect(answerB.dataset.messageContextBlock).toBeTruthy();
|
||||
expect(answerA.dataset.messageContextBlock)
|
||||
.not.toBe(answerB.dataset.messageContextBlock);
|
||||
expect(answerA.querySelector("[data-contextual-activity]")).toBeInTheDocument();
|
||||
expect(answerB.querySelector("[data-contextual-activity]")).toBeInTheDocument();
|
||||
expect(answerA).toHaveClass("message-context-hit-area", "relative");
|
||||
expect(answerB).toHaveClass("message-context-hit-area", "relative");
|
||||
|
||||
fireEvent.pointerEnter(answerA, { pointerType: "mouse" });
|
||||
expect(answerA).toHaveAttribute("data-context-block-active", "true");
|
||||
expect(answerB).not.toHaveAttribute("data-context-block-active");
|
||||
|
||||
fireEvent.pointerEnter(answerB, { pointerType: "mouse" });
|
||||
expect(answerA).not.toHaveAttribute("data-context-block-active");
|
||||
expect(answerB).toHaveAttribute("data-context-block-active", "true");
|
||||
|
||||
const answerBTrigger = answerB.querySelector<HTMLElement>("[data-message-block-menu-trigger]")!;
|
||||
expect(answerBTrigger).toHaveClass(
|
||||
"-start-[var(--message-block-trigger-offset)]",
|
||||
"h-[var(--message-block-control-size)]",
|
||||
"w-[var(--message-block-control-size)]",
|
||||
);
|
||||
fireEvent.pointerLeave(answerB, {
|
||||
pointerType: "mouse",
|
||||
relatedTarget: answerBTrigger,
|
||||
});
|
||||
expect(answerB).toHaveAttribute("data-context-block-active", "true");
|
||||
fireEvent.pointerLeave(answerB, { pointerType: "mouse" });
|
||||
expect(answerB).not.toHaveAttribute("data-context-block-active");
|
||||
|
||||
fireEvent.focus(answerA.querySelector<HTMLElement>("[data-message-block-menu-trigger]")!);
|
||||
expect(answerA).toHaveAttribute("data-context-block-active", "true");
|
||||
fireEvent.focus(answerBTrigger);
|
||||
expect(answerA).not.toHaveAttribute("data-context-block-active");
|
||||
expect(answerB).toHaveAttribute("data-context-block-active", "true");
|
||||
});
|
||||
|
||||
it("uses one active visual block across user and assistant messages", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "user-a", role: "user", content: "first prompt", createdAt: 500 },
|
||||
{ id: "answer-a", role: "assistant", content: "first answer", createdAt: 1_000 },
|
||||
{ id: "user-b", role: "user", content: "second prompt", createdAt: 1_500 },
|
||||
];
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
const userA = screen.getByText("first prompt")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const answerA = screen.getByText("first answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const userB = screen.getByText("second prompt")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
|
||||
expect(userA.dataset.messageContextBlock).toBeTruthy();
|
||||
expect(userB.dataset.messageContextBlock).toBeTruthy();
|
||||
expect(userA.dataset.messageContextBlock).not.toBe(answerA.dataset.messageContextBlock);
|
||||
expect(userB.dataset.messageContextBlock).not.toBe(answerA.dataset.messageContextBlock);
|
||||
expect(userA.querySelector("[data-message-block-menu-trigger]")).toBeInTheDocument();
|
||||
expect(userB.querySelector("[data-message-block-menu-trigger]")).toBeInTheDocument();
|
||||
|
||||
fireEvent.pointerEnter(userA, { pointerType: "mouse" });
|
||||
expect(userA).toHaveAttribute("data-context-block-active", "true");
|
||||
expect(answerA).not.toHaveAttribute("data-context-block-active");
|
||||
|
||||
fireEvent.pointerEnter(answerA, { pointerType: "mouse" });
|
||||
expect(userA).not.toHaveAttribute("data-context-block-active");
|
||||
expect(answerA).toHaveAttribute("data-context-block-active", "true");
|
||||
|
||||
fireEvent.pointerEnter(userB, { pointerType: "mouse" });
|
||||
expect(answerA).not.toHaveAttribute("data-context-block-active");
|
||||
expect(userB).toHaveAttribute("data-context-block-active", "true");
|
||||
|
||||
const { menu: userMenu } = openMessageBlockMenu(userA);
|
||||
expect(userMenu.querySelector("[data-message-block-copy-action]")).toBeInTheDocument();
|
||||
expect(userMenu.querySelector("[data-message-block-fork-action]")).not.toBeInTheDocument();
|
||||
fireEvent.focus(userA.querySelector<HTMLElement>("[data-message-block-menu-trigger]")!);
|
||||
expect(userA).toHaveAttribute("data-context-block-active", "true");
|
||||
expect(userB).not.toHaveAttribute("data-context-block-active");
|
||||
});
|
||||
|
||||
it("closes an open block menu after the pointer leaves its block and panel", async () => {
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "user-a", role: "user", content: "first prompt", createdAt: 500 },
|
||||
{ id: "answer-a", role: "assistant", content: "first answer", createdAt: 1_000 },
|
||||
{ id: "user-b", role: "user", content: "second prompt", createdAt: 1_500 },
|
||||
];
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
const userA = screen.getByText("first prompt")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const userB = screen.getByText("second prompt")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
|
||||
fireEvent.pointerEnter(userA, { pointerType: "mouse" });
|
||||
const { menu } = openMessageBlockMenu(userA);
|
||||
expect(menu).toHaveAttribute(
|
||||
"data-message-context-menu-block",
|
||||
userA.dataset.messageContextBlock,
|
||||
);
|
||||
|
||||
fireEvent.pointerLeave(userA, {
|
||||
pointerType: "mouse",
|
||||
relatedTarget: menu,
|
||||
});
|
||||
expect(menu).toHaveAttribute("data-state", "open");
|
||||
expect(userA).toHaveAttribute("data-context-block-active", "true");
|
||||
|
||||
fireEvent.pointerLeave(menu, {
|
||||
pointerType: "mouse",
|
||||
relatedTarget: userB,
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('[data-message-block-menu][data-state="open"]'))
|
||||
.not.toBeInTheDocument();
|
||||
});
|
||||
expect(userA).not.toHaveAttribute("data-context-block-active");
|
||||
expect(userB).toHaveAttribute("data-context-block-active", "true");
|
||||
|
||||
fireEvent.pointerEnter(userA, { pointerType: "mouse" });
|
||||
openMessageBlockMenu(userA);
|
||||
fireEvent.pointerEnter(userB, { pointerType: "mouse" });
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('[data-message-block-menu][data-state="open"]'))
|
||||
.not.toBeInTheDocument();
|
||||
});
|
||||
expect(userB).toHaveAttribute("data-context-block-active", "true");
|
||||
});
|
||||
|
||||
it("clears completed block controls when the pointer enters an ungrouped message", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "user-a", role: "user", content: "first prompt", createdAt: 500 },
|
||||
{
|
||||
id: "tool-a",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "first command",
|
||||
traces: ["first command"],
|
||||
createdAt: 1_000,
|
||||
},
|
||||
{ id: "answer-a", role: "assistant", content: "first answer", createdAt: 2_000 },
|
||||
{ id: "user-b", role: "user", content: "current prompt", createdAt: 3_000 },
|
||||
{
|
||||
id: "answer-b",
|
||||
role: "assistant",
|
||||
content: "current answer",
|
||||
isStreaming: true,
|
||||
createdAt: 4_000,
|
||||
},
|
||||
];
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming activeTurnId={null} />);
|
||||
const completedAnswer = screen.getByText("first answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const currentAnswer = screen.getByText("current answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
|
||||
fireEvent.pointerEnter(completedAnswer, { pointerType: "mouse" });
|
||||
expect(completedAnswer).toHaveAttribute("data-context-block-active", "true");
|
||||
|
||||
fireEvent.pointerEnter(currentAnswer, { pointerType: "mouse" });
|
||||
expect(completedAnswer).not.toHaveAttribute("data-context-block-active");
|
||||
});
|
||||
|
||||
it("keeps only the last tapped message block controls active on touch", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "user-a", role: "user", content: "first prompt", createdAt: 500 },
|
||||
{ id: "answer-a", role: "assistant", content: "first answer", createdAt: 1_000 },
|
||||
{ id: "user-b", role: "user", content: "second prompt", createdAt: 1_500 },
|
||||
{ id: "answer-b", role: "assistant", content: "second answer", createdAt: 2_000 },
|
||||
];
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
const answerA = screen.getByText("first answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const answerB = screen.getByText("second answer")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
|
||||
fireEvent.pointerDown(answerA, { pointerType: "touch" });
|
||||
fireEvent.pointerLeave(answerA, { pointerType: "touch" });
|
||||
expect(answerA).toHaveAttribute("data-context-block-active", "true");
|
||||
|
||||
fireEvent.pointerDown(answerB, { pointerType: "touch" });
|
||||
expect(answerA).not.toHaveAttribute("data-context-block-active");
|
||||
expect(answerB).toHaveAttribute("data-context-block-active", "true");
|
||||
});
|
||||
|
||||
it.each(["mouse", "touch"])("preserves the %s block when previous controls lose focus", (pointerType) => {
|
||||
render(<ThreadMessages messages={[
|
||||
{ id: "user", role: "user", content: "prompt", createdAt: 1 },
|
||||
{ id: "answer", role: "assistant", content: "answer", createdAt: 2 },
|
||||
]} />);
|
||||
const user = screen.getByText("prompt").closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const answer = screen.getByText("answer").closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const trigger = user.querySelector<HTMLElement>("[data-message-block-menu-trigger]")!;
|
||||
fireEvent.focus(trigger);
|
||||
if (pointerType === "touch") {
|
||||
openMessageBlockMenu(user);
|
||||
fireEvent.pointerDown(answer, { pointerType });
|
||||
} else {
|
||||
fireEvent.pointerEnter(answer, { pointerType });
|
||||
fireEvent.pointerDown(answer, { pointerType });
|
||||
}
|
||||
fireEvent.blur(trigger, { relatedTarget: document.body });
|
||||
|
||||
expect(answer).toHaveAttribute("data-context-block-active", "true");
|
||||
expect(user).not.toHaveAttribute("data-context-block-active");
|
||||
expect(document.querySelector('[data-message-block-menu][data-state="open"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("closes the block menu with Escape from a focused copy action", async () => {
|
||||
render(<ThreadMessages messages={[
|
||||
{ id: "answer", role: "assistant", content: "answer", createdAt: 2 },
|
||||
]} />);
|
||||
const answer = screen.getByText("answer").closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const { menu, trigger } = openMessageBlockMenu(answer);
|
||||
const copy = menu.querySelector<HTMLElement>("[data-message-block-copy-action]")!;
|
||||
act(() => copy.focus());
|
||||
expect(copy).toHaveFocus();
|
||||
fireEvent.keyDown(copy, { key: "Escape" });
|
||||
await waitFor(() => expect(menu).not.toBeInTheDocument());
|
||||
expect(trigger).toHaveAttribute("aria-expanded", "false");
|
||||
});
|
||||
|
||||
it("clears keyboard context when focus leaves and no pointer owns a block", () => {
|
||||
render(<ThreadMessages messages={[
|
||||
{ id: "answer", role: "assistant", content: "answer", createdAt: 2 },
|
||||
]} />);
|
||||
const answer = screen.getByText("answer").closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const trigger = answer.querySelector<HTMLElement>("[data-message-block-menu-trigger]")!;
|
||||
fireEvent.focus(trigger);
|
||||
expect(answer).toHaveAttribute("data-context-block-active", "true");
|
||||
fireEvent.blur(trigger, { relatedTarget: document.body });
|
||||
expect(answer).not.toHaveAttribute("data-context-block-active");
|
||||
});
|
||||
|
||||
it.each(["cron", "local_trigger", "trigger"])("preserves %s provenance as static menu metadata", (kind) => {
|
||||
render(<ThreadMessages messages={[
|
||||
{ id: "answer", role: "assistant", content: "automated answer", createdAt: 2,
|
||||
source: { kind, label: "Review schedule" } },
|
||||
]} />);
|
||||
const answer = screen.getByText("automated answer").closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const { menu } = openMessageBlockMenu(answer);
|
||||
const metadata = menu.querySelector<HTMLElement>("[data-message-block-metadata]")!;
|
||||
expect(metadata).toHaveTextContent("Triggered automatically · Review schedule");
|
||||
expect(metadata.querySelector("time[datetime]")).toBeInTheDocument();
|
||||
expect(metadata.querySelector("button, svg, [tabindex]")).toBeNull();
|
||||
expect(metadata).toBe(menu.querySelector("[data-message-block-menu-actions]")?.lastElementChild);
|
||||
});
|
||||
|
||||
it("renders a fork boundary divider after the copied history", () => {
|
||||
@@ -1018,9 +1448,15 @@ describe("ThreadMessages", () => {
|
||||
expect(units[1].message).not.toHaveProperty("reasoning");
|
||||
}
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
const { container } = render(
|
||||
<ThreadMessages messages={messages} isStreaming={false} />,
|
||||
);
|
||||
expect(screen.queryByRole("button", { name: /^thinking$/i })).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Worked for 9s")).toBeInTheDocument();
|
||||
openAssistantBlockMenu(container);
|
||||
const disclosure = screen.getByRole("button", { name: "Worked for 9s" });
|
||||
expect(disclosure).toHaveAttribute("aria-expanded", "false");
|
||||
fireEvent.click(disclosure);
|
||||
expect(screen.getByTestId("agent-activity-content")).toBeInTheDocument();
|
||||
expect(screen.getByText("final answer")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1056,9 +1492,14 @@ describe("ThreadMessages", () => {
|
||||
|
||||
expect(units[0].type === "activity" ? units[0].turnLatencyMs : undefined).toBe(20_000);
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
expect(screen.getByText("Worked for 20s")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Worked for 3s")).not.toBeInTheDocument();
|
||||
const { container } = render(
|
||||
<ThreadMessages messages={messages} isStreaming={false} />,
|
||||
);
|
||||
openAssistantBlockMenu(container);
|
||||
expect(screen.getByRole("button", { name: "Worked for 20s" }))
|
||||
.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Worked for 3s" }))
|
||||
.not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps a streamed answer outside late activity when the prompt snapshot is absent", () => {
|
||||
@@ -1112,7 +1553,7 @@ describe("ThreadMessages", () => {
|
||||
expect(answer.compareDocumentPosition(liveActivity) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
|
||||
it("keeps late activity after a completed assistant answer", () => {
|
||||
it("summarizes late activity above the completed assistant answer", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{
|
||||
id: "r1",
|
||||
@@ -1156,12 +1597,13 @@ describe("ThreadMessages", () => {
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
|
||||
const answer = screen.getByText("Hong Kong is hot today.");
|
||||
openMessageBlockMenu(answer.closest<HTMLElement>("[data-thread-display-unit]")!);
|
||||
const laterActivity = screen.getAllByRole("button", { name: /worked/i }).at(-1);
|
||||
expect(laterActivity).toBeTruthy();
|
||||
expect(answer.compareDocumentPosition(laterActivity!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(laterActivity).toHaveAttribute("data-message-block-activity-action", "true");
|
||||
});
|
||||
|
||||
it("keeps completed web-search activity on both sides of an answer", () => {
|
||||
it("folds completed web-search activity into one row above the answer", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{
|
||||
id: "user",
|
||||
@@ -1197,11 +1639,11 @@ describe("ThreadMessages", () => {
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
|
||||
const activities = screen.getAllByRole("button", { name: /worked/i });
|
||||
const answer = screen.getByText("知道,IEM Cologne Major 2026 今天开打了。");
|
||||
expect(activities).toHaveLength(2);
|
||||
expect(activities[0].compareDocumentPosition(answer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(answer.compareDocumentPosition(activities[1]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
openMessageBlockMenu(answer.closest<HTMLElement>("[data-thread-display-unit]")!);
|
||||
const activities = screen.getAllByRole("button", { name: /worked/i });
|
||||
expect(activities).toHaveLength(1);
|
||||
expect(activities[0]).toHaveAttribute("data-message-block-activity-action", "true");
|
||||
});
|
||||
|
||||
it("preserves a completed prior turn's order while the next turn is streaming", () => {
|
||||
@@ -1376,10 +1818,15 @@ describe("ThreadMessages", () => {
|
||||
},
|
||||
];
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
const { container } = render(
|
||||
<ThreadMessages messages={messages} isStreaming={false} />,
|
||||
);
|
||||
|
||||
expect(screen.getByText("Worked for 15s")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Worked for 0s")).not.toBeInTheDocument();
|
||||
openAssistantBlockMenu(container);
|
||||
expect(screen.getByRole("button", { name: "Worked for 15s" }))
|
||||
.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Worked for 0s" }))
|
||||
.not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps answer slices on either side of activity in generation order", () => {
|
||||
@@ -1431,8 +1878,7 @@ describe("ThreadMessages", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getAllByRole("button", { name: "Copy" })).toHaveLength(2);
|
||||
expect(screen.getAllByRole("button", { name: "Fork" })).toHaveLength(1);
|
||||
expect(assistantActionCounts(document)).toEqual({ copy: 2, fork: 1 });
|
||||
expect(screen.getByText("starting…").closest("[data-testid='activity-model-message']")).toBeNull();
|
||||
expect(screen.getByText("final reply").closest("[data-testid='activity-model-message']")).toBeNull();
|
||||
});
|
||||
@@ -1489,6 +1935,10 @@ describe("ThreadMessages", () => {
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
expect(screen.getByText("result.csv")).toBeInTheDocument();
|
||||
const ownerRow = screen.getByText("result.csv")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
openAssistantBlockMenu(ownerRow);
|
||||
expect(screen.getByRole("button", { name: "Worked" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides current turn actions until turn_end", () => {
|
||||
@@ -1530,18 +1980,17 @@ describe("ThreadMessages", () => {
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const finalAnswer = screen.getByText("second answer slice")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
expect(firstAnswer.querySelector("[data-assistant-footer]")).not.toBeInTheDocument();
|
||||
expect(finalAnswer.querySelector("[data-assistant-footer]"))
|
||||
.toHaveAttribute("data-state", "reserved");
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Copy"]')).toHaveLength(1);
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Fork"]')).toHaveLength(1);
|
||||
expect(firstAnswer.querySelector("[data-message-block-menu-trigger]"))
|
||||
.not.toBeInTheDocument();
|
||||
expect(finalAnswer.querySelector("[data-message-block-menu-trigger]"))
|
||||
.not.toBeInTheDocument();
|
||||
expect(assistantActionCounts(container)).toEqual({ copy: 1, fork: 1 });
|
||||
|
||||
rerender(<ThreadMessages {...props} isStreaming={false} activeTurnId={null} />);
|
||||
|
||||
expect(firstAnswer.querySelector("[data-assistant-footer]"))
|
||||
.toHaveAttribute("data-state", "visible");
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Copy"]')).toHaveLength(3);
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Fork"]')).toHaveLength(2);
|
||||
expect(firstAnswer.querySelector("[data-message-block-menu-trigger]"))
|
||||
.toBeInTheDocument();
|
||||
expect(assistantActionCounts(container)).toEqual({ copy: 3, fork: 2 });
|
||||
});
|
||||
|
||||
it("keeps active turn actions hidden across guidance and failed user rows", () => {
|
||||
@@ -1570,8 +2019,7 @@ describe("ThreadMessages", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Copy"]')).toHaveLength(1);
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Fork"]')).toHaveLength(1);
|
||||
expect(assistantActionCounts(container)).toEqual({ copy: 1, fork: 1 });
|
||||
});
|
||||
|
||||
it("only hides the active assistant-only automation turn", () => {
|
||||
@@ -1593,8 +2041,7 @@ describe("ThreadMessages", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Copy"]')).toHaveLength(1);
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Fork"]')).toHaveLength(0);
|
||||
expect(assistantActionCounts(container)).toEqual({ copy: 1, fork: 0 });
|
||||
});
|
||||
|
||||
it("falls back to the latest user boundary for untagged active slices", () => {
|
||||
@@ -1610,10 +2057,7 @@ describe("ThreadMessages", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.querySelector('[data-assistant-footer] [aria-label="Copy"]'))
|
||||
.not.toBeInTheDocument();
|
||||
expect(container.querySelector('[data-assistant-footer] [aria-label="Fork"]'))
|
||||
.not.toBeInTheDocument();
|
||||
expect(assistantActionCounts(container)).toEqual({ copy: 0, fork: 0 });
|
||||
});
|
||||
|
||||
it("falls back to the latest user boundary while the active turn id is pending", () => {
|
||||
@@ -1631,10 +2075,7 @@ describe("ThreadMessages", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Copy"]'))
|
||||
.toHaveLength(1);
|
||||
expect(container.querySelectorAll('[data-assistant-footer] [aria-label="Fork"]'))
|
||||
.toHaveLength(1);
|
||||
expect(assistantActionCounts(container)).toEqual({ copy: 1, fork: 1 });
|
||||
});
|
||||
|
||||
it("projects adjacent assistant text slices into one answer", () => {
|
||||
@@ -1642,8 +2083,10 @@ describe("ThreadMessages", () => {
|
||||
{ id: "a1", role: "assistant", content: "part one", createdAt: 1 },
|
||||
{ id: "a2", role: "assistant", content: "part two", createdAt: 2 },
|
||||
];
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
expect(screen.getAllByRole("button", { name: "Copy" })).toHaveLength(1);
|
||||
const { container } = render(
|
||||
<ThreadMessages messages={messages} isStreaming={false} />,
|
||||
);
|
||||
expect(assistantActionCounts(container).copy).toBe(1);
|
||||
expect(screen.getByText("part one")).toBeInTheDocument();
|
||||
expect(screen.getByText("part two")).toBeInTheDocument();
|
||||
});
|
||||
@@ -1672,7 +2115,10 @@ describe("ThreadMessages", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getAllByRole("button", { name: "Fork" }).at(-1)!);
|
||||
const answerRow = screen.getByText("answer two")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
openMessageBlockMenu(answerRow);
|
||||
fireEvent.click(document.querySelector("[data-message-block-fork-action]")!);
|
||||
expect(onForkFromMessage).toHaveBeenCalledWith(2);
|
||||
});
|
||||
|
||||
|
||||
@@ -22,6 +22,13 @@ import { canonicalThreadPayload } from "./thread-test-payload";
|
||||
const HERO_GREETING_PATTERN =
|
||||
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
|
||||
|
||||
async function openMessageActions(text: string): Promise<HTMLElement> {
|
||||
const message = await screen.findByText(text);
|
||||
const block = message.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
fireEvent.click(within(block).getByRole("button", { name: "Message actions" }));
|
||||
return screen.findByRole("dialog", { name: "Message actions" });
|
||||
}
|
||||
|
||||
function makeClient() {
|
||||
const errorHandlers = new Set<(err: StreamError) => void>();
|
||||
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
|
||||
@@ -532,7 +539,8 @@ describe("ThreadShell", () => {
|
||||
/>,
|
||||
));
|
||||
|
||||
const activity = await screen.findByRole("button", { name: /Worked/ });
|
||||
const menu = await openMessageActions("done");
|
||||
const activity = within(menu).getByRole("button", { name: /Worked/ });
|
||||
fireEvent.click(activity);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Full activity details could not be loaded.",
|
||||
@@ -544,9 +552,9 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
|
||||
await waitFor(() => expect(document.body).toHaveTextContent("echo full"));
|
||||
|
||||
const resolvedActivity = screen.getByRole("button", { name: /Worked/ });
|
||||
fireEvent.click(resolvedActivity);
|
||||
fireEvent.click(resolvedActivity);
|
||||
fireEvent.click(screen.getByRole("button", { name: /Collapse activity details/ }));
|
||||
const reopenedMenu = await openMessageActions("done");
|
||||
fireEvent.click(within(reopenedMenu).getByRole("button", { name: /Worked/ }));
|
||||
await act(async () => Promise.resolve());
|
||||
expect(detailCalls).toBe(2);
|
||||
});
|
||||
@@ -584,7 +592,7 @@ describe("ThreadShell", () => {
|
||||
/>,
|
||||
);
|
||||
const { rerender } = render(view("trace-failure-a"));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
|
||||
fireEvent.click(within(await openMessageActions("done-a")).getByRole("button", { name: /Worked/ }));
|
||||
|
||||
rerender(view("trace-failure-b"));
|
||||
await screen.findByText("done-b");
|
||||
@@ -624,7 +632,7 @@ describe("ThreadShell", () => {
|
||||
/>,
|
||||
);
|
||||
const { rerender } = render(view("visible-failure-a"));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
|
||||
fireEvent.click(within(await openMessageActions("failed-a")).getByRole("button", { name: /Worked/ }));
|
||||
expect(await screen.findByRole("alert")).toBeInTheDocument();
|
||||
|
||||
rerender(view("visible-failure-b"));
|
||||
@@ -873,7 +881,8 @@ describe("ThreadShell", () => {
|
||||
/>,
|
||||
));
|
||||
|
||||
await waitFor(() => expect(screen.getAllByRole("button", { name: "Copy" })).toHaveLength(1));
|
||||
const oldMenu = await openMessageActions("old automation");
|
||||
expect(within(oldMenu).getByRole("button", { name: "Copy" })).toBeInTheDocument();
|
||||
const turnId = "turn-automation";
|
||||
const startedAt = Date.now() / 1000;
|
||||
act(() => client._emitChat("assistant-only-actions", {
|
||||
@@ -883,7 +892,7 @@ describe("ThreadShell", () => {
|
||||
started_at: startedAt,
|
||||
turn_id: turnId,
|
||||
}));
|
||||
expect(screen.getAllByRole("button", { name: "Copy" })).toHaveLength(1);
|
||||
expect(screen.getAllByRole("button", { name: "Message actions" })).toHaveLength(1);
|
||||
|
||||
act(() => client._emitChat("assistant-only-actions", {
|
||||
event: "message",
|
||||
@@ -892,14 +901,18 @@ describe("ThreadShell", () => {
|
||||
turn_id: turnId,
|
||||
}));
|
||||
await waitFor(() => expect(screen.getByText("new automation")).toBeInTheDocument());
|
||||
expect(screen.getAllByRole("button", { name: "Copy" })).toHaveLength(1);
|
||||
expect(screen.getAllByRole("button", { name: "Message actions" })).toHaveLength(1);
|
||||
expect(screen.getByText("new automation").closest("[data-thread-display-unit]"))
|
||||
.not.toHaveAttribute("data-message-context-block");
|
||||
|
||||
act(() => client._emitChat("assistant-only-actions", {
|
||||
event: "turn_end",
|
||||
chat_id: "assistant-only-actions",
|
||||
turn_id: turnId,
|
||||
}));
|
||||
await waitFor(() => expect(screen.getAllByRole("button", { name: "Copy" })).toHaveLength(2));
|
||||
await waitFor(() => expect(screen.getAllByRole("button", { name: "Message actions" })).toHaveLength(2));
|
||||
const newMenu = await openMessageActions("new automation");
|
||||
expect(within(newMenu).getByRole("button", { name: "Copy" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not navigate away when clicking the chat title", async () => {
|
||||
@@ -1177,6 +1190,7 @@ describe("ThreadShell", () => {
|
||||
).not.toHaveAttribute("data-fallback");
|
||||
});
|
||||
expect(screen.getByText("Default")).toBeInTheDocument();
|
||||
await openMessageActions("Reply from the actual provider");
|
||||
expect(await screen.findByText("backup")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -2060,10 +2074,8 @@ describe("ThreadShell", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const targetText = await screen.findByText("answer 100");
|
||||
fireEvent.click(within(targetText.closest(".w-full") as HTMLElement).getByRole("button", {
|
||||
name: "Fork",
|
||||
}));
|
||||
const menu = await openMessageActions("answer 100");
|
||||
fireEvent.click(within(menu).getByRole("button", { name: "Fork" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onForkChat).toHaveBeenCalledWith("long-chat", 101),
|
||||
|
||||
@@ -266,6 +266,27 @@ describe("ThreadViewport", () => {
|
||||
expect(takeUserControl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("yields scroll control before expanding activity from a portaled message menu", () => {
|
||||
const takeUserControl = vi.spyOn(ThreadMotionCoordinator.prototype, "takeUserControl");
|
||||
render(
|
||||
<ThreadViewport
|
||||
messages={[
|
||||
{ id: "reasoning", role: "assistant", content: "", reasoning: "A completed thought", createdAt: 1 },
|
||||
{ id: "answer", role: "assistant", content: "Finished answer", createdAt: 2 },
|
||||
]}
|
||||
isStreaming={false}
|
||||
composer={<div>composer</div>}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
|
||||
const disclosure = screen.getByRole("button", { name: "Worked" });
|
||||
expect(screen.getByTestId("thread-message-region")).not.toContainElement(disclosure);
|
||||
takeUserControl.mockClear();
|
||||
fireEvent.click(disclosure);
|
||||
expect(takeUserControl).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByRole("button", { name: /Collapse activity details/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("top-aligns short threads in the message rendering area", () => {
|
||||
render(
|
||||
<ThreadViewport
|
||||
@@ -305,12 +326,16 @@ describe("ThreadViewport", () => {
|
||||
expect(screen.getByTestId("thread-message-region")).toHaveClass("min-w-0");
|
||||
});
|
||||
|
||||
it("uses the shared content-column width for conversation messages", () => {
|
||||
it("keeps message hit rows full width and constrains content inside each row", () => {
|
||||
render(<ThreadViewport messages={messages} isStreaming={false} composer={<div>composer</div>} />);
|
||||
|
||||
expect(screen.getByTestId("thread-message-region").firstElementChild).toHaveClass(
|
||||
"mx-auto", "w-full", "max-w-[var(--content-column-width)]",
|
||||
);
|
||||
const region = screen.getByTestId("thread-message-region");
|
||||
expect(region.firstElementChild).toHaveClass("w-full");
|
||||
expect(region.firstElementChild).not.toHaveClass("max-w-[var(--content-column-width)]");
|
||||
expect(region.parentElement).not.toHaveClass("max-w-[64rem]");
|
||||
const rows = region.querySelectorAll("[data-thread-display-unit]");
|
||||
expect(rows.length).toBeGreaterThan(0);
|
||||
for (const row of rows) expect(row).toHaveClass("thread-message-row");
|
||||
});
|
||||
|
||||
it("top-aligns a short active turn while the agent is responding", () => {
|
||||
|
||||
Reference in new issue
Block a user