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}
|
||||
|
||||
Reference in new issue
Block a user