* fix(webui): keep activity header stable when toggling * fix(webui): keep activity spacing compact
1574 lines
51 KiB
TypeScript
1574 lines
51 KiB
TypeScript
import {
|
|
CompletedTaskIcon,
|
|
WebSearchIcon,
|
|
McpIcon,
|
|
ToolRunIcon,
|
|
} from "@/components/icons/product-icons";
|
|
import {
|
|
Fragment,
|
|
memo,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useState,
|
|
type ReactNode,
|
|
} from "react";
|
|
import { Clock3, Layers, Terminal } from "lucide-react";
|
|
import { useTranslation } from "react-i18next";
|
|
|
|
import { MarkdownText } from "@/components/MarkdownText";
|
|
import { cliAppInitials, mcpPresetInitials } from "@/components/CliAppMentionText";
|
|
import { ActivityStep } from "@/components/thread/activity/ActivityStep";
|
|
import { coalesceActivityMessages } from "@/components/thread/activity/activity-message-model";
|
|
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";
|
|
import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context";
|
|
import { describeExecSession, passiveRunningCheckSessionId, toolEventArguments, toolEventName } from "@/components/thread/activity/exec-session-model";
|
|
import {
|
|
canGroupGenericToolRuns,
|
|
type GenericToolRunItem,
|
|
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 { WebSearchActionRow, WebSearchRun } from "@/components/thread/activity/WebSearchRun";
|
|
import { webSearchRunsByTraceLine } from "@/components/thread/activity/web-search-model";
|
|
import {
|
|
isReasoningOnlyAssistant,
|
|
} from "@/lib/activity-timeline";
|
|
import { formControlFocusClassName } from "@/components/ui/form-control";
|
|
import { useFileEditDisplayMode } from "@/hooks/useFileEditDisplayMode";
|
|
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
|
|
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
|
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
|
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
|
import type { FileEditDisplayMode } from "@/lib/local-preferences";
|
|
import { logoFallbackUrls } from "@/lib/provider-brand";
|
|
import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";
|
|
import { cn } from "@/lib/utils";
|
|
import type {
|
|
CliAppInfo,
|
|
McpPresetInfo,
|
|
RetryStatus,
|
|
ToolProgressEvent,
|
|
UIFileEdit,
|
|
UIMessage,
|
|
} from "@/lib/types";
|
|
|
|
const EMPTY_CLI_APPS: CliAppInfo[] = [];
|
|
const EMPTY_MCP_PRESETS: McpPresetInfo[] = [];
|
|
|
|
interface ActivityCounts {
|
|
reasoningSteps: number;
|
|
toolCalls: number;
|
|
modelSegments: number;
|
|
cliCount: number;
|
|
mcpCount: number;
|
|
fileCount: number;
|
|
}
|
|
|
|
interface CliRunSummary {
|
|
key: string;
|
|
name: string;
|
|
args: string[];
|
|
json: boolean;
|
|
workingDir?: string;
|
|
status: CliRunStatus;
|
|
error?: string;
|
|
}
|
|
|
|
type CliRunStatus = "running" | "done" | "error";
|
|
type McpRunStatus = "running" | "done" | "error";
|
|
|
|
interface McpRunSummary {
|
|
key: string;
|
|
presetName: string;
|
|
displayName: string;
|
|
toolName: string;
|
|
args: unknown;
|
|
status: McpRunStatus;
|
|
error?: string;
|
|
}
|
|
|
|
function countActivity(
|
|
messages: UIMessage[],
|
|
fileEdits: FileEditSummary[],
|
|
cliRuns: CliRunSummary[],
|
|
mcpRuns: McpRunSummary[],
|
|
): ActivityCounts {
|
|
let reasoningSteps = 0;
|
|
let toolCalls = 0;
|
|
let modelSegments = 0;
|
|
const cliCount = cliRuns.length;
|
|
const mcpCount = mcpRuns.length;
|
|
for (const m of messages) {
|
|
if (m.activityKind === "model") {
|
|
modelSegments += 1;
|
|
continue;
|
|
}
|
|
if (isReasoningOnlyAssistant(m)) {
|
|
reasoningSteps += 1;
|
|
continue;
|
|
}
|
|
if (m.kind === "trace") {
|
|
if (m.traceDetail) {
|
|
toolCalls += m.traceDetail.traceCount;
|
|
continue;
|
|
}
|
|
const lines = traceLines(m);
|
|
for (const line of lines) {
|
|
if (!isCliRunTraceLine(line) && !isMcpRunTraceLine(line)) {
|
|
toolCalls += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return {
|
|
reasoningSteps,
|
|
toolCalls,
|
|
modelSegments,
|
|
cliCount,
|
|
mcpCount,
|
|
fileCount: fileEdits.length,
|
|
};
|
|
}
|
|
|
|
interface AgentActivityClusterProps {
|
|
messages: UIMessage[];
|
|
/** True while the session turn is still running (drives “Working…” copy + header sheen). */
|
|
isTurnStreaming: boolean;
|
|
hasBodyBelow: boolean;
|
|
/** Persisted end-to-end turn latency from the assistant answer, used for history replay. */
|
|
turnLatencyMs?: number;
|
|
/** User turn start timestamp for live activity before the first trace/reasoning row. */
|
|
startedAtMs?: number;
|
|
retryStatus?: RetryStatus | null;
|
|
cliApps?: CliAppInfo[];
|
|
mcpPresets?: McpPresetInfo[];
|
|
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) {
|
|
const displayMode = useFileEditDisplayMode();
|
|
const messages = useMemo(() => coalesceActivityMessages(props.messages), [props.messages]);
|
|
const editsByMessage = useMemo(
|
|
() => summarizeFileEditsByMessage(messages, props.isTurnStreaming),
|
|
[messages, props.isTurnStreaming],
|
|
);
|
|
if (displayMode === "summary" || !editsByMessage.size) {
|
|
return <FoldedAgentActivity {...props} />;
|
|
}
|
|
|
|
// Diff rows break the fold so they stay visible in their original timeline position.
|
|
const items: ReactNode[] = [];
|
|
let pending: UIMessage[] = [];
|
|
const flush = (last: boolean) => {
|
|
// A live turn still needs its status header when the last row is a diff.
|
|
if (!pending.length && !(last && props.isTurnStreaming)) return;
|
|
items.push(
|
|
<FoldedAgentActivity
|
|
{...props}
|
|
detailsId={undefined}
|
|
key={pending[0]?.id ?? "tail-status"}
|
|
messages={pending}
|
|
isTurnStreaming={last && props.isTurnStreaming}
|
|
retryStatus={last ? props.retryStatus : null}
|
|
hasBodyBelow={false}
|
|
/>,
|
|
);
|
|
pending = [];
|
|
};
|
|
for (const message of messages) {
|
|
const edits = editsByMessage.get(message.id);
|
|
if (message.fileEdits?.length) {
|
|
const traces = traceLines(message).filter((line) => !isFileEditTraceLine(line));
|
|
if (traces.some((line) => line.trim())) {
|
|
pending.push({ ...message, traces, content: traces.at(-1) ?? "", fileEdits: undefined });
|
|
}
|
|
} else {
|
|
pending.push(message);
|
|
}
|
|
if (edits?.length) {
|
|
flush(false);
|
|
items.push(
|
|
<FileEditGroup
|
|
key={`${message.id}:edits`}
|
|
edits={edits}
|
|
displayMode={displayMode}
|
|
onOpenFilePreview={props.onOpenFilePreview}
|
|
/>,
|
|
);
|
|
}
|
|
}
|
|
flush(true);
|
|
return (
|
|
<div id={props.detailsId} className={cn("flex w-full flex-col gap-0.5", props.hasBodyBelow && "mb-2")}>
|
|
{items}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function FoldedAgentActivity({
|
|
messages,
|
|
isTurnStreaming,
|
|
hasBodyBelow,
|
|
turnLatencyMs,
|
|
startedAtMs,
|
|
retryStatus = null,
|
|
cliApps = EMPTY_CLI_APPS,
|
|
mcpPresets = EMPTY_MCP_PRESETS,
|
|
traceDetailScope = null,
|
|
onLoadTraceDetails,
|
|
onOpenFilePreview,
|
|
expanded,
|
|
onExpandedChange,
|
|
hideHeader = false,
|
|
detailsId,
|
|
}: AgentActivityClusterProps) {
|
|
const { t } = useTranslation();
|
|
const { activityMode, fileEditDisplayMode } = useLocalPreferences();
|
|
const pageVisible = usePageVisibility();
|
|
const threadVisible = useThreadVisibility();
|
|
const activityMessages = useMemo(() => coalesceActivityMessages(messages), [messages]);
|
|
const fileEditsByMessage = useMemo(
|
|
() => summarizeFileEditsByMessage(activityMessages, isTurnStreaming),
|
|
[activityMessages, isTurnStreaming],
|
|
);
|
|
const fileEdits = useMemo(
|
|
() => [...fileEditsByMessage.values()].flat(),
|
|
[fileEditsByMessage],
|
|
);
|
|
const cliRuns = useMemo(() => collectCliRuns(activityMessages), [activityMessages]);
|
|
const mcpRuns = useMemo(() => collectMcpRuns(activityMessages), [activityMessages]);
|
|
const cliAppsByName = useMemo(
|
|
() => new Map(cliApps.map((app) => [app.name.toLowerCase(), app])),
|
|
[cliApps],
|
|
);
|
|
const mcpPresetsByName = useMemo(
|
|
() => new Map(mcpPresets.map((preset) => [preset.name.toLowerCase(), preset])),
|
|
[mcpPresets],
|
|
);
|
|
const {
|
|
reasoningSteps,
|
|
toolCalls,
|
|
modelSegments,
|
|
cliCount,
|
|
mcpCount,
|
|
fileCount,
|
|
} = countActivity(activityMessages, fileEdits, cliRuns, mcpRuns);
|
|
|
|
const [outerOpenLocal, setOuterOpenLocal] = useState<boolean>();
|
|
const [failedTraceDetailKey, setFailedTraceDetailKey] = useState<string | null>(null);
|
|
const [now, setNow] = useState(() => Date.now());
|
|
const outerExpanded = expanded ?? outerOpenLocal ?? (activityMode === "expanded");
|
|
useEffect(() => {
|
|
setOuterOpenLocal(undefined);
|
|
}, [activityMode]);
|
|
const deferredTraceRefs = useMemo(
|
|
() => Array.from(new Set(
|
|
messages
|
|
.map((message) => message.traceDetail?.ref)
|
|
.filter((ref): ref is string => typeof ref === "string" && ref.length > 0),
|
|
)),
|
|
[messages],
|
|
);
|
|
const traceDetailKey = useMemo(
|
|
() => `${traceDetailScope ?? ""}\u0000${deferredTraceRefs.join("\u0000")}`,
|
|
[deferredTraceRefs, traceDetailScope],
|
|
);
|
|
const traceDetailLoadFailed = failedTraceDetailKey === traceDetailKey;
|
|
const requestTraceDetails = useCallback(async (refs: string[]) => {
|
|
if (!onLoadTraceDetails) return;
|
|
setFailedTraceDetailKey(null);
|
|
try {
|
|
await onLoadTraceDetails(refs);
|
|
} catch {
|
|
setFailedTraceDetailKey(`${traceDetailScope ?? ""}\u0000${refs.join("\u0000")}`);
|
|
}
|
|
}, [onLoadTraceDetails, traceDetailScope]);
|
|
|
|
const hasVisibleActivity = reasoningSteps > 0 || toolCalls > 0 || modelSegments > 0 || cliCount > 0 || mcpCount > 0 || fileCount > 0;
|
|
const hasOnlyFileActivity = fileCount > 0 && activityMessages.every(messageHasOnlyFileActivity);
|
|
const durationMs = activityDurationMs(
|
|
activityMessages,
|
|
isTurnStreaming,
|
|
now,
|
|
turnLatencyMs,
|
|
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" })
|
|
: retryStatus?.error_kind === "timeout"
|
|
? t("message.retryTimeout", { defaultValue: "Model timed out" })
|
|
: retryStatus?.error_kind === "rate_limit"
|
|
? t("message.retryRateLimit", { defaultValue: "Rate limited" })
|
|
: retryStatus?.error_kind === "server"
|
|
? t("message.retryServer", { defaultValue: "Model unavailable" })
|
|
: t("message.retryUnknown", { defaultValue: "Model request failed" });
|
|
const retrySeconds = retryStatus?.next_retry_at === undefined
|
|
? 0
|
|
: Math.max(0, Math.ceil(retryStatus.next_retry_at - now / 1000));
|
|
const activityLabel = retryStatus?.state === "exhausted"
|
|
? t("message.retryExhausted", {
|
|
error: retryError,
|
|
defaultValue: "{{error}} Ending turn",
|
|
})
|
|
: retryStatus?.state === "waiting"
|
|
? retrySeconds > 0
|
|
? t("message.retryWaiting", {
|
|
error: retryError,
|
|
seconds: retrySeconds,
|
|
defaultValue: "{{error}} Retrying in {{seconds}}s",
|
|
})
|
|
: t("message.retrying", {
|
|
error: retryError,
|
|
defaultValue: "{{error}} Retrying",
|
|
})
|
|
: isTurnStreaming
|
|
? workingLabel(activityDuration)
|
|
: durationMs <= 0
|
|
? t("message.activityWorked", { defaultValue: "Worked" })
|
|
: t("message.activityWorkedFor", {
|
|
duration: activityDuration,
|
|
defaultValue: "Worked for {{duration}}",
|
|
});
|
|
|
|
const toggleOuter = () => {
|
|
if (expanded !== undefined) {
|
|
onExpandedChange?.(!expanded);
|
|
return;
|
|
}
|
|
setOuterOpenLocal(!outerExpanded);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (outerExpanded && deferredTraceRefs.length > 0) {
|
|
void requestTraceDetails(deferredTraceRefs);
|
|
}
|
|
}, [deferredTraceRefs, outerExpanded, requestTraceDetails]);
|
|
|
|
useEffect(() => {
|
|
if (!isTurnStreaming || !pageVisible || !threadVisible) return undefined;
|
|
setNow(Date.now());
|
|
const interval = window.setInterval(() => setNow(Date.now()), 1_000);
|
|
return () => window.clearInterval(interval);
|
|
}, [isTurnStreaming, pageVisible, threadVisible]);
|
|
|
|
if (!hasVisibleActivity && !isTurnStreaming) return null;
|
|
|
|
if (hasOnlyFileActivity && expanded === undefined) {
|
|
return (
|
|
<div className={cn("w-full", hasBodyBelow && "mb-2")}>
|
|
<FileEditGroup
|
|
edits={fileEdits}
|
|
displayMode={fileEditDisplayMode}
|
|
onOpenFilePreview={onOpenFilePreview}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<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}
|
|
preview={showActivityPreview ? (
|
|
<CollapsedActivityPreview
|
|
messages={activityMessages}
|
|
fileEditsByMessage={fileEditsByMessage}
|
|
cliAppsByName={cliAppsByName}
|
|
mcpPresetsByName={mcpPresetsByName}
|
|
visible={pageVisible && threadVisible}
|
|
/>
|
|
) : undefined}
|
|
hasDetails={hasVisibleActivity}
|
|
onToggle={toggleOuter}
|
|
>
|
|
{traceDetailLoadFailed ? (
|
|
<div role="alert" className="flex items-center gap-2 py-1 text-[12px] text-destructive">
|
|
<span>{t("message.traceDetailsLoadFailed", { defaultValue: "Full activity details could not be loaded." })}</span>
|
|
<button
|
|
type="button"
|
|
className="shrink-0 rounded-sm font-medium underline underline-offset-2 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
|
onClick={() => void requestTraceDetails(deferredTraceRefs)}
|
|
>
|
|
{t("message.retryTraceDetails", { defaultValue: "Retry" })}
|
|
</button>
|
|
</div>
|
|
) : null}
|
|
<ActivityMessageTimeline
|
|
messages={activityMessages}
|
|
active={isTurnStreaming}
|
|
cliAppsByName={cliAppsByName}
|
|
mcpPresetsByName={mcpPresetsByName}
|
|
fileEditsByMessage={fileEditsByMessage}
|
|
fileEditDisplayMode={fileEditDisplayMode}
|
|
onOpenFilePreview={onOpenFilePreview}
|
|
/>
|
|
</ThinkingReasoningShell>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function messageHasOnlyFileActivity(message: UIMessage): boolean {
|
|
if (message.kind !== "trace" || !message.fileEdits?.length) return false;
|
|
return traceLines(message).every((line) => !line.trim() || isFileEditTraceLine(line));
|
|
}
|
|
|
|
function activityDurationMs(
|
|
messages: UIMessage[],
|
|
active: boolean,
|
|
now: number,
|
|
completedLatencyMs?: number,
|
|
activeStartedAtMs?: number,
|
|
): number {
|
|
if (!active && Number.isFinite(completedLatencyMs) && completedLatencyMs! >= 0) {
|
|
return Math.round(completedLatencyMs!);
|
|
}
|
|
const timestamps = messages
|
|
.map((message) => message.createdAt)
|
|
.filter((value) => Number.isFinite(value));
|
|
if (!timestamps.length) {
|
|
return active
|
|
&& typeof activeStartedAtMs === "number"
|
|
&& Number.isFinite(activeStartedAtMs)
|
|
? Math.max(0, now - activeStartedAtMs)
|
|
: 0;
|
|
}
|
|
const first = active && Number.isFinite(activeStartedAtMs)
|
|
? activeStartedAtMs!
|
|
: Math.min(...timestamps);
|
|
const last = active && first > 1_000_000_000_000
|
|
? now
|
|
: Math.max(...timestamps);
|
|
return Math.max(0, last - first);
|
|
}
|
|
|
|
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);
|
|
const rest = seconds % 60;
|
|
return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
|
|
}
|
|
|
|
function traceLines(message: UIMessage): string[] {
|
|
if (message.traces?.length) return message.traces;
|
|
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,
|
|
cliAppsByName,
|
|
mcpPresetsByName,
|
|
fileEditsByMessage,
|
|
fileEditDisplayMode,
|
|
onOpenFilePreview,
|
|
}: {
|
|
messages: UIMessage[];
|
|
active: boolean;
|
|
cliAppsByName: Map<string, CliAppInfo>;
|
|
mcpPresetsByName: Map<string, McpPresetInfo>;
|
|
fileEditsByMessage: Map<string, FileEditSummary[]>;
|
|
fileEditDisplayMode: FileEditDisplayMode;
|
|
onOpenFilePreview?: (path: string) => void;
|
|
}) {
|
|
const items: ReactNode[] = [];
|
|
|
|
messages.forEach((message, index) => {
|
|
if (message.activityKind === "model") {
|
|
items.push(
|
|
<ActivityModelMessage
|
|
key={message.id}
|
|
message={message}
|
|
active={active}
|
|
onOpenFilePreview={onOpenFilePreview}
|
|
/>,
|
|
);
|
|
return;
|
|
}
|
|
if (isReasoningOnlyAssistant(message)) {
|
|
items.push(
|
|
<ReasoningRow
|
|
key={message.id}
|
|
text={message.reasoning ?? ""}
|
|
streaming={active && !!message.reasoningStreaming}
|
|
/>,
|
|
);
|
|
return;
|
|
}
|
|
if (message.kind === "trace") {
|
|
const fileEdits = fileEditsByMessage.get(message.id) ?? [];
|
|
items.push(
|
|
<Fragment key={message.id}>
|
|
<ActivityTraceTimeline
|
|
message={message}
|
|
active={active && index === messages.length - 1}
|
|
turnActive={active}
|
|
cliAppsByName={cliAppsByName}
|
|
mcpPresetsByName={mcpPresetsByName}
|
|
/>
|
|
<FileEditGroup
|
|
edits={fileEdits}
|
|
displayMode={fileEditDisplayMode}
|
|
onOpenFilePreview={onOpenFilePreview}
|
|
/>
|
|
</Fragment>,
|
|
);
|
|
}
|
|
});
|
|
return <>{items}</>;
|
|
});
|
|
|
|
/**
|
|
* Keep an intermediate assistant segment as normal Markdown. The activity
|
|
* surface owns ordering and lifecycle, not a reduced rendering mode: users
|
|
* should see the same prose, links, and code treatment before and after the
|
|
* surrounding turn is folded.
|
|
*/
|
|
function ActivityModelMessage({
|
|
message,
|
|
active,
|
|
onOpenFilePreview,
|
|
}: {
|
|
message: UIMessage;
|
|
active: boolean;
|
|
onOpenFilePreview?: (path: string) => void;
|
|
}) {
|
|
if (!message.content.trim()) return null;
|
|
return (
|
|
<div
|
|
data-testid="activity-model-message"
|
|
data-assistant-selectable={active && message.isStreaming ? undefined : "true"}
|
|
className="w-full min-w-0 py-1 text-reading"
|
|
>
|
|
<MarkdownText
|
|
streaming={active && !!message.isStreaming}
|
|
preserveStreamingLayout
|
|
onOpenFilePreview={onOpenFilePreview}
|
|
>
|
|
{message.content}
|
|
</MarkdownText>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function ActivityTraceList({
|
|
lines,
|
|
active,
|
|
stateByLine,
|
|
}: {
|
|
lines: string[];
|
|
active: boolean;
|
|
stateByLine?: Map<string, GenericToolState>;
|
|
}) {
|
|
const items: ReactNode[] = [];
|
|
let genericItems: GenericToolRunItem[] = [];
|
|
|
|
const flushGenericItems = (suffix: string) => {
|
|
if (!genericItems.length) return;
|
|
items.push(
|
|
<GenericToolRun
|
|
key={`generic-tool:${genericItems[0].trace.groupKey}:${suffix}`}
|
|
items={genericItems}
|
|
/>,
|
|
);
|
|
genericItems = [];
|
|
};
|
|
|
|
lines.forEach((line, index) => {
|
|
const trace = parseGenericToolTrace(line);
|
|
if (trace) {
|
|
const key = canonicalToolTrace(line);
|
|
const explicitState = stateByLine?.get(key);
|
|
const fallbackStatus: GenericToolStatus = active && index === lines.length - 1 ? "running" : "done";
|
|
const item: GenericToolRunItem = {
|
|
trace,
|
|
status: explicitState?.status === "running" && !active ? "done" : explicitState?.status ?? fallbackStatus,
|
|
error: explicitState?.error,
|
|
};
|
|
const previous = genericItems[genericItems.length - 1];
|
|
if (previous && !canGroupGenericToolRuns(previous, item)) flushGenericItems(String(index));
|
|
genericItems.push(item);
|
|
return;
|
|
}
|
|
|
|
flushGenericItems(String(index));
|
|
items.push(
|
|
<ActivityTraceRow
|
|
key={`${line}-${index}`}
|
|
line={line}
|
|
active={active && index === lines.length - 1}
|
|
state={stateByLine?.get(canonicalToolTrace(line))}
|
|
/>,
|
|
);
|
|
});
|
|
flushGenericItems("tail");
|
|
|
|
return (
|
|
<>
|
|
{items}
|
|
</>
|
|
);
|
|
}
|
|
|
|
interface ActivityTraceEntry {
|
|
line: string;
|
|
sessionEvent?: ToolProgressEvent;
|
|
sessionChecks?: ToolProgressEvent[];
|
|
}
|
|
|
|
const SESSION_CHECK_FOLD_THRESHOLD = 5;
|
|
|
|
/** Keep individual observations available without mounting hundreds of identical rows. */
|
|
function foldSessionChecks(entries: ActivityTraceEntry[]): ActivityTraceEntry[] {
|
|
const result: ActivityTraceEntry[] = [];
|
|
let index = 0;
|
|
while (index < entries.length) {
|
|
const first = entries[index].sessionEvent;
|
|
const id = first && passiveRunningCheckSessionId(first);
|
|
let end = index + 1;
|
|
if (id) {
|
|
while (end < entries.length) {
|
|
const next = entries[end].sessionEvent;
|
|
if (!next || passiveRunningCheckSessionId(next) !== id) break;
|
|
end += 1;
|
|
}
|
|
}
|
|
if (id && end - index >= SESSION_CHECK_FOLD_THRESHOLD) {
|
|
result.push({ line: "", sessionChecks: entries.slice(index, end).map((entry) => entry.sessionEvent!) });
|
|
} else {
|
|
result.push(...entries.slice(index, end));
|
|
}
|
|
index = end;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/** Restore exec_session call identities lost by display-text deduplication. */
|
|
function activityTraceEntries(message: UIMessage): ActivityTraceEntry[] {
|
|
const lines = traceLines(message);
|
|
const events = message.toolEvents ?? [];
|
|
if (!events.some((event) => toolEventName(event) === "exec_session")) return lines.map((line) => ({ line }));
|
|
const lineKeys = new Set(lines.map(canonicalToolTrace));
|
|
const eventEntries: ActivityTraceEntry[] = [];
|
|
const rendered = new Set<string>();
|
|
const sessionIndices = new Map<string, number>();
|
|
for (const event of events) {
|
|
const line = formatToolCallTrace(event);
|
|
if (!line) continue;
|
|
const key = canonicalToolTrace(line);
|
|
if (toolEventName(event) === "exec_session") {
|
|
const callKey = event.call_id ?? key;
|
|
const existing = sessionIndices.get(callKey);
|
|
if (existing !== undefined) {
|
|
const previous = eventEntries[existing].sessionEvent!;
|
|
if ((GENERIC_TOOL_STATUS_RANK[phaseStatus(event.phase)]) >= GENERIC_TOOL_STATUS_RANK[phaseStatus(previous.phase)]) {
|
|
eventEntries[existing] = { line, sessionEvent: { ...previous, ...event } };
|
|
}
|
|
} else {
|
|
sessionIndices.set(callKey, eventEntries.length);
|
|
eventEntries.push({ line, sessionEvent: event });
|
|
}
|
|
} else if (lineKeys.has(key) && !rendered.has(key)) {
|
|
rendered.add(key);
|
|
eventEntries.push({ line });
|
|
}
|
|
}
|
|
|
|
// Anchor text-only lines before the next matching structured call, or after
|
|
// all calls when they are at the end. Repeated calls keep their identities.
|
|
const positions = new Map<string, number[]>();
|
|
eventEntries.forEach((entry, index) => {
|
|
const key = canonicalToolTrace(entry.line);
|
|
const indices = positions.get(key) ?? [];
|
|
indices.push(index);
|
|
positions.set(key, indices);
|
|
});
|
|
const occurrences = new Map<string, number>();
|
|
const before = new Map<number, string[]>();
|
|
let pending: string[] = [];
|
|
for (const line of lines) {
|
|
const key = canonicalToolTrace(line);
|
|
const indices = positions.get(key);
|
|
if (!indices?.length) {
|
|
pending.push(line);
|
|
continue;
|
|
}
|
|
const count = occurrences.get(key) ?? 0;
|
|
occurrences.set(key, count + 1);
|
|
if (!pending.length) continue;
|
|
const index = indices[Math.min(count, indices.length - 1)];
|
|
const anchored = before.get(index) ?? [];
|
|
for (const preceding of pending) anchored.push(preceding);
|
|
before.set(index, anchored);
|
|
pending = [];
|
|
}
|
|
const result: ActivityTraceEntry[] = [];
|
|
eventEntries.forEach((entry, index) => {
|
|
for (const line of before.get(index) ?? []) result.push({ line });
|
|
result.push(entry);
|
|
});
|
|
for (const line of pending) result.push({ line });
|
|
return result;
|
|
}
|
|
|
|
function phaseStatus(phase: unknown): GenericToolStatus {
|
|
return phase === "error" ? "error" : phase === "end" ? "done" : "running";
|
|
}
|
|
|
|
function ActivityTraceTimeline({
|
|
message,
|
|
active,
|
|
turnActive,
|
|
cliAppsByName,
|
|
mcpPresetsByName,
|
|
}: {
|
|
message: UIMessage;
|
|
active: boolean;
|
|
turnActive: boolean;
|
|
cliAppsByName: Map<string, CliAppInfo>;
|
|
mcpPresetsByName: Map<string, McpPresetInfo>;
|
|
}) {
|
|
const entries = foldSessionChecks(activityTraceEntries(message));
|
|
const cliRunsByLine = cliRunMapByTraceLine(message);
|
|
const mcpRunsByLine = mcpRunMapByTraceLine(message);
|
|
const webSearchRunsByLine = webSearchRunsByTraceLine(message.toolEvents ?? []);
|
|
const genericStateByLine = genericToolStateByTraceLine(message);
|
|
const renderedRunKeys = new Set<string>();
|
|
const items: ReactNode[] = [];
|
|
let normalLines: string[] = [];
|
|
|
|
const flushNormalLines = (suffix: string) => {
|
|
if (!normalLines.length) return;
|
|
items.push(
|
|
<ActivityTraceList
|
|
key={`${message.id}:trace:${suffix}`}
|
|
lines={normalLines}
|
|
active={active}
|
|
stateByLine={genericStateByLine}
|
|
/>,
|
|
);
|
|
normalLines = [];
|
|
};
|
|
|
|
entries.forEach(({ line, sessionEvent, sessionChecks }, index) => {
|
|
if (sessionChecks) {
|
|
flushNormalLines(String(index));
|
|
items.push(<ExecSessionCheckGroup key={`${message.id}:checks:${sessionChecks[0].call_id ?? index}`} events={sessionChecks} turnActive={turnActive} />);
|
|
return;
|
|
}
|
|
if (sessionEvent || /^exec_session\(/.test(line.trim())) {
|
|
flushNormalLines(String(index));
|
|
let event = sessionEvent;
|
|
if (!event) {
|
|
const raw = /^exec_session\((.*)\)$/.exec(line.trim())?.[1] ?? "";
|
|
event = { name: "exec_session", arguments: raw, phase: active && index === entries.length - 1 ? "start" : "unknown" };
|
|
}
|
|
items.push(<ExecSessionRow key={`${message.id}:session:${event.call_id ?? index}`} event={event} turnActive={turnActive} />);
|
|
return;
|
|
}
|
|
const traceKey = canonicalToolTrace(line);
|
|
const webSearchRun = webSearchRunsByLine.get(traceKey);
|
|
if (webSearchRun) {
|
|
flushNormalLines(String(index));
|
|
renderedRunKeys.add(webSearchRun.key);
|
|
items.push(
|
|
<WebSearchRun
|
|
key={`${message.id}:web-search:${webSearchRun.key}:${index}`}
|
|
run={webSearchRun}
|
|
turnActive={active}
|
|
/>,
|
|
);
|
|
return;
|
|
}
|
|
|
|
const cliRun = cliRunsByLine.get(traceKey) ?? parseCliRunTrace(line);
|
|
if (cliRun) {
|
|
flushNormalLines(String(index));
|
|
renderedRunKeys.add(cliRun.key);
|
|
items.push(
|
|
<CliRunGroup
|
|
key={`${message.id}:cli:${cliRun.key}:${index}`}
|
|
runs={[cliRun]}
|
|
active={active}
|
|
cliAppsByName={cliAppsByName}
|
|
/>,
|
|
);
|
|
return;
|
|
}
|
|
|
|
const mcpRun = mcpRunsByLine.get(traceKey) ?? parseMcpRunTrace(line);
|
|
if (mcpRun) {
|
|
flushNormalLines(String(index));
|
|
renderedRunKeys.add(mcpRun.key);
|
|
items.push(
|
|
<McpRunGroup
|
|
key={`${message.id}:mcp:${mcpRun.key}:${index}`}
|
|
runs={[mcpRun]}
|
|
active={active}
|
|
mcpPresetsByName={mcpPresetsByName}
|
|
/>,
|
|
);
|
|
return;
|
|
}
|
|
|
|
normalLines.push(line);
|
|
});
|
|
|
|
flushNormalLines("tail");
|
|
|
|
for (const run of webSearchRunsByLine.values()) {
|
|
if (renderedRunKeys.has(run.key)) continue;
|
|
items.push(
|
|
<WebSearchRun
|
|
key={`${message.id}:web-search:${run.key}:event`}
|
|
run={run}
|
|
turnActive={active}
|
|
/>,
|
|
);
|
|
}
|
|
for (const run of cliRunsByLine.values()) {
|
|
if (renderedRunKeys.has(run.key)) continue;
|
|
items.push(
|
|
<CliRunGroup
|
|
key={`${message.id}:cli:${run.key}:event`}
|
|
runs={[run]}
|
|
active={active}
|
|
cliAppsByName={cliAppsByName}
|
|
/>,
|
|
);
|
|
}
|
|
for (const run of mcpRunsByLine.values()) {
|
|
if (renderedRunKeys.has(run.key)) continue;
|
|
items.push(
|
|
<McpRunGroup
|
|
key={`${message.id}:mcp:${run.key}:event`}
|
|
runs={[run]}
|
|
active={active}
|
|
mcpPresetsByName={mcpPresetsByName}
|
|
/>,
|
|
);
|
|
}
|
|
|
|
if (!items.length) return null;
|
|
return (
|
|
<>
|
|
{items}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function ExecSessionCheckGroup({ events, turnActive }: { events: ToolProgressEvent[]; turnActive: boolean }) {
|
|
const { t } = useTranslation();
|
|
const [expanded, setExpanded] = useState(false);
|
|
const earlier = events.slice(0, -1);
|
|
return (
|
|
<>
|
|
<button
|
|
type="button"
|
|
aria-expanded={expanded}
|
|
className={cn("ml-[1.625rem] w-fit rounded-sm py-0.5 text-left text-[13px] text-muted-foreground hover:underline", formControlFocusClassName)}
|
|
onClick={() => setExpanded((value) => !value)}
|
|
>
|
|
{t(`message.agentActivity.${expanded ? "hideEarlierCommandChecks" : "showEarlierCommandChecks"}`, { count: earlier.length })}
|
|
</button>
|
|
{expanded ? earlier.map((event, index) => (
|
|
<ExecSessionRow key={event.call_id ?? index} event={event} turnActive={turnActive} />
|
|
)) : null}
|
|
<ExecSessionRow event={events[events.length - 1]} turnActive={turnActive} />
|
|
</>
|
|
);
|
|
}
|
|
|
|
function ExecSessionRow({ event, turnActive }: { event: ToolProgressEvent; turnActive: boolean }) {
|
|
const { t } = useTranslation();
|
|
const commands = useContext(ExecSessionCommandsContext);
|
|
const id = toolEventArguments(event).session_id;
|
|
const model = describeExecSession(event, turnActive, typeof id === "string" ? commands.get(id) : undefined, t);
|
|
return (
|
|
<ActivityStep
|
|
icon={Terminal}
|
|
active={model.active}
|
|
tone={model.tone}
|
|
label={formatActivityTarget(t, model.label, model.detail)}
|
|
detail={[model.observation, model.aside].filter(Boolean).join(" · ")}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function ActivityTraceRow({
|
|
line,
|
|
active,
|
|
state,
|
|
}: {
|
|
line: string;
|
|
active: boolean;
|
|
state?: GenericToolState;
|
|
}) {
|
|
const { t } = useTranslation();
|
|
const status = state?.status ?? (active ? "running" : "done");
|
|
const trace = describeTraceLine(line, status, t, state?.result);
|
|
const rowActive = status === "running" && active;
|
|
const Icon = trace.icon === "clock" ? Clock3 : (trace.kind === "search"
|
|
? WebSearchIcon
|
|
: trace.kind === "done"
|
|
? CompletedTaskIcon
|
|
: trace.kind === "tool"
|
|
? ToolRunIcon
|
|
: Layers);
|
|
if (trace.url && trace.host) {
|
|
return (
|
|
<WebActivityRow
|
|
title={trace.label}
|
|
href={trace.url}
|
|
host={trace.host}
|
|
displayUrl={trace.detail}
|
|
active={rowActive}
|
|
tone={status === "error" ? "error" : status === "done" ? "success" : "active"}
|
|
/>
|
|
);
|
|
}
|
|
return (
|
|
<ActivityStep
|
|
icon={Icon}
|
|
active={rowActive && trace.kind !== "done"}
|
|
tone={status === "error" ? "error" : status === "done" ? "success" : "active"}
|
|
label={trace.kind === "search" ? trace.label : formatActivityTarget(t, trace.label, trace.detail)}
|
|
detail={trace.kind === "search" ? trace.detail : trace.aside}
|
|
labelClassName={trace.kind === "search" && trace.detail ? "max-w-[50%]" : undefined}
|
|
/>
|
|
);
|
|
}
|
|
|
|
interface GenericToolState {
|
|
status: GenericToolStatus;
|
|
error?: string;
|
|
result?: unknown;
|
|
}
|
|
|
|
const GENERIC_TOOL_STATUS_RANK: Record<GenericToolStatus, number> = { running: 1, done: 2, error: 3 };
|
|
|
|
function genericToolStateByTraceLine(message: UIMessage): Map<string, GenericToolState> {
|
|
const map = new Map<string, GenericToolState>();
|
|
for (const event of message.toolEvents ?? []) {
|
|
const line = formatToolCallTrace(event);
|
|
if (!line) continue;
|
|
const key = canonicalToolTrace(line);
|
|
const status: GenericToolStatus = event.phase === "error"
|
|
? "error"
|
|
: event.phase === "end"
|
|
? "done"
|
|
: "running";
|
|
const next = {
|
|
status,
|
|
error: status === "error" ? toolProgressError(event.error) : undefined,
|
|
result: event.result,
|
|
};
|
|
const previous = map.get(key);
|
|
if (!previous || GENERIC_TOOL_STATUS_RANK[next.status] >= GENERIC_TOOL_STATUS_RANK[previous.status]) {
|
|
map.set(key, next);
|
|
}
|
|
}
|
|
return map;
|
|
}
|
|
|
|
function toolProgressError(error: unknown): string | undefined {
|
|
if (typeof error === "string") return error;
|
|
if (error && typeof error === "object") {
|
|
try {
|
|
return JSON.stringify(error);
|
|
} catch {
|
|
return "Tool call failed";
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
const CLI_RUN_TOOL_NAMES = new Set(["run_cli_app", "cli_anything_run"]);
|
|
const CLI_RUN_STATUS_RANK: Record<CliRunStatus, number> = { running: 1, done: 2, error: 3 };
|
|
const MCP_RUN_STATUS_RANK: Record<McpRunStatus, number> = { running: 1, done: 2, error: 3 };
|
|
const MCP_TOOL_NAME_RE = /^mcp_([a-z0-9_-]+?)_(.+)$/i;
|
|
|
|
function isCliRunTraceLine(line: string): boolean {
|
|
return /^(run_cli_app|cli_anything_run)\(/.test(line.trim());
|
|
}
|
|
|
|
function isMcpRunTraceLine(line: string): boolean {
|
|
return MCP_TOOL_NAME_RE.test(line.trim().split("(", 1)[0] ?? "");
|
|
}
|
|
|
|
function isFileEditTraceLine(line: string): boolean {
|
|
return /^(write_file|edit_file|apply_patch)\(/.test(line.trim());
|
|
}
|
|
|
|
function parseCliRunTrace(line: string, status: CliRunStatus = "running"): CliRunSummary | null {
|
|
const match = /^(run_cli_app|cli_anything_run)\((.*)\)$/.exec(line.trim());
|
|
if (!match) return null;
|
|
const argsText = match[2].trim();
|
|
let argsObject: unknown = {};
|
|
if (argsText) {
|
|
try {
|
|
argsObject = JSON.parse(argsText);
|
|
} catch {
|
|
return {
|
|
key: line,
|
|
name: "cli",
|
|
args: [argsText],
|
|
json: false,
|
|
status,
|
|
};
|
|
}
|
|
}
|
|
return cliRunFromArguments(argsObject, { key: line, status });
|
|
}
|
|
|
|
function parseToolEventArguments(event: ToolProgressEvent): unknown {
|
|
const fnArgs = (event as { function?: { arguments?: unknown } }).function?.arguments;
|
|
const raw = fnArgs ?? event.arguments;
|
|
if (typeof raw !== "string") return raw ?? {};
|
|
if (!raw.trim()) return {};
|
|
try {
|
|
return JSON.parse(raw);
|
|
} catch {
|
|
return { args: [raw] };
|
|
}
|
|
}
|
|
|
|
function cliRunStatusFromPhase(phase: unknown): CliRunStatus {
|
|
if (phase === "error") return "error";
|
|
if (phase === "end") return "done";
|
|
return "running";
|
|
}
|
|
|
|
function cliRunError(event: ToolProgressEvent): string | undefined {
|
|
const error = event.error;
|
|
if (typeof error === "string") return error;
|
|
if (error && typeof error === "object") return JSON.stringify(error);
|
|
return undefined;
|
|
}
|
|
|
|
function cliRunFromArguments(
|
|
argsObject: unknown,
|
|
options: { key: string; status: CliRunStatus; error?: string },
|
|
): CliRunSummary {
|
|
if (!argsObject || typeof argsObject !== "object" || Array.isArray(argsObject)) {
|
|
return {
|
|
key: options.key,
|
|
name: "cli",
|
|
args: [],
|
|
json: false,
|
|
status: options.status,
|
|
error: options.error,
|
|
};
|
|
}
|
|
const record = argsObject as Record<string, unknown>;
|
|
const appName = typeof record.name === "string" && record.name.trim()
|
|
? record.name.trim()
|
|
: "cli";
|
|
const rawArgs = Array.isArray(record.args) ? record.args : [];
|
|
const cliArgs = rawArgs.filter((item): item is string => typeof item === "string");
|
|
return {
|
|
key: options.key,
|
|
name: appName,
|
|
args: cliArgs,
|
|
json: record.json === true || record.json === "true",
|
|
workingDir: typeof record.working_dir === "string" ? record.working_dir : undefined,
|
|
status: options.status,
|
|
error: options.error,
|
|
};
|
|
}
|
|
|
|
function cliRunFromEvent(event: ToolProgressEvent): CliRunSummary | null {
|
|
const name = toolEventName(event);
|
|
if (!CLI_RUN_TOOL_NAMES.has(name)) return null;
|
|
const argsObject = parseToolEventArguments(event);
|
|
const key = event.call_id ? `call:${event.call_id}` : `${name}:${JSON.stringify(argsObject)}`;
|
|
return cliRunFromArguments(argsObject, {
|
|
key,
|
|
status: cliRunStatusFromPhase(event.phase),
|
|
error: cliRunError(event),
|
|
});
|
|
}
|
|
|
|
function cliRunMapByTraceLine(message: UIMessage): Map<string, CliRunSummary> {
|
|
const runsByLine = new Map<string, CliRunSummary>();
|
|
for (const event of message.toolEvents ?? []) {
|
|
const run = cliRunFromEvent(event);
|
|
if (!run) continue;
|
|
const line = formatToolCallTrace(event);
|
|
if (!line) continue;
|
|
const key = canonicalToolTrace(line);
|
|
runsByLine.set(key, mergeCliRun(runsByLine.get(key), run));
|
|
}
|
|
return runsByLine;
|
|
}
|
|
|
|
function mergeCliRun(existing: CliRunSummary | undefined, incoming: CliRunSummary): CliRunSummary {
|
|
if (!existing) return incoming;
|
|
return CLI_RUN_STATUS_RANK[incoming.status] >= CLI_RUN_STATUS_RANK[existing.status]
|
|
? { ...existing, ...incoming }
|
|
: existing;
|
|
}
|
|
|
|
function collectCliRuns(messages: UIMessage[]): CliRunSummary[] {
|
|
const runsByKey = new Map<string, CliRunSummary>();
|
|
for (const message of messages) {
|
|
if (message.kind !== "trace") continue;
|
|
let hasStructuredCliRun = false;
|
|
for (const event of message.toolEvents ?? []) {
|
|
const run = cliRunFromEvent(event);
|
|
if (!run) continue;
|
|
hasStructuredCliRun = true;
|
|
runsByKey.set(run.key, mergeCliRun(runsByKey.get(run.key), run));
|
|
}
|
|
if (hasStructuredCliRun) continue;
|
|
for (const line of traceLines(message)) {
|
|
const run = parseCliRunTrace(line);
|
|
if (!run || runsByKey.has(run.key)) continue;
|
|
runsByKey.set(run.key, run);
|
|
}
|
|
}
|
|
return [...runsByKey.values()];
|
|
}
|
|
|
|
function titleFromPresetName(name: string): string {
|
|
const productName = PRODUCT_NAME_OVERRIDES[name.toLowerCase()];
|
|
if (productName) return productName;
|
|
return name
|
|
.split(/[-_]/)
|
|
.filter(Boolean)
|
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
.join(" ") || name;
|
|
}
|
|
|
|
const PRODUCT_NAME_OVERRIDES: Record<string, string> = {
|
|
github: "GitHub",
|
|
gitlab: "GitLab",
|
|
openai: "OpenAI",
|
|
};
|
|
|
|
function mcpRunFromToolName(
|
|
toolName: string,
|
|
argsObject: unknown,
|
|
options: { key: string; status: McpRunStatus; error?: string },
|
|
): McpRunSummary | null {
|
|
const match = MCP_TOOL_NAME_RE.exec(toolName);
|
|
if (!match) return null;
|
|
const presetName = match[1].toLowerCase();
|
|
return {
|
|
key: options.key,
|
|
presetName,
|
|
displayName: titleFromPresetName(presetName),
|
|
toolName: match[2],
|
|
args: argsObject,
|
|
status: options.status,
|
|
error: options.error,
|
|
};
|
|
}
|
|
|
|
function parseMcpRunTrace(line: string, status: McpRunStatus = "running"): McpRunSummary | null {
|
|
const match = /^([a-z0-9_-]+)\((.*)\)$/i.exec(line.trim());
|
|
if (!match || !MCP_TOOL_NAME_RE.test(match[1])) return null;
|
|
const argsText = match[2].trim();
|
|
let argsObject: unknown = {};
|
|
if (argsText) {
|
|
try {
|
|
argsObject = JSON.parse(argsText);
|
|
} catch {
|
|
argsObject = argsText;
|
|
}
|
|
}
|
|
return mcpRunFromToolName(match[1], argsObject, { key: line, status });
|
|
}
|
|
|
|
function mcpRunFromEvent(event: ToolProgressEvent): McpRunSummary | null {
|
|
const name = toolEventName(event);
|
|
if (!MCP_TOOL_NAME_RE.test(name)) return null;
|
|
const argsObject = parseToolEventArguments(event);
|
|
const key = event.call_id ? `call:${event.call_id}` : `${name}:${JSON.stringify(argsObject)}`;
|
|
return mcpRunFromToolName(name, argsObject, {
|
|
key,
|
|
status: cliRunStatusFromPhase(event.phase),
|
|
error: cliRunError(event),
|
|
});
|
|
}
|
|
|
|
function mcpRunMapByTraceLine(message: UIMessage): Map<string, McpRunSummary> {
|
|
const runsByLine = new Map<string, McpRunSummary>();
|
|
for (const event of message.toolEvents ?? []) {
|
|
const run = mcpRunFromEvent(event);
|
|
if (!run) continue;
|
|
const line = formatToolCallTrace(event);
|
|
if (!line) continue;
|
|
const key = canonicalToolTrace(line);
|
|
runsByLine.set(key, mergeMcpRun(runsByLine.get(key), run));
|
|
}
|
|
return runsByLine;
|
|
}
|
|
|
|
function mergeMcpRun(existing: McpRunSummary | undefined, incoming: McpRunSummary): McpRunSummary {
|
|
if (!existing) return incoming;
|
|
return MCP_RUN_STATUS_RANK[incoming.status] >= MCP_RUN_STATUS_RANK[existing.status]
|
|
? { ...existing, ...incoming }
|
|
: existing;
|
|
}
|
|
|
|
function collectMcpRuns(messages: UIMessage[]): McpRunSummary[] {
|
|
const runsByKey = new Map<string, McpRunSummary>();
|
|
for (const message of messages) {
|
|
if (message.kind !== "trace") continue;
|
|
let hasStructuredMcpRun = false;
|
|
for (const event of message.toolEvents ?? []) {
|
|
const run = mcpRunFromEvent(event);
|
|
if (!run) continue;
|
|
hasStructuredMcpRun = true;
|
|
runsByKey.set(run.key, mergeMcpRun(runsByKey.get(run.key), run));
|
|
}
|
|
if (hasStructuredMcpRun) continue;
|
|
for (const line of traceLines(message)) {
|
|
const run = parseMcpRunTrace(line);
|
|
if (!run || runsByKey.has(run.key)) continue;
|
|
runsByKey.set(run.key, run);
|
|
}
|
|
}
|
|
return [...runsByKey.values()];
|
|
}
|
|
|
|
function displayCliArg(arg: string): string {
|
|
return /\s/.test(arg) ? JSON.stringify(arg) : arg;
|
|
}
|
|
|
|
function formatCliArgs(run: CliRunSummary): string {
|
|
const args = [...(run.json ? ["--json"] : []), ...run.args].map(displayCliArg);
|
|
return args.join(" ");
|
|
}
|
|
|
|
function fileEditCallKey(edit: UIFileEdit): string {
|
|
if (edit.call_id && edit.path) return `${edit.call_id}|${edit.tool}|${edit.path}`;
|
|
if (edit.call_id) return `${edit.call_id}|${edit.tool}`;
|
|
return `${edit.tool}|${edit.path}`;
|
|
}
|
|
|
|
function latestFileEditEvents(edits: UIFileEdit[]): UIFileEdit[] {
|
|
const order: string[] = [];
|
|
const byKey = new Map<string, UIFileEdit>();
|
|
for (const edit of edits) {
|
|
const key = fileEditCallKey(edit);
|
|
if (!byKey.has(key)) order.push(key);
|
|
byKey.set(key, edit);
|
|
}
|
|
return order.map((key) => byKey.get(key)).filter(Boolean) as UIFileEdit[];
|
|
}
|
|
|
|
/** Keep each edit at the point where its call first appeared. Later lifecycle
|
|
* events update that row in place instead of moving completed edits to the end. */
|
|
function summarizeFileEditsByMessage(
|
|
messages: UIMessage[],
|
|
active: boolean,
|
|
): Map<string, FileEditSummary[]> {
|
|
const messageByEdit = new Map<string, string>();
|
|
const edits: UIFileEdit[] = [];
|
|
for (const message of messages) {
|
|
for (const edit of message.fileEdits ?? []) {
|
|
const key = fileEditCallKey(edit);
|
|
if (!messageByEdit.has(key)) messageByEdit.set(key, message.id);
|
|
edits.push(edit);
|
|
}
|
|
}
|
|
|
|
const grouped = new Map<string, FileEditSummary[]>();
|
|
for (const edit of summarizeFileEdits(edits, active)) {
|
|
const messageId = messageByEdit.get(edit.key);
|
|
if (!messageId) continue;
|
|
const group = grouped.get(messageId) ?? [];
|
|
group.push(edit);
|
|
grouped.set(messageId, group);
|
|
}
|
|
return grouped;
|
|
}
|
|
|
|
function summarizeFileEdits(edits: UIFileEdit[], active: boolean): FileEditSummary[] {
|
|
return latestFileEditEvents(edits).flatMap((edit) => {
|
|
const editing = active && edit.status === "editing";
|
|
const failed = edit.status === "error";
|
|
if (!edit.path && edit.pending && !editing) return [];
|
|
if (!edit.path && !editing && !failed) return [];
|
|
|
|
const status: UIFileEdit["status"] = editing
|
|
? "editing"
|
|
: failed
|
|
? "error"
|
|
: "done";
|
|
const binary = !!edit.binary;
|
|
return [{
|
|
key: fileEditCallKey(edit),
|
|
path: edit.path || "",
|
|
absolute_path: edit.absolute_path,
|
|
added: binary ? 0 : edit.added,
|
|
deleted: binary ? 0 : edit.deleted,
|
|
approximate: active && !!edit.approximate,
|
|
binary,
|
|
status,
|
|
operation: edit.operation,
|
|
pending: !!edit.pending && !edit.path,
|
|
error: edit.error,
|
|
diff: edit.diff,
|
|
}];
|
|
});
|
|
}
|
|
|
|
function CliRunGroup({
|
|
runs,
|
|
active,
|
|
cliAppsByName,
|
|
}: {
|
|
runs: CliRunSummary[];
|
|
active: boolean;
|
|
cliAppsByName: Map<string, CliAppInfo>;
|
|
}) {
|
|
if (runs.length === 0) return null;
|
|
return (
|
|
<>
|
|
{runs.map((run) => (
|
|
<CliRunRow
|
|
key={run.key}
|
|
run={run}
|
|
active={active}
|
|
app={cliAppsByName.get(run.name.toLowerCase())}
|
|
/>
|
|
))}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function CliRunRow({ run, active, app }: { run: CliRunSummary; active: boolean; app?: CliAppInfo }) {
|
|
const { t } = useTranslation();
|
|
const args = compactActivityPath(redactShellCommand(formatCliArgs(run)));
|
|
const failed = run.status === "error";
|
|
const rowActive = active && run.status === "running";
|
|
const color = failed ? "#DC2626" : app?.brand_color || "#0891B2";
|
|
const logoUrls = useMemo(() => logoFallbackUrls(app?.logo_url), [app?.logo_url]);
|
|
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
|
|
const displayName = app?.display_name || titleFromPresetName(run.name);
|
|
const label = t(
|
|
`message.${failed ? "cliActivityFailedOne" : rowActive ? "cliActivityRunningOne" : "cliActivityRanOne"}`,
|
|
{ name: displayName },
|
|
);
|
|
|
|
return (
|
|
<ActivityStep
|
|
active={rowActive}
|
|
tone={failed ? "error" : rowActive ? "active" : run.status === "done" ? "success" : "neutral"}
|
|
label={label}
|
|
detail={args}
|
|
detailClassName="font-mono text-[12px]"
|
|
marker={(
|
|
<span
|
|
data-testid={`activity-cli-logo-${run.name.toLowerCase()}`}
|
|
className={cn(
|
|
"grid h-4 w-4 shrink-0 place-items-center overflow-hidden rounded-mark text-[6.5px] font-semibold text-white",
|
|
rowActive && "animate-pulse",
|
|
)}
|
|
style={{ backgroundColor: logoUrl ? "transparent" : color }}
|
|
aria-hidden
|
|
>
|
|
{logoUrl ? (
|
|
<img
|
|
src={logoUrl}
|
|
alt=""
|
|
decoding="async"
|
|
loading="lazy"
|
|
className="h-full w-full object-contain"
|
|
onLoad={onLogoLoad}
|
|
onError={onLogoError}
|
|
/>
|
|
) : app ? (
|
|
cliAppInitials(app).slice(0, 2)
|
|
) : (
|
|
<Terminal className="h-3 w-3" aria-hidden />
|
|
)}
|
|
</span>
|
|
)}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function McpRunGroup({
|
|
runs,
|
|
active,
|
|
mcpPresetsByName,
|
|
}: {
|
|
runs: McpRunSummary[];
|
|
active: boolean;
|
|
mcpPresetsByName: Map<string, McpPresetInfo>;
|
|
}) {
|
|
if (runs.length === 0) return null;
|
|
return (
|
|
<>
|
|
{runs.map((run) => (
|
|
<McpRunRow
|
|
key={run.key}
|
|
run={run}
|
|
active={active}
|
|
preset={mcpPresetsByName.get(run.presetName.toLowerCase())}
|
|
/>
|
|
))}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function McpRunRow({ run, active, preset }: { run: McpRunSummary; active: boolean; preset?: McpPresetInfo }) {
|
|
const { t } = useTranslation();
|
|
const failed = run.status === "error";
|
|
const rowActive = active && run.status === "running";
|
|
const color = failed ? "#DC2626" : preset?.brand_color || "#6D5DF6";
|
|
const logoUrls = useMemo(() => logoFallbackUrls(preset?.logo_url), [preset?.logo_url]);
|
|
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
|
|
const displayName = preset?.display_name || run.displayName;
|
|
const activity = describeMcpActivity(
|
|
run.toolName,
|
|
run.args,
|
|
failed ? "error" : rowActive ? "running" : "done",
|
|
t,
|
|
);
|
|
const label = formatActivityTarget(t, activity.action, activity.target ?? "");
|
|
|
|
return (
|
|
<ActivityStep
|
|
active={rowActive}
|
|
tone={failed ? "error" : rowActive ? "active" : run.status === "done" ? "success" : "neutral"}
|
|
label={label}
|
|
detail={displayName}
|
|
marker={(
|
|
<span
|
|
data-testid={`activity-mcp-logo-${run.presetName.toLowerCase()}`}
|
|
className={cn(
|
|
"grid h-4 w-4 shrink-0 place-items-center overflow-hidden rounded-mark text-[6.5px] font-semibold text-white",
|
|
rowActive && "animate-pulse",
|
|
)}
|
|
style={{ backgroundColor: logoUrl ? "transparent" : color }}
|
|
aria-hidden
|
|
>
|
|
{logoUrl ? (
|
|
<img
|
|
src={logoUrl}
|
|
alt=""
|
|
decoding="async"
|
|
loading="lazy"
|
|
className="h-full w-full object-contain"
|
|
onLoad={onLogoLoad}
|
|
onError={onLogoError}
|
|
/>
|
|
) : preset ? (
|
|
mcpPresetInitials(preset).slice(0, 2)
|
|
) : (
|
|
<McpIcon className="h-3 w-3" aria-hidden />
|
|
)}
|
|
</span>
|
|
)}
|
|
/>
|
|
);
|
|
}
|