fix(webui): clarify command session activity
This commit is contained in:
1 parent
c80ae65746
commit
de9cce45b4
28 files changed
+1174
-68
No files matched your search
@@ -8,6 +8,7 @@ import {
|
||||
Fragment,
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
@@ -28,6 +29,8 @@ import {
|
||||
} 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,
|
||||
@@ -46,6 +49,7 @@ import { webSearchRunsByTraceLine } from "@/components/thread/activity/web-searc
|
||||
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";
|
||||
@@ -555,6 +559,7 @@ const ActivityMessageTimeline = memo(function ActivityMessageTimeline({
|
||||
<ActivityTraceTimeline
|
||||
message={message}
|
||||
active={active && index === messages.length - 1}
|
||||
turnActive={active}
|
||||
cliAppsByName={cliAppsByName}
|
||||
mcpPresetsByName={mcpPresetsByName}
|
||||
/>
|
||||
@@ -662,18 +667,125 @@ function ActivityTraceList({
|
||||
);
|
||||
}
|
||||
|
||||
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 lines = traceLines(message);
|
||||
const entries = foldSessionChecks(activityTraceEntries(message));
|
||||
const cliRunsByLine = cliRunMapByTraceLine(message);
|
||||
const mcpRunsByLine = mcpRunMapByTraceLine(message);
|
||||
const webSearchRunsByLine = webSearchRunsByTraceLine(message.toolEvents ?? []);
|
||||
@@ -695,7 +807,22 @@ function ActivityTraceTimeline({
|
||||
normalLines = [];
|
||||
};
|
||||
|
||||
lines.forEach((line, index) => {
|
||||
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) {
|
||||
@@ -787,6 +914,44 @@ function ActivityTraceTimeline({
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -938,14 +1103,6 @@ function cliRunError(event: ToolProgressEvent): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function toolEventName(event: ToolProgressEvent): string {
|
||||
return typeof (event as { function?: { name?: unknown } }).function?.name === "string"
|
||||
? String((event as { function?: { name?: unknown } }).function?.name)
|
||||
: typeof event.name === "string"
|
||||
? event.name
|
||||
: "";
|
||||
}
|
||||
|
||||
function cliRunFromArguments(
|
||||
argsObject: unknown,
|
||||
options: { key: string; status: CliRunStatus; error?: string },
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useMemo } from "react";
|
||||
import { SubagentThreadView } from "@/components/thread/SubagentThreadView";
|
||||
import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context";
|
||||
import { execSessionCommands } from "@/components/thread/activity/exec-session-model";
|
||||
import { useSubagentThread } from "@/components/thread/useSubagentThread";
|
||||
import type { SubagentTaskSnapshot } from "@/lib/types";
|
||||
|
||||
@@ -12,6 +15,9 @@ interface SubagentThreadProps {
|
||||
|
||||
export function SubagentThread({ token, sessionKey, task, historyEnabled, isStreaming }: SubagentThreadProps) {
|
||||
const { messages, loading, error, activeTurnId, retry } = useSubagentThread({ token, sessionKey, task, historyEnabled });
|
||||
return <SubagentThreadView messages={messages} loading={loading} error={error} isStreaming={isStreaming}
|
||||
activeTurnId={activeTurnId} runStartedAt={task.created_at} onRetry={retry} />;
|
||||
const commands = useMemo(() => execSessionCommands(messages), [messages]);
|
||||
return <ExecSessionCommandsContext.Provider value={commands}>
|
||||
<SubagentThreadView messages={messages} loading={loading} error={error} isStreaming={isStreaming}
|
||||
activeTurnId={activeTurnId} runStartedAt={task.created_at} onRetry={retry} />
|
||||
</ExecSessionCommandsContext.Provider>;
|
||||
}
|
||||
@@ -37,6 +37,8 @@ import { ThreadHeader } from "@/components/thread/ThreadHeader";
|
||||
import { ThreadLoadingSkeleton } from "@/components/thread/ThreadLoadingSkeleton";
|
||||
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
|
||||
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
|
||||
import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context";
|
||||
import { execSessionCommands } from "@/components/thread/activity/exec-session-model";
|
||||
import { useNanobotStream, type SendAttachment, type SendOptions } from "@/hooks/useNanobotStream";
|
||||
import { useFilePreviewState, type FilePreviewState, type FilePreviewStore } from "@/hooks/useFilePreviewState";
|
||||
import {
|
||||
@@ -558,6 +560,7 @@ export function ThreadShell({
|
||||
}, [chatId, onTurnEnd]);
|
||||
const {
|
||||
messages,
|
||||
execSourceMessages,
|
||||
modelRequests,
|
||||
messagesKey,
|
||||
messagesReady,
|
||||
@@ -598,7 +601,11 @@ export function ThreadShell({
|
||||
const showTemporaryChatControl =
|
||||
!hideHeader && !session && !loading && !!onTemporaryChatEnabledChange;
|
||||
const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);
|
||||
const updateNavigationMessages = promptNavigation.updateMessages;
|
||||
const sessionCommands = useMemo(
|
||||
() => messagesReady ? execSessionCommands(execSourceMessages ?? [], promptNavigation.window?.messages ?? []) : new Map<string, string>(),
|
||||
[execSourceMessages, messagesReady, promptNavigation.window?.messages],
|
||||
);
|
||||
const expandNavigationTraceDetail = promptNavigation.expandTraceDetail;
|
||||
useEffect(() => {
|
||||
if (!chatId || !messagesReady) return;
|
||||
messageCacheRef.current.setLoadedMessages(chatId, promptNavigation.window
|
||||
@@ -613,13 +620,9 @@ export function ThreadShell({
|
||||
const details = await loadBodyTraceDetails(refs);
|
||||
for (const detail of details) {
|
||||
const projected = projectThreadEvents(detail.events);
|
||||
updateNavigationMessages((current) => current.flatMap((message) => (
|
||||
message.traceDetail?.ref === detail.ref
|
||||
? projected.map((row) => ({ ...row, activitySegmentId: message.activitySegmentId }))
|
||||
: [message]
|
||||
)));
|
||||
expandNavigationTraceDetail(detail.ref, projected);
|
||||
}
|
||||
}, [loadBodyTraceDetails, updateNavigationMessages]);
|
||||
}, [expandNavigationTraceDetail, loadBodyTraceDetails]);
|
||||
|
||||
useEffect(() => {
|
||||
if (chatId && historyKey) sessionKeyByChatIdRef.current.set(chatId, historyKey);
|
||||
@@ -1476,6 +1479,7 @@ export function ThreadShell({
|
||||
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
|
||||
>
|
||||
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
|
||||
<ExecSessionCommandsContext.Provider value={sessionCommands}>
|
||||
<ThreadViewport
|
||||
ref={viewportRef}
|
||||
messages={displayMessages}
|
||||
@@ -1513,6 +1517,7 @@ export function ThreadShell({
|
||||
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
|
||||
onQuoteSelection={session ? handleQuoteSelection : undefined}
|
||||
/>
|
||||
</ExecSessionCommandsContext.Provider>
|
||||
</FileActionsProvider>
|
||||
</FilePreviewAvailabilityProvider>
|
||||
</div>
|
||||
|
||||
@@ -28,7 +28,10 @@ export function redactActivityText(value: string): string {
|
||||
}
|
||||
|
||||
export function redactShellCommand(command: string): string {
|
||||
return redactActivityText(command).replaceAll("<redacted>", "••••");
|
||||
return redactActivityText(command)
|
||||
.replace(/(^|[\s;])(-u(?:=|\s+)|--(?:proxy-)?user(?:=|\s+))(?:"(?:\\.|[^"\\])*"|'[^']*'|[^\s;]+)/gim, "$1$2<redacted>")
|
||||
.replace(/(^|[\s;])(-u)(?:"(?:\\.|[^"\\])*"|'[^']*'|[^\s;]*:[^\s;]+)/gim, "$1$2<redacted>")
|
||||
.replaceAll("<redacted>", "••••");
|
||||
}
|
||||
|
||||
export function compactActivityPath(value: string): string {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
/** Commands from exec events in the currently loaded transcript only. */
|
||||
export const ExecSessionCommandsContext = createContext<ReadonlyMap<string, string>>(new Map());
|
||||
@@ -0,0 +1,213 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import type { ToolProgressEvent, UIMessage } from "@/lib/types";
|
||||
import { summarizeShellCommand } from "./activity-text";
|
||||
import type { ActivityStepTone } from "./ActivityStep";
|
||||
|
||||
interface SessionObservation {
|
||||
kind: "running" | "stopping" | "exited" | "terminated" | "timeout" | "idle-timeout" | "unknown";
|
||||
exitCode?: number;
|
||||
waitTimedOut?: boolean;
|
||||
}
|
||||
|
||||
export interface ExecSessionPresentation {
|
||||
label: string;
|
||||
detail: string;
|
||||
aside?: string;
|
||||
observation?: string;
|
||||
active: boolean;
|
||||
tone: ActivityStepTone;
|
||||
}
|
||||
|
||||
const ERROR_HINT = "\n\n[Consider this result in the context of the user's goal and decide whether and how to proceed.]";
|
||||
const INITIAL_WAIT = "\nInitial wait ended; session remains active.";
|
||||
const WAIT_TIMEOUT = /\nWait timed out after [\d.]+s; session remains active\.$/;
|
||||
const WAIT_NOT_OBSERVED = /\nWait target not observed: [^\n]*$/;
|
||||
const ELAPSED = /\nElapsed: \d+(?:\.\d+)?s$/;
|
||||
|
||||
export function toolEventArguments(event: ToolProgressEvent): Record<string, unknown> {
|
||||
const functionArgs = (event as { function?: { arguments?: unknown } }).function?.arguments;
|
||||
let args = functionArgs ?? event.arguments;
|
||||
if (typeof args === "string") {
|
||||
try {
|
||||
args = JSON.parse(args) as unknown;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
return args && typeof args === "object" && !Array.isArray(args) ? args as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
export function toolEventName(event: ToolProgressEvent): string {
|
||||
const functionName = (event as { function?: { name?: unknown } }).function?.name;
|
||||
return typeof functionName === "string" ? functionName : typeof event.name === "string" ? event.name : "";
|
||||
}
|
||||
|
||||
/** Only examine the formatter's final lines, never status-like text earlier in output. */
|
||||
function parseSessionObservation(value: unknown, expectedId?: string): SessionObservation {
|
||||
if (typeof value !== "string") return { kind: "unknown" };
|
||||
let tail = value.slice(-16_384);
|
||||
if (tail.endsWith(ERROR_HINT)) tail = tail.slice(0, -ERROR_HINT.length);
|
||||
if (tail.endsWith(INITIAL_WAIT)) tail = tail.slice(0, -INITIAL_WAIT.length);
|
||||
const waitTimedOut = WAIT_TIMEOUT.test(tail);
|
||||
tail = tail.replace(WAIT_TIMEOUT, "").replace(WAIT_NOT_OBSERVED, "");
|
||||
if (!ELAPSED.test(tail)) return { kind: "unknown" };
|
||||
tail = tail.replace(ELAPSED, "");
|
||||
|
||||
const running = /(?:^|\n)Process (running|stopping)\. session_id: ([a-f0-9]{12})\n(?:Output silent for \d+(?:\.\d+)?s; no stdout\/stderr bytes observed\. This does not establish a stall\.\n)?Runtime remaining: (?:unlimited|\d+(?:\.\d+)?s)$/.exec(tail);
|
||||
if (running && (!expectedId || running[2] === expectedId)) {
|
||||
return { kind: running[1] === "running" ? "running" : "stopping", waitTimedOut };
|
||||
}
|
||||
|
||||
const exit = /(?:^|\n)Exit code: (-?\d+)$/.exec(tail);
|
||||
if (!exit || waitTimedOut) return { kind: "unknown" };
|
||||
const exitCode = Number(exit[1]);
|
||||
let beforeExit = tail.slice(0, exit.index);
|
||||
beforeExit = beforeExit.replace(/(?:^|\n)Stdin closed\.$/, "");
|
||||
beforeExit = beforeExit.replace(/(?:^|\n)Output collection ended before EOF; output may be incomplete\.$/, "");
|
||||
if (/(?:^|\n)Error: Command timed out; session was terminated\. Reason: max_runtime\.$/.test(beforeExit)) {
|
||||
return { kind: "timeout", exitCode };
|
||||
}
|
||||
if (/(?:^|\n)Error: Output silence limit reached; session was terminated\. Reason: idle_timeout\.$/.test(beforeExit)) {
|
||||
return { kind: "idle-timeout", exitCode };
|
||||
}
|
||||
if (/(?:^|\n)Session terminated\. Reason: (?:cancelled|owner_closed|shutdown)\.$/.test(beforeExit)) {
|
||||
return { kind: "terminated", exitCode };
|
||||
}
|
||||
return { kind: "exited", exitCode };
|
||||
}
|
||||
|
||||
/** Only routine, successful running checks can be folded without hiding another action. */
|
||||
export function passiveRunningCheckSessionId(event: ToolProgressEvent): string | undefined {
|
||||
if (event.phase !== "end") return undefined;
|
||||
const args = toolEventArguments(event);
|
||||
if (typeof args.session_id !== "string" || args.input != null || args.close_stdin || args.terminate || args.wait_for) return undefined;
|
||||
return parseSessionObservation(event.result, args.session_id).kind === "running" ? args.session_id : undefined;
|
||||
}
|
||||
|
||||
export function sessionIdFromExecResult(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const tail = value.slice(-16_384);
|
||||
if (!tail.endsWith(INITIAL_WAIT)) return undefined;
|
||||
const match = /(?:^|\n)Process (?:running|stopping)\. session_id: ([a-f0-9]{12})\n(?:Output silent for \d+(?:\.\d+)?s; no stdout\/stderr bytes observed\. This does not establish a stall\.\n)?Runtime remaining: (?:unlimited|\d+(?:\.\d+)?s)\nElapsed: \d+(?:\.\d+)?s\nInitial wait ended; session remains active\.$/.exec(tail);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
/** Build from loaded transcript sources, not the currently visible activity slice. */
|
||||
export function execSessionCommands(...groups: readonly UIMessage[][]): ReadonlyMap<string, string> {
|
||||
const commands = new Map<string, string>();
|
||||
const ambiguous = new Set<string>();
|
||||
for (const messages of groups) {
|
||||
for (const message of messages) {
|
||||
for (const event of message.toolEvents ?? []) {
|
||||
if (toolEventName(event) !== "exec" || event.phase !== "end") continue;
|
||||
const id = sessionIdFromExecResult(event.result);
|
||||
if (!id || ambiguous.has(id)) continue;
|
||||
const args = toolEventArguments(event);
|
||||
const command = typeof args.command === "string" && args.command.trim()
|
||||
? args.command : typeof args.cmd === "string" ? args.cmd : "";
|
||||
if (!command.trim()) continue;
|
||||
const previous = commands.get(id);
|
||||
if (previous !== undefined && previous !== command) {
|
||||
commands.delete(id);
|
||||
ambiguous.add(id);
|
||||
} else {
|
||||
commands.set(id, command);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return commands;
|
||||
}
|
||||
|
||||
function observationLabel(observation: SessionObservation, t: TFunction): { label: string; tone: ActivityStepTone } | undefined {
|
||||
const text = (key: string, options?: Record<string, unknown>) => t(`message.agentActivity.${key}`, options);
|
||||
switch (observation.kind) {
|
||||
case "running":
|
||||
return { label: text(observation.waitTimedOut ? "commandWaitTimedOut" : "commandWasRunning"), tone: "neutral" };
|
||||
case "stopping":
|
||||
return { label: text("commandWasStopping"), tone: "neutral" };
|
||||
case "exited":
|
||||
return observation.exitCode === 0
|
||||
? { label: text("commandCompleted"), tone: "success" }
|
||||
: { label: text("commandExitFailed", { code: observation.exitCode }), tone: "error" };
|
||||
case "terminated":
|
||||
// This optional line can also be the last line of stdout; only the exit is certain.
|
||||
return { label: text("commandExited", { code: observation.exitCode }), tone: "neutral" };
|
||||
case "timeout":
|
||||
return { label: text("commandTimedOut"), tone: "error" };
|
||||
case "idle-timeout":
|
||||
return { label: text("commandIdleTimedOut"), tone: "error" };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function describeExecSession(
|
||||
event: ToolProgressEvent,
|
||||
turnActive: boolean,
|
||||
command: string | undefined,
|
||||
t: TFunction,
|
||||
): ExecSessionPresentation {
|
||||
const args = toolEventArguments(event);
|
||||
const hasInput = typeof args.input === "string" && args.input.length > 0;
|
||||
const closeInput = args.close_stdin === true;
|
||||
const stop = args.terminate === true;
|
||||
const action = stop ? "stop" : hasInput && closeInput ? "sendClose" : hasInput ? "send" : closeInput ? "close" : "check";
|
||||
const copy = (key: string) => t(`message.agentActivity.${key}`);
|
||||
const preview = command ? summarizeShellCommand(command, t) : { detail: "" };
|
||||
|
||||
if (event.phase === "start" || !event.phase) {
|
||||
const labels = {
|
||||
stop: "stoppingCommand", sendClose: "sendingClosingInput", send: "sendingCommandInput",
|
||||
close: "closingCommandInput", check: args.wait_for ? "waitingCommandOutput" : "waitingCommandResult",
|
||||
};
|
||||
return {
|
||||
...preview,
|
||||
label: copy(turnActive ? labels[action] : "commandStatusUnknown"),
|
||||
active: turnActive,
|
||||
tone: turnActive ? "active" : "neutral",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.phase !== "end" && event.phase !== "error") {
|
||||
return { ...preview, label: copy("commandStatusUnknown"), active: false, tone: "neutral" };
|
||||
}
|
||||
|
||||
let observation = parseSessionObservation(
|
||||
event.phase === "error" ? event.error : event.result,
|
||||
typeof args.session_id === "string" ? args.session_id : undefined,
|
||||
);
|
||||
// A successful tool return cannot be a runtime timeout. Its stdout may end
|
||||
// with text that resembles the optional timeout reason line.
|
||||
if (event.phase !== "error" && (observation.kind === "timeout" || observation.kind === "idle-timeout")) {
|
||||
observation = { kind: "exited", exitCode: observation.exitCode };
|
||||
}
|
||||
const observed = observationLabel(observation, t);
|
||||
if (event.phase === "error" && observation.kind !== "timeout" && observation.kind !== "idle-timeout") {
|
||||
const errors = {
|
||||
stop: "stopCommandError", sendClose: "sendCloseInputError", send: "sendInputError",
|
||||
close: "closeInputError", check: "checkCommandError",
|
||||
};
|
||||
return { ...preview, label: copy(errors[action]), active: false, tone: "error" };
|
||||
}
|
||||
|
||||
const completed = {
|
||||
sendClose: "sentClosedInput", send: "sentCommandInput", close: "closedCommandInput",
|
||||
};
|
||||
if (action === "send" || action === "close" || action === "sendClose") {
|
||||
return {
|
||||
...preview,
|
||||
label: copy(completed[action]),
|
||||
observation: observed?.label ?? copy("commandStatusUnknown"),
|
||||
active: false,
|
||||
tone: observed?.tone ?? "neutral",
|
||||
};
|
||||
}
|
||||
return {
|
||||
...preview,
|
||||
label: observed?.label ?? copy("commandCheckedUnknown"),
|
||||
active: false,
|
||||
tone: observed?.tone ?? "neutral",
|
||||
};
|
||||
}
|
||||
@@ -71,6 +71,7 @@ const EXCLUDED_TOOLS = new Set([
|
||||
"cli_anything_run",
|
||||
"edit_file",
|
||||
"exec",
|
||||
"exec_session",
|
||||
"exec_command",
|
||||
"execute_command",
|
||||
"run_cli_app",
|
||||
@@ -280,8 +281,6 @@ function activityLabel(
|
||||
return activityStatus(t, status, "startingLongTask", "startedLongTask", "startLongTaskFailed");
|
||||
case "update_goal":
|
||||
return activityStatus(t, status, "updatingLongTask", "updatedLongTask", "updateLongTaskFailed");
|
||||
case "exec_session":
|
||||
return activityStatus(t, status, "continuingCommand", "continuedCommand", "continueCommandFailed");
|
||||
case "list_exec_sessions":
|
||||
return activityStatus(t, status, "checkingRunningCommands", "checkedRunningCommands", "checkRunningCommandsFailed");
|
||||
case "screenshot":
|
||||
@@ -333,8 +332,6 @@ function activityDetail(items: GenericToolRunItem[], family: ToolFamily, name: s
|
||||
return safeText(fieldValue(trace, "ui_summary"));
|
||||
case "update_goal":
|
||||
return safeText(fieldValue(trace, "action"));
|
||||
case "exec_session":
|
||||
return compactIdentifier(fieldValue(trace, "session_id"));
|
||||
case "screenshot":
|
||||
case "capture_screenshot":
|
||||
return "";
|
||||
@@ -396,12 +393,6 @@ function quote(value: string): string {
|
||||
return safe ? `“${safe}”` : "";
|
||||
}
|
||||
|
||||
function compactIdentifier(value: string): string {
|
||||
const safe = safeText(value);
|
||||
if (safe.length <= 16) return safe;
|
||||
return `${safe.slice(0, 7)}…${safe.slice(-5)}`;
|
||||
}
|
||||
|
||||
function humanizeToolName(name: string): string {
|
||||
const words = name
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
|
||||
Reference in new issue
Block a user