feat(webui): show the latest activity in collapsed turns

This commit is contained in:
Xubin Ren committed 2026-11-14 14:37:30 +08:00
1 parent 5e9810c1ad
commit 83ad917d6b
26 files changed
+476 -115

No files matched your search

@@ -11,7 +11,6 @@ import {
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
@@ -26,6 +25,7 @@ import {
compactActivityPath,
formatActivityTarget,
redactShellCommand,
safeActivityDetail,
} from "@/components/thread/activity/activity-text";
import { FileEditGroup, type FileEditSummary } from "@/components/thread/activity/FileEditRow";
import { GenericToolRun } from "@/components/thread/activity/GenericToolRun";
@@ -37,14 +37,16 @@ import {
type GenericToolStatus,
parseGenericToolTrace,
} from "@/components/thread/activity/generic-tool-model";
import { LatestActivityWheel } from "@/components/thread/activity/LatestActivityWheel";
import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";
import { compactReasoningPreview } from "@/components/thread/activity/reasoning-preview";
import { describeMcpActivity } from "@/components/thread/activity/mcp-activity-model";
import { ThinkingReasoningShell } from "@/components/thread/activity/ThinkingReasoningShell";
import { WebActivityRow } from "@/components/thread/activity/WebActivityRow";
import {
describeTraceLine,
} from "@/components/thread/activity/trace-activity-model";
import { WebSearchRun } from "@/components/thread/activity/WebSearchRun";
import { WebSearchActionRow, WebSearchRun } from "@/components/thread/activity/WebSearchRun";
import { webSearchRunsByTraceLine } from "@/components/thread/activity/web-search-model";
import {
isReasoningOnlyAssistant,
@@ -279,20 +281,12 @@ function FoldedAgentActivity({
fileCount,
} = countActivity(activityMessages, fileEdits, cliRuns, mcpRuns);
const [userToggledOuter, setUserToggledOuter] = useState(false);
const [outerOpenLocal, setOuterOpenLocal] = useState(false);
const [completionHoldOpen, setCompletionHoldOpen] = useState(false);
const [outerOpenLocal, setOuterOpenLocal] = useState<boolean>();
const [failedTraceDetailKey, setFailedTraceDetailKey] = useState<string | null>(null);
const [now, setNow] = useState(() => Date.now());
const wasTurnStreamingRef = useRef(isTurnStreaming);
const wasTurnStreaming = wasTurnStreamingRef.current;
const outerExpanded = expanded ?? (
userToggledOuter
? outerOpenLocal
: activityMode === "expanded" || isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming)
);
const outerExpanded = expanded ?? outerOpenLocal ?? (activityMode === "expanded");
useEffect(() => {
setUserToggledOuter(false);
setOuterOpenLocal(undefined);
}, [activityMode]);
const deferredTraceRefs = useMemo(
() => Array.from(new Set(
@@ -327,6 +321,11 @@ function FoldedAgentActivity({
startedAtMs,
);
const activityDuration = formatActivityDuration(durationMs);
const showActivityPreview = isTurnStreaming && hasVisibleActivity && !outerExpanded && !hideHeader && !retryStatus;
const workingLabel = (duration: string) => t("message.activityWorkingFor", {
duration,
defaultValue: "Working for {{duration}}",
});
const isCompletedDisclosure = !isTurnStreaming && expanded !== undefined;
const retryError = retryStatus?.error_kind === "connection"
? t("message.retryConnection", { defaultValue: "Connection failed" })
@@ -357,10 +356,7 @@ function FoldedAgentActivity({
defaultValue: "{{error}} Retrying",
})
: isTurnStreaming
? t("message.activityWorkingFor", {
duration: activityDuration,
defaultValue: "Working for {{duration}}",
})
? workingLabel(activityDuration)
: durationMs <= 0
? t("message.activityWorked", { defaultValue: "Worked" })
: t("message.activityWorkedFor", {
@@ -373,9 +369,7 @@ function FoldedAgentActivity({
onExpandedChange?.(!expanded);
return;
}
const nextOpen = userToggledOuter ? !outerOpenLocal : !outerExpanded;
setUserToggledOuter(true);
setOuterOpenLocal(nextOpen);
setOuterOpenLocal(!outerExpanded);
};
useEffect(() => {
@@ -391,19 +385,6 @@ function FoldedAgentActivity({
return () => window.clearInterval(interval);
}, [isTurnStreaming, pageVisible, threadVisible]);
useEffect(() => {
const wasStreaming = wasTurnStreamingRef.current;
wasTurnStreamingRef.current = isTurnStreaming;
if (isTurnStreaming) {
setCompletionHoldOpen(false);
return undefined;
}
if (!wasStreaming || userToggledOuter) return undefined;
setCompletionHoldOpen(true);
const timeout = window.setTimeout(() => setCompletionHoldOpen(false), 300);
return () => window.clearTimeout(timeout);
}, [isTurnStreaming, userToggledOuter]);
if (!hasVisibleActivity && !isTurnStreaming) return null;
if (hasOnlyFileActivity && expanded === undefined) {
@@ -428,6 +409,16 @@ function FoldedAgentActivity({
collapseLabel={t("message.collapseActivity")}
contentId={detailsId}
label={activityLabel}
reservedLabel={showActivityPreview ? workingLabel("00m 00s") : undefined}
preview={showActivityPreview ? (
<CollapsedActivityPreview
messages={activityMessages}
fileEditsByMessage={fileEditsByMessage}
cliAppsByName={cliAppsByName}
mcpPresetsByName={mcpPresetsByName}
visible={pageVisible && threadVisible}
/>
) : undefined}
hasDetails={hasVisibleActivity}
onToggle={toggleOuter}
>
@@ -511,6 +502,62 @@ function traceLines(message: UIMessage): string[] {
return message.content.trim() ? [message.content] : [];
}
const CollapsedActivityPreview = memo(function CollapsedActivityPreview({
messages, fileEditsByMessage, cliAppsByName, mcpPresetsByName, visible,
}: {
messages: UIMessage[];
fileEditsByMessage: Map<string, FileEditSummary[]>;
cliAppsByName: Map<string, CliAppInfo>;
mcpPresetsByName: Map<string, McpPresetInfo>;
visible: boolean;
}) {
const row = useMemo(() => {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (isReasoningOnlyAssistant(message)) {
return <ReasoningRow key={message.id} text={message.reasoning ?? ""} streaming={!!message.reasoningStreaming} />;
}
if (message.activityKind === "model" && message.content.trim()) {
return <ActivityStep key={message.id} icon={Layers} label={safeActivityDetail(compactReasoningPreview(message.content))} />;
}
if (message.kind !== "trace") continue;
const edit = fileEditsByMessage.get(message.id)?.at(-1);
if (edit) return <FileEditGroup key={edit.key} edits={[edit]} displayMode="summary" />;
const entry = activityTraceEntries(message).at(-1);
const event = entry?.sessionEvent ?? message.toolEvents?.at(-1);
const line = entry?.line ?? formatToolCallTrace(event);
if (!line?.trim()) continue;
const traceKey = canonicalToolTrace(line);
const events = message.toolEvents ?? [];
const matchingEvent = entry?.sessionEvent ?? [...events].reverse().find((item) => {
const trace = formatToolCallTrace(item);
return trace !== null && canonicalToolTrace(trace) === traceKey;
});
const key = `${message.id}:${matchingEvent?.call_id ?? traceKey}`;
const search = webSearchRunsByTraceLine(events).get(traceKey);
if (search) {
const source = search.sources.at(-1);
if (source) return <WebActivityRow key={`${key}:${source.href}`} {...source} />;
return <WebSearchActionRow key={key} run={search} turnActive />;
}
if (matchingEvent && toolEventName(matchingEvent) === "exec_session") {
return <ExecSessionRow key={key} event={matchingEvent} turnActive />;
}
const state = genericToolStateByTraceLine(message).get(traceKey);
const cli = cliRunMapByTraceLine(message).get(traceKey) ?? parseCliRunTrace(line, state?.status);
if (cli) return <CliRunRow key={key} run={cli} active app={cliAppsByName.get(cli.name.toLowerCase())} />;
const mcp = mcpRunMapByTraceLine(message).get(traceKey) ?? parseMcpRunTrace(line, state?.status);
if (mcp) return <McpRunRow key={key} run={mcp} active preset={mcpPresetsByName.get(mcp.presetName.toLowerCase())} />;
const trace = parseGenericToolTrace(line);
if (trace) return <GenericToolRun key={key} items={[{ trace, status: state?.status ?? "running", error: state?.error }]} />;
return <ActivityTraceRow key={key} line={line} active state={state} />;
}
return null;
}, [messages, fileEditsByMessage, cliAppsByName, mcpPresetsByName]);
return row ? <LatestActivityWheel row={row} visible={visible} /> : null;
});
const ActivityMessageTimeline = memo(function ActivityMessageTimeline({
messages,
active,
@@ -52,6 +52,7 @@ export function ActivityStep({
const textLabel = typeof label === "string" ? [label, detail].filter(Boolean).join("\n") : undefined;
const activityMarker = (
<span
data-activity-marker=""
className={cn(
"flex h-5 w-[1.125rem] shrink-0 items-start justify-center pt-[3px]",
markerLabel && ["rounded-sm", formControlFocusClassName],
@@ -0,0 +1,51 @@
import { useLayoutEffect, useRef, useState, type ReactElement } from "react";
import { motion, useReducedMotion } from "motion/react";
const SLOW = 0.24;
const FAST = 0.12;
const rowClass = "flex h-6 min-w-0 items-center [&>*]:w-full";
export function LatestActivityWheel({ row, visible }: { row: ReactElement; visible: boolean }) {
const reducedMotion = useReducedMotion();
const canRoll = visible && !reducedMotion;
const last = useRef({ row, time: -Infinity });
const [frame, setFrame] = useState<{ key: ReactElement["key"]; previous?: ReactElement; duration?: number }>({ key: row.key });
useLayoutEffect(() => {
const previous = last.current;
if (!canRoll) {
last.current = { row, time: -Infinity };
setFrame({ key: row.key });
} else if (previous.row.key !== row.key) {
const time = performance.now();
setFrame({ previous: previous.row, key: row.key, duration: time - previous.time < 280 ? FAST : SLOW });
last.current = { row, time };
} else {
// A tool's status or label can change without advancing the wheel.
last.current = { ...previous, row };
}
}, [canRoll, row]);
const outgoing = canRoll && frame.key === row.key ? frame.previous : undefined;
return (
<div
aria-hidden
{...{ inert: "" }}
data-testid="latest-activity-wheel"
className="relative h-6 min-w-0 overflow-hidden pe-1 max-sm:ms-6 sm:flex-1 [mask-image:linear-gradient(transparent,black_10%,black_90%,transparent)] [&_[data-activity-marker]]:self-center [&_[data-activity-marker]]:items-center [&_[data-activity-marker]]:pt-0"
>
{canRoll ? <motion.div
key={frame.key}
initial={outgoing ? { y: "100%" } : false}
animate={{ y: 0 }}
transition={{ duration: outgoing ? frame.duration : 0, ease: [0.22, 0.7, 0.26, 1] }}
onAnimationComplete={() => {
if (outgoing) setFrame((current) => current === frame ? { key: frame.key } : current);
}}
>
{outgoing ? <div className={`absolute inset-x-0 bottom-full ${rowClass}`}>{outgoing}</div> : null}
<div className={rowClass}>{row}</div>
</motion.div> : <div className={rowClass}>{row}</div>}
</div>
);
}
@@ -11,6 +11,8 @@ interface ThinkingReasoningShellProps {
collapseLabel?: string;
contentId?: string;
label: string;
reservedLabel?: string;
preview?: ReactNode;
children: ReactNode;
hasDetails?: boolean;
onToggle: () => void;
@@ -24,6 +26,8 @@ export function ThinkingReasoningShell({
collapseLabel,
contentId: providedContentId,
label,
reservedLabel,
preview,
children,
hasDetails = true,
onToggle,
@@ -32,21 +36,30 @@ export function ThinkingReasoningShell({
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 headerClassName = cn(
"touch-target inline-flex h-7 min-w-0 items-center gap-1.5 rounded-md px-1.5",
preview && "max-sm:self-start",
);
const labelClassName = "min-w-0 truncate text-[12px] font-normal leading-4";
const headerLabel = (
<span
data-sheen-text={active ? label : undefined}
className={cn(labelClassName, "text-muted-foreground", active && "streaming-text-sheen")}
>
{label}
</span>
);
const headerContent = (
<>
<Activity className={cn("h-3.5 w-3.5 shrink-0", active ? "activity-current" : "text-muted-foreground")} strokeWidth={1.5} aria-hidden>
{active ? <path className="activity-current-trace" pathLength={100} d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" /> : null}
</Activity>
<span
data-sheen-text={active ? label : undefined}
className={cn(
"min-w-0 truncate text-[12px] font-normal leading-4 text-muted-foreground",
active && "streaming-text-sheen",
)}
>
{label}
</span>
{reservedLabel ? (
<span className="grid min-w-0 tabular-nums [&>span]:col-start-1 [&>span]:row-start-1">
{headerLabel}
<span className={cn(labelClassName, "invisible")} aria-hidden>{reservedLabel}</span>
</span>
) : headerLabel}
</>
);
return (
@@ -57,7 +70,10 @@ export function ThinkingReasoningShell({
data-block-context-rail={contextual && showHeader || undefined}
data-block-context-expanded={contextual && expanded ? true : undefined}
>
{showHeader ? <div className="flex min-h-7 items-center gap-1.5">
{showHeader ? <div className={cn(
"flex min-h-7 items-center gap-1.5",
preview && "max-sm:flex-col max-sm:items-stretch max-sm:gap-0",
)}>
{hasDetails ? (
<button
type="button"
@@ -87,6 +103,7 @@ export function ThinkingReasoningShell({
{headerContent}
</div>
)}
{preview}
</div> : null}
{hasDetails ? (
@@ -12,21 +12,9 @@ import {
} from "@/components/thread/activity/web-search-model";
export function WebSearchRun({ run, turnActive }: { run: WebSearchRunModel; turnActive: boolean }) {
const { t } = useTranslation();
const active = run.status === "running" && turnActive;
const status = run.status === "running" && !turnActive ? "done" : run.status;
const presentation = presentWebSearchAction(run.query, status, run.target, t);
return (
<>
<ActivityStep
icon={status === "error" ? AlertCircle : WebSearchIcon}
active={active}
tone={status === "error" ? "error" : status === "done" ? "success" : "active"}
label={presentation.label}
detail={presentation.detail}
labelClassName={presentation.detail ? "max-w-[50%]" : undefined}
/>
<WebSearchActionRow run={run} turnActive={turnActive} />
{run.sources.map((source) => (
<WebActivityRow
key={source.href}
@@ -39,3 +27,21 @@ export function WebSearchRun({ run, turnActive }: { run: WebSearchRunModel; turn
</>
);
}
export function WebSearchActionRow({ run, turnActive }: { run: WebSearchRunModel; turnActive: boolean }) {
const { t } = useTranslation();
const active = run.status === "running" && turnActive;
const status = run.status === "running" && !turnActive ? "done" : run.status;
const presentation = presentWebSearchAction(run.query, status, run.target, t);
return (
<ActivityStep
icon={status === "error" ? AlertCircle : WebSearchIcon}
active={active}
tone={status === "error" ? "error" : status === "done" ? "success" : "active"}
label={presentation.label}
detail={presentation.detail}
labelClassName={presentation.detail ? "max-w-[50%]" : undefined}
/>
);
}