From de9cce45b424176e88e9b701fdede5d2fca916de Mon Sep 17 00:00:00 2001 From: chengyongru Date: Fri, 13 Nov 2026 19:16:03 +0800 Subject: [PATCH] fix(webui): clarify command session activity --- webui/browser/exec-session-fixture.tsx | 48 ++++ webui/browser/exec-session.spec.ts | 30 +++ webui/browser/fixture.tsx | 3 + .../thread/AgentActivityCluster.tsx | 177 ++++++++++++++- .../src/components/thread/SubagentThread.tsx | 10 +- webui/src/components/thread/ThreadShell.tsx | 19 +- .../thread/activity/activity-text.ts | 5 +- .../thread/activity/exec-session-context.ts | 4 + .../thread/activity/exec-session-model.ts | 213 ++++++++++++++++++ .../thread/activity/generic-tool-model.ts | 11 +- webui/src/hooks/useNanobotStream.ts | 31 ++- webui/src/hooks/usePromptHistory.ts | 29 ++- webui/src/i18n/locales/en/common.json | 26 +++ webui/src/i18n/locales/es/common.json | 26 +++ webui/src/i18n/locales/fr/common.json | 26 +++ webui/src/i18n/locales/id/common.json | 26 +++ webui/src/i18n/locales/ja/common.json | 26 +++ webui/src/i18n/locales/ko/common.json | 26 +++ webui/src/i18n/locales/pt-BR/common.json | 26 +++ webui/src/i18n/locales/vi/common.json | 26 +++ webui/src/i18n/locales/zh-CN/common.json | 26 +++ webui/src/i18n/locales/zh-TW/common.json | 26 +++ .../src/tests/agent-activity-cluster.test.tsx | 124 ++++++++++ webui/src/tests/exec-session-model.test.ts | 127 +++++++++++ webui/src/tests/generic-tool-model.test.ts | 15 +- webui/src/tests/thread-shell.test.tsx | 98 +++++++- webui/src/tests/thread-viewport.test.tsx | 6 +- webui/src/tests/useNanobotStream.test.tsx | 32 +++ 28 files changed, 1174 insertions(+), 68 deletions(-) create mode 100644 webui/browser/exec-session-fixture.tsx create mode 100644 webui/browser/exec-session.spec.ts create mode 100644 webui/src/components/thread/activity/exec-session-context.ts create mode 100644 webui/src/components/thread/activity/exec-session-model.ts create mode 100644 webui/src/tests/exec-session-model.test.ts diff --git a/webui/browser/exec-session-fixture.tsx b/webui/browser/exec-session-fixture.tsx new file mode 100644 index 000000000..bb026913b --- /dev/null +++ b/webui/browser/exec-session-fixture.tsx @@ -0,0 +1,48 @@ +import { useState } from "react"; + +import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster"; +import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context"; +import { execSessionCommands } from "@/components/thread/activity/exec-session-model"; +import { formatToolCallTrace } from "@/lib/tool-traces"; +import type { ToolProgressEvent, UIMessage } from "@/lib/types"; + +const id = "012345abcdef"; +const running = `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s`; +const history: UIMessage[] = [{ + id: "source", role: "tool", kind: "trace", content: "exec()", createdAt: 1, + toolEvents: [{ name: "exec", call_id: "source", phase: "end", arguments: { command: "curl -u alice:secret-value https://example.invalid" }, + result: `${running}\nInitial wait ended; session remains active.` }], +}]; +const commands = execSessionCommands(history); +type Stage = "waiting" | "running" | "input" | "failed" | "many"; + +function sessionMessage(stage: Stage): UIMessage { + let events: ToolProgressEvent[]; + if (stage === "many") { + events = Array.from({ length: 25 }, (_, index) => ({ + name: "exec_session", call_id: `poll-${index}`, phase: "end", arguments: { session_id: id }, result: running, + })); + } else { + events = [{ name: "exec_session", call_id: "poll", arguments: { session_id: id, ...(stage === "input" ? { input: "private-stdin" } : {}) }, + phase: stage === "waiting" ? "start" : "end", + ...(stage === "waiting" ? {} : { result: stage === "failed" ? "Exit code: 7\nElapsed: 2.0s" : running }) }]; + } + const traces = events.map((event) => formatToolCallTrace(event)!); + return { id: "trace", role: "tool", kind: "trace", content: traces[0], traces, toolEvents: events, createdAt: 2 }; +} + +export function ExecSessionFixture() { + const [stage, setStage] = useState("waiting"); + return
+ +
+ + + +
+
; +} diff --git a/webui/browser/exec-session.spec.ts b/webui/browser/exec-session.spec.ts new file mode 100644 index 000000000..d6727d03a --- /dev/null +++ b/webui/browser/exec-session.spec.ts @@ -0,0 +1,30 @@ +import { expect, test } from "@playwright/test"; + +for (const width of [1280, 360]) { + test(`shows command activity and keeps long check histories inspectable at ${width}px`, async ({ page }) => { + await page.setViewportSize({ width, height: 720 }); + await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en")); + await page.goto("/browser/fixture.html?case=exec-session"); + const activity = page.getByRole("region", { name: "Command activity" }); + await expect(activity).toContainText("Waiting for command result curl -u •••• https://example.invalid"); + await page.getByRole("button", { name: "running", exact: true }).click(); + await expect(activity).toContainText("Command was still running at the last check curl -u •••• https://example.invalid"); + await page.getByRole("button", { name: "input", exact: true }).click(); + await expect(activity).toContainText("Sent input curl -u •••• https://example.invalid"); + await page.getByRole("button", { name: "failed", exact: true }).click(); + await expect(activity).toContainText("Command failed (exit code 7) curl -u •••• https://example.invalid"); + await page.getByRole("button", { name: "many", exact: true }).click(); + const disclosure = activity.getByRole("button", { name: "Show earlier command checks (24)" }); + await expect(activity.getByTestId("activity-step")).toHaveCount(1); + await disclosure.click(); + await expect(activity.getByTestId("activity-step")).toHaveCount(25); + await activity.getByRole("button", { name: "Hide earlier command checks (24)" }).click(); + await expect(activity.getByTestId("activity-step")).toHaveCount(1); + await expect(activity).not.toContainText("012345abcdef"); + await expect(activity).not.toContainText("private-stdin"); + await expect(activity).not.toContainText("secret-value"); + expect(await activity.innerHTML()).not.toContain("secret-value"); + expect(await activity.innerHTML()).not.toContain("012345abcdef"); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(width); + }); +} diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index fac7d74eb..285cf745c 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -33,6 +33,7 @@ import { ThreadLoadingFixture } from "./thread-loading-fixture"; import { AnswerOrderFixture } from "./answer-order-fixture"; import { SidebarActivityFixture } from "./sidebar-activity-fixture"; import { ActivityLogosFixture } from "./activity-logos-fixture"; +import { ExecSessionFixture } from "./exec-session-fixture"; import { HistoryHydrationFixture } from "./history-hydration-fixture"; import { IdleCompactionFixture, installIdleCompactionApi } from "./idle-compaction-fixture"; import { FileEditPathFixture } from "./file-edit-path-fixture"; @@ -262,6 +263,8 @@ createRoot(document.getElementById("root")!).render( ? : parameters.get("case") === "activity-logos" ? + : parameters.get("case") === "exec-session" + ? : parameters.get("case") === "sidebar-activity" ? : parameters.get("case") === "chat-failure" diff --git a/webui/src/components/thread/AgentActivityCluster.tsx b/webui/src/components/thread/AgentActivityCluster.tsx index 7ee840be3..4d194d1eb 100644 --- a/webui/src/components/thread/AgentActivityCluster.tsx +++ b/webui/src/components/thread/AgentActivityCluster.tsx @@ -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({ @@ -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(); + const sessionIndices = new Map(); + 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(); + 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(); + const before = new Map(); + 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; mcpPresetsByName: Map; }) { - 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(); + 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(); + 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 ( + <> + + {expanded ? earlier.map((event, index) => ( + + )) : null} + + + ); +} + +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 ( + + ); +} + 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 }, diff --git a/webui/src/components/thread/SubagentThread.tsx b/webui/src/components/thread/SubagentThread.tsx index 1d716102a..a754ca983 100644 --- a/webui/src/components/thread/SubagentThread.tsx +++ b/webui/src/components/thread/SubagentThread.tsx @@ -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 ; + const commands = useMemo(() => execSessionCommands(messages), [messages]); + return + + ; } diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index f4f78ddcd..b05a47ed0 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -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(), + [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} > + + diff --git a/webui/src/components/thread/activity/activity-text.ts b/webui/src/components/thread/activity/activity-text.ts index e31fff981..2f39986f1 100644 --- a/webui/src/components/thread/activity/activity-text.ts +++ b/webui/src/components/thread/activity/activity-text.ts @@ -28,7 +28,10 @@ export function redactActivityText(value: string): string { } export function redactShellCommand(command: string): string { - return redactActivityText(command).replaceAll("", "••••"); + return redactActivityText(command) + .replace(/(^|[\s;])(-u(?:=|\s+)|--(?:proxy-)?user(?:=|\s+))(?:"(?:\\.|[^"\\])*"|'[^']*'|[^\s;]+)/gim, "$1$2") + .replace(/(^|[\s;])(-u)(?:"(?:\\.|[^"\\])*"|'[^']*'|[^\s;]*:[^\s;]+)/gim, "$1$2") + .replaceAll("", "••••"); } export function compactActivityPath(value: string): string { diff --git a/webui/src/components/thread/activity/exec-session-context.ts b/webui/src/components/thread/activity/exec-session-context.ts new file mode 100644 index 000000000..1d2bace4f --- /dev/null +++ b/webui/src/components/thread/activity/exec-session-context.ts @@ -0,0 +1,4 @@ +import { createContext } from "react"; + +/** Commands from exec events in the currently loaded transcript only. */ +export const ExecSessionCommandsContext = createContext>(new Map()); diff --git a/webui/src/components/thread/activity/exec-session-model.ts b/webui/src/components/thread/activity/exec-session-model.ts new file mode 100644 index 000000000..1cef2960c --- /dev/null +++ b/webui/src/components/thread/activity/exec-session-model.ts @@ -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 { + 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 : {}; +} + +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 { + const commands = new Map(); + const ambiguous = new Set(); + 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) => 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", + }; +} diff --git a/webui/src/components/thread/activity/generic-tool-model.ts b/webui/src/components/thread/activity/generic-tool-model.ts index 5675296c1..4e2d2ddf6 100644 --- a/webui/src/components/thread/activity/generic-tool-model.ts +++ b/webui/src/components/thread/activity/generic-tool-model.ts @@ -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") diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 3bfaed96e..14cf83549 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -126,6 +126,8 @@ export function useNanobotStream( historyActiveTurnId: string | null = null, ): { messages: UIMessage[]; + /** Stable across text-only updates; refreshed at exec/history boundaries. */ + execSourceMessages: UIMessage[]; modelRequests: ReadonlyMap; /** Conversation owning these messages, including while a selection is handing over. */ messagesKey: string | null; @@ -178,6 +180,7 @@ export function useNanobotStream( historyRunGenerationRef.current = { chatId, generation: chatId ? client.getRunGeneration(chatId) : 0 }; } const [messages, setRenderedMessages] = useState(initialTranscript.messages); + const [execSourceMessages, setExecSourceMessages] = useState(initialTranscript.messages); const [modelRequests, setModelRequests] = useState(initialTranscript.modelRequests); const messagesRef = useRef(messages); // Keep received state ahead of React's batched render: navigation can unmount @@ -292,6 +295,7 @@ export function useNanobotStream( : projection.fileEditSegmentId, }; transcriptRef.current.rejectTurn(rejectedTurnId); + setExecSourceMessages(nextMessages); return nextMessages; }); @@ -484,6 +488,7 @@ export function useNanobotStream( useEffect(() => { transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey, temporary); setMessages(transcriptRef.current.messages); + setExecSourceMessages(transcriptRef.current.messages); setMessageScope({ chatId, historyKey, client }); setRunState(chatId ? client.getRunState(chatId) : null); setStreamError(null); @@ -504,8 +509,14 @@ export function useNanobotStream( ) => { setMessages((prev) => { transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: prev }; - return transcriptRef.current.project(event, { createId: () => crypto.randomUUID(), now: Date.now(), + const next = transcriptRef.current.project(event, { createId: () => crypto.randomUUID(), now: Date.now(), sideChannel: options?.sideChannel }); + if (event.event === "message" && event.tool_events?.some((tool) => ( + (tool.name === "exec" || (tool as { function?: { name?: unknown } }).function?.name === "exec") + && tool.phase === "end" && typeof tool.result === "string" + && tool.result.endsWith("\nInitial wait ended; session remains active.") + ))) setExecSourceMessages(next); + return next; }); }, [setMessages]); @@ -520,7 +531,7 @@ export function useNanobotStream( pending.owner.finishRead(pending.read); if (transcriptRef.current === pending.owner) publishHistory(); }, [publishHistory]); - const detailRequestsRef = useRef(new Map>()); + const detailRequestsRef = useRef(new WeakMap>>()); const reconcileCanonical = useCallback((generation: number, canonical: ReturnType, accepted: boolean) => { if (!chatId) return; const settle = !canonical.snapshot.hasPendingToolCalls @@ -552,6 +563,7 @@ export function useNanobotStream( const accepted = owner.accept(body, decision); // Commit the received owner before cache listeners/ledger callbacks can reenter. setMessages(owner.messages); + setExecSourceMessages(owner.messages); if (accepted && chatId) messageCache?.set(chatId, owner.save()); if (ownRead) { publishing = true; @@ -605,6 +617,7 @@ export function useNanobotStream( flushPendingStreamEvents(); const accepted = owner.accept(body, read); setMessages(owner.messages); + setExecSourceMessages(owner.messages); if (accepted) { if (chatId) messageCache?.set(chatId, owner.save()); settleFragment(owner); @@ -629,18 +642,25 @@ export function useNanobotStream( const loadTraceDetails = useCallback(async (refs: string[]) => { const owner = transcriptRef.current; if (!historyKey) return []; + let requests = detailRequestsRef.current.get(owner); + if (!requests) { + requests = new Map(); + detailRequestsRef.current.set(owner, requests); + } + const ownerRequests = requests; const details = await Promise.all(refs.map((ref) => { const id = `${historyKey}:${ref}`; - const existing = detailRequestsRef.current.get(id); + const existing = ownerRequests.get(id); if (existing) return existing; const request = fetchWebuiThreadTraceDetail(getToken(), historyKey, ref).then((detail) => { if (transcriptRef.current !== owner) return null; flushPendingStreamEvents(); owner.expandDetail(ref, detail.events); setMessages(owner.messages); + setExecSourceMessages(owner.messages); return { ref, events: detail.events }; - }).finally(() => detailRequestsRef.current.delete(id)); - detailRequestsRef.current.set(id, request); + }).finally(() => ownerRequests.delete(id)); + ownerRequests.set(id, request); return request; })); return details.filter((detail) => detail !== null); @@ -1062,6 +1082,7 @@ export function useNanobotStream( return { messages, + execSourceMessages, modelRequests, messagesKey: messageScope.historyKey ?? messageScope.chatId, messagesReady: messageScope.chatId === chatId && messageScope.historyKey === historyKey && messageScope.client === client, diff --git a/webui/src/hooks/usePromptHistory.ts b/webui/src/hooks/usePromptHistory.ts index 2cd0fc26c..041a772bf 100644 --- a/webui/src/hooks/usePromptHistory.ts +++ b/webui/src/hooks/usePromptHistory.ts @@ -12,6 +12,14 @@ import { type PromptAnchor, userPromptAnchors } from "@/components/thread/prompt interface HistoryPage { messages: UIMessage[]; body: WebuiThreadPersistedPayload; + details: Map; +} + +function expandDetails(messages: UIMessage[], details: ReadonlyMap): UIMessage[] { + return messages.flatMap((message) => { + const rows = message.traceDetail && details.get(message.traceDetail.ref); + return rows ? rows.map((row) => ({ ...row, activitySegmentId: message.activitySegmentId })) : [message]; + }); } const HISTORY_PAGE_LIMIT = 3; @@ -36,7 +44,7 @@ export interface PromptHistoryNavigation { cancel: () => void; latest: () => void; retry: () => void; - updateMessages: (update: (messages: UIMessage[]) => UIMessage[]) => void; + expandTraceDetail: (ref: string, rows: UIMessage[]) => void; } /** Browsing pages never replace the canonical latest page or live turn state. */ @@ -140,8 +148,12 @@ export function usePromptHistory(key: string | null, version: number, messages: return merged; }, [currentScope, enabled, index, indexed, key, messages]); - const updateMessages = useCallback((update: (messages: UIMessage[]) => UIMessage[]) => { - setPages((current) => current.map((page) => ({ ...page, messages: update(page.messages) }))); + const expandTraceDetail = useCallback((ref: string, rows: UIMessage[]) => { + setPages((current) => current.map((page) => { + if (!page.messages.some((message) => message.traceDetail?.ref === ref)) return page; + const details = new Map(page.details).set(ref, rows); + return { ...page, messages: expandDetails(page.messages, details), details }; + })); }, []); const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string, automatic = false) => { @@ -166,7 +178,7 @@ export function usePromptHistory(key: string | null, version: number, messages: if (!id && generation && previousGeneration && generation !== previousGeneration) { throw new Error("History changed; select the message again"); } - const page = { body, messages: projectWebuiThreadMessages(projectThreadEvents(body.events)) }; + const page = { body, messages: projectWebuiThreadMessages(projectThreadEvents(body.events)), details: new Map() }; if (id && !page.messages.some((message) => message.id === id)) { setRefresh((value) => value + 1); throw new Error("History changed; select the message again"); @@ -198,11 +210,14 @@ export function usePromptHistory(key: string | null, version: number, messages: const range = body.page?.record_range; if (range) { let joined = joinThreadFragments([], body); + const details = new Map(page.details); while (pages[index + 1]?.body.page?.record_range?.turn === range.turn) { - joined = joinThreadFragments(joined.pages, pages[++index].body); + const next = pages[++index]; + joined = joinThreadFragments(joined.pages, next.body); + for (const [ref, detail] of next.details) details.set(ref, detail); } body = joined.body; - rows = projectWebuiThreadMessages(projectThreadEvents(body.events)); + rows = expandDetails(projectWebuiThreadMessages(projectThreadEvents(body.events)), details); } const eventIndex = body.fork_boundary_event_index; if (eventIndex !== undefined) boundary = messages.length + projectWebuiThreadMessages(projectThreadEvents(body.events.slice(0, eventIndex))).length; @@ -228,7 +243,7 @@ export function usePromptHistory(key: string | null, version: number, messages: return { prompts, window, target: currentScope ? target : null, loading: currentScope && loading, operation: currentScope && (loading || error) ? operation : null, - error: currentScope ? error ?? indexError : null, cancel, latest, updateMessages, + error: currentScope ? error ?? indexError : null, cancel, latest, expandTraceDetail, retry: () => error ? retry.current() : setRefresh((value) => value + 1), jump: (id) => { const prompt = prompts.find((item) => item.id === id); diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 46d17e6ee..3b6bed4f0 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -2426,11 +2426,37 @@ "updatedLongTask": "Updated long task", "updateLongTaskFailed": "Could not update long task", "continuingCommand": "Continuing command", + "waitingCommandResult": "Waiting for command result", + "waitingCommandOutput": "Waiting for command output", + "sendingCommandInput": "Sending input", + "closingCommandInput": "Closing command input", + "sendingClosingInput": "Sending and closing command input", + "stoppingCommand": "Stopping command", + "commandStatusUnknown": "Command status unknown", + "commandWasRunning": "Command was still running at the last check", + "commandWaitTimedOut": "Wait timed out; command was still running at the last check", + "commandWasStopping": "Command was stopping at the last check", + "commandCompleted": "Command completed", + "commandExitFailed": "Command failed (exit code {{code}})", + "commandExited": "Command exited (exit code {{code}})", + "commandTimedOut": "Command timed out and was stopped", + "commandIdleTimedOut": "Command stopped after output silence", + "commandCheckedUnknown": "Command checked; status unknown", + "stopCommandError": "Could not stop command", + "sendCloseInputError": "Could not send or close command input", + "sendInputError": "Could not send input", + "closeInputError": "Could not close command input", + "checkCommandError": "Could not check command", + "sentClosedInput": "Sent and closed command input", + "sentCommandInput": "Sent input", + "closedCommandInput": "Closed command input", "continuedCommand": "Continued command", "continueCommandFailed": "Could not continue command", "checkingRunningCommands": "Checking running commands", "checkedRunningCommands": "Checked running commands", "checkRunningCommandsFailed": "Could not check running commands", + "showEarlierCommandChecks": "Show earlier command checks ({{count}})", + "hideEarlierCommandChecks": "Hide earlier command checks ({{count}})", "capturingScreenshot": "Capturing screenshot", "capturedScreenshot": "Captured screenshot", "captureScreenshotFailed": "Could not capture screenshot", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 95b431096..29c96229e 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -2271,11 +2271,37 @@ "updatedLongTask": "Tarea larga actualizada", "updateLongTaskFailed": "No se pudo actualizar la tarea larga", "continuingCommand": "Continuando comando", + "waitingCommandResult": "Esperando el resultado del comando", + "waitingCommandOutput": "Esperando la salida del comando", + "sendingCommandInput": "Enviando entrada", + "closingCommandInput": "Cerrando la entrada del comando", + "sendingClosingInput": "Enviando y cerrando la entrada del comando", + "stoppingCommand": "Deteniendo el comando", + "commandStatusUnknown": "Estado del comando desconocido", + "commandWasRunning": "El comando seguía en ejecución en la última comprobación", + "commandWaitTimedOut": "Se agotó el tiempo de espera; el comando seguía en ejecución en la última comprobación", + "commandWasStopping": "El comando se estaba deteniendo en la última comprobación", + "commandCompleted": "Comando completado", + "commandExitFailed": "El comando falló (código de salida {{code}})", + "commandExited": "El comando ha finalizado (código de salida {{code}})", + "commandTimedOut": "El comando superó el tiempo límite y se detuvo", + "commandIdleTimedOut": "El comando se detuvo tras un período sin salida", + "commandCheckedUnknown": "Comando comprobado; estado desconocido", + "stopCommandError": "No se pudo detener el comando", + "sendCloseInputError": "No se pudo enviar o cerrar la entrada del comando", + "sendInputError": "No se pudo enviar la entrada", + "closeInputError": "No se pudo cerrar la entrada del comando", + "checkCommandError": "No se pudo comprobar el comando", + "sentClosedInput": "Se envió y se cerró la entrada del comando", + "sentCommandInput": "Entrada enviada", + "closedCommandInput": "Entrada del comando cerrada", "continuedCommand": "Comando continuado", "continueCommandFailed": "No se pudo continuar el comando", "checkingRunningCommands": "Comprobando comandos en ejecución", "checkedRunningCommands": "Comandos en ejecución comprobados", "checkRunningCommandsFailed": "No se pudieron comprobar los comandos en ejecución", + "showEarlierCommandChecks": "Mostrar las comprobaciones anteriores de comandos ({{count}})", + "hideEarlierCommandChecks": "Ocultar las comprobaciones anteriores de comandos ({{count}})", "capturingScreenshot": "Capturando pantalla", "capturedScreenshot": "Captura de pantalla realizada", "captureScreenshotFailed": "No se pudo capturar la pantalla", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 1a9208854..1707b359f 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -2271,11 +2271,37 @@ "updatedLongTask": "Tâche longue mise à jour", "updateLongTaskFailed": "Impossible de mettre à jour la tâche longue", "continuingCommand": "Poursuite de la commande", + "waitingCommandResult": "En attente du résultat de la commande", + "waitingCommandOutput": "En attente de la sortie de la commande", + "sendingCommandInput": "Envoi de l’entrée", + "closingCommandInput": "Fermeture de l’entrée de la commande", + "sendingClosingInput": "Envoi puis fermeture de l’entrée de la commande", + "stoppingCommand": "Arrêt de la commande", + "commandStatusUnknown": "État de la commande inconnu", + "commandWasRunning": "La commande était toujours en cours d’exécution lors de la dernière vérification", + "commandWaitTimedOut": "Délai d’attente dépassé ; la commande était toujours en cours d’exécution lors de la dernière vérification", + "commandWasStopping": "La commande était en cours d’arrêt lors de la dernière vérification", + "commandCompleted": "Commande terminée", + "commandExitFailed": "Échec de la commande (code de sortie {{code}})", + "commandExited": "La commande s’est terminée (code de sortie {{code}})", + "commandTimedOut": "La commande a dépassé le délai imparti et a été arrêtée", + "commandIdleTimedOut": "La commande a été arrêtée après une période sans sortie", + "commandCheckedUnknown": "Commande vérifiée ; état inconnu", + "stopCommandError": "Impossible d’arrêter la commande", + "sendCloseInputError": "Impossible d’envoyer ou de fermer l’entrée de la commande", + "sendInputError": "Impossible d’envoyer l’entrée", + "closeInputError": "Impossible de fermer l’entrée de la commande", + "checkCommandError": "Impossible de vérifier la commande", + "sentClosedInput": "Entrée de la commande envoyée et fermée", + "sentCommandInput": "Entrée envoyée", + "closedCommandInput": "Entrée de la commande fermée", "continuedCommand": "Commande poursuivie", "continueCommandFailed": "Impossible de poursuivre la commande", "checkingRunningCommands": "Vérification des commandes en cours", "checkedRunningCommands": "Commandes en cours vérifiées", "checkRunningCommandsFailed": "Impossible de vérifier les commandes en cours", + "showEarlierCommandChecks": "Afficher les vérifications précédentes des commandes ({{count}})", + "hideEarlierCommandChecks": "Masquer les vérifications précédentes des commandes ({{count}})", "capturingScreenshot": "Capture d’écran en cours", "capturedScreenshot": "Capture d’écran effectuée", "captureScreenshotFailed": "Impossible d’effectuer la capture d’écran", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 57a2480bd..85f75873f 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -2271,11 +2271,37 @@ "updatedLongTask": "Tugas panjang diperbarui", "updateLongTaskFailed": "Tidak dapat memperbarui tugas panjang", "continuingCommand": "Melanjutkan perintah", + "waitingCommandResult": "Menunggu hasil perintah", + "waitingCommandOutput": "Menunggu keluaran perintah", + "sendingCommandInput": "Mengirim masukan", + "closingCommandInput": "Menutup masukan perintah", + "sendingClosingInput": "Mengirim dan menutup masukan perintah", + "stoppingCommand": "Menghentikan perintah", + "commandStatusUnknown": "Status perintah tidak diketahui", + "commandWasRunning": "Perintah masih berjalan pada pemeriksaan terakhir", + "commandWaitTimedOut": "Waktu tunggu habis; perintah masih berjalan pada pemeriksaan terakhir", + "commandWasStopping": "Perintah sedang dihentikan pada pemeriksaan terakhir", + "commandCompleted": "Perintah selesai", + "commandExitFailed": "Perintah gagal (kode keluar {{code}})", + "commandExited": "Perintah telah berakhir (kode keluar {{code}})", + "commandTimedOut": "Perintah melampaui batas waktu dan dihentikan", + "commandIdleTimedOut": "Perintah dihentikan setelah tidak ada keluaran selama beberapa waktu", + "commandCheckedUnknown": "Perintah diperiksa; status tidak diketahui", + "stopCommandError": "Tidak dapat menghentikan perintah", + "sendCloseInputError": "Tidak dapat mengirim atau menutup masukan perintah", + "sendInputError": "Tidak dapat mengirim masukan", + "closeInputError": "Tidak dapat menutup masukan perintah", + "checkCommandError": "Tidak dapat memeriksa perintah", + "sentClosedInput": "Masukan perintah telah dikirim dan ditutup", + "sentCommandInput": "Masukan terkirim", + "closedCommandInput": "Masukan perintah ditutup", "continuedCommand": "Perintah dilanjutkan", "continueCommandFailed": "Tidak dapat melanjutkan perintah", "checkingRunningCommands": "Memeriksa perintah yang berjalan", "checkedRunningCommands": "Perintah yang berjalan diperiksa", "checkRunningCommandsFailed": "Tidak dapat memeriksa perintah yang berjalan", + "showEarlierCommandChecks": "Tampilkan pemeriksaan perintah sebelumnya ({{count}})", + "hideEarlierCommandChecks": "Sembunyikan pemeriksaan perintah sebelumnya ({{count}})", "capturingScreenshot": "Mengambil tangkapan layar", "capturedScreenshot": "Tangkapan layar diambil", "captureScreenshotFailed": "Tidak dapat mengambil tangkapan layar", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 6acecf8e7..c031adf54 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -2271,11 +2271,37 @@ "updatedLongTask": "長期タスクを更新しました", "updateLongTaskFailed": "長期タスクを更新できませんでした", "continuingCommand": "コマンドを続行中", + "waitingCommandResult": "コマンドの結果を待機中", + "waitingCommandOutput": "コマンドの出力を待機中", + "sendingCommandInput": "入力を送信中", + "closingCommandInput": "コマンドの入力を閉じています", + "sendingClosingInput": "コマンドの入力を送信して閉じています", + "stoppingCommand": "コマンドを停止中", + "commandStatusUnknown": "コマンドの状態は不明です", + "commandWasRunning": "前回の確認時、コマンドはまだ実行中でした", + "commandWaitTimedOut": "待機がタイムアウトしました。前回の確認時、コマンドはまだ実行中でした", + "commandWasStopping": "前回の確認時、コマンドは停止処理中でした", + "commandCompleted": "コマンドが完了しました", + "commandExitFailed": "コマンドが失敗しました(終了コード {{code}})", + "commandExited": "コマンドが終了しました(終了コード {{code}})", + "commandTimedOut": "コマンドがタイムアウトしたため停止しました", + "commandIdleTimedOut": "一定時間出力がなかったためコマンドを停止しました", + "commandCheckedUnknown": "コマンドを確認しましたが、状態は不明です", + "stopCommandError": "コマンドを停止できませんでした", + "sendCloseInputError": "コマンドの入力を送信または閉じることができませんでした", + "sendInputError": "入力を送信できませんでした", + "closeInputError": "コマンドの入力を閉じることができませんでした", + "checkCommandError": "コマンドを確認できませんでした", + "sentClosedInput": "コマンドの入力を送信して閉じました", + "sentCommandInput": "入力を送信しました", + "closedCommandInput": "コマンドの入力を閉じました", "continuedCommand": "コマンドを続行しました", "continueCommandFailed": "コマンドを続行できませんでした", "checkingRunningCommands": "実行中のコマンドを確認中", "checkedRunningCommands": "実行中のコマンドを確認しました", "checkRunningCommandsFailed": "実行中のコマンドを確認できませんでした", + "showEarlierCommandChecks": "以前のコマンド確認を表示({{count}})", + "hideEarlierCommandChecks": "以前のコマンド確認を非表示({{count}})", "capturingScreenshot": "スクリーンショットを撮影中", "capturedScreenshot": "スクリーンショットを撮影しました", "captureScreenshotFailed": "スクリーンショットを撮影できませんでした", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index cbb3f5966..0783d3370 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -2271,11 +2271,37 @@ "updatedLongTask": "장기 작업 업데이트 완료", "updateLongTaskFailed": "장기 작업을 업데이트하지 못함", "continuingCommand": "명령 계속 진행 중", + "waitingCommandResult": "명령 결과를 기다리는 중", + "waitingCommandOutput": "명령 출력을 기다리는 중", + "sendingCommandInput": "입력 전송 중", + "closingCommandInput": "명령 입력을 닫는 중", + "sendingClosingInput": "명령 입력을 전송하고 닫는 중", + "stoppingCommand": "명령을 중지하는 중", + "commandStatusUnknown": "명령 상태를 알 수 없음", + "commandWasRunning": "마지막 확인 시 명령이 계속 실행 중이었음", + "commandWaitTimedOut": "대기 시간이 초과되었으며 마지막 확인 시 명령이 계속 실행 중이었음", + "commandWasStopping": "마지막 확인 시 명령이 중지되고 있었음", + "commandCompleted": "명령 완료", + "commandExitFailed": "명령 실패 (종료 코드 {{code}})", + "commandExited": "명령이 종료됨 (종료 코드 {{code}})", + "commandTimedOut": "명령이 제한 시간을 초과하여 중지됨", + "commandIdleTimedOut": "일정 시간 동안 출력이 없어 명령이 중지됨", + "commandCheckedUnknown": "명령을 확인했으나 상태를 알 수 없음", + "stopCommandError": "명령을 중지하지 못함", + "sendCloseInputError": "명령 입력을 전송하거나 닫지 못함", + "sendInputError": "입력을 전송하지 못함", + "closeInputError": "명령 입력을 닫지 못함", + "checkCommandError": "명령을 확인하지 못함", + "sentClosedInput": "명령 입력을 전송하고 닫음", + "sentCommandInput": "입력 전송 완료", + "closedCommandInput": "명령 입력 닫힘", "continuedCommand": "명령 계속 진행 완료", "continueCommandFailed": "명령을 계속 진행하지 못함", "checkingRunningCommands": "실행 중인 명령 확인 중", "checkedRunningCommands": "실행 중인 명령 확인 완료", "checkRunningCommandsFailed": "실행 중인 명령을 확인하지 못함", + "showEarlierCommandChecks": "이전 명령 확인 내역 표시 ({{count}})", + "hideEarlierCommandChecks": "이전 명령 확인 내역 숨기기 ({{count}})", "capturingScreenshot": "스크린샷 캡처 중", "capturedScreenshot": "스크린샷 캡처 완료", "captureScreenshotFailed": "스크린샷을 캡처하지 못함", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 4c982f52c..acba00ee2 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -2246,11 +2246,37 @@ "updatedLongTask": "Tarefa longa atualizada", "updateLongTaskFailed": "Não foi possível atualizar a tarefa longa", "continuingCommand": "Continuando comando", + "waitingCommandResult": "Aguardando resultado do comando", + "waitingCommandOutput": "Aguardando saída do comando", + "sendingCommandInput": "Enviando entrada", + "closingCommandInput": "Fechando entrada do comando", + "sendingClosingInput": "Enviando e fechando a entrada do comando", + "stoppingCommand": "Interrompendo comando", + "commandStatusUnknown": "Status do comando desconhecido", + "commandWasRunning": "O comando ainda estava em execução na última verificação", + "commandWaitTimedOut": "O tempo de espera se esgotou; o comando ainda estava em execução na última verificação", + "commandWasStopping": "O comando estava sendo interrompido na última verificação", + "commandCompleted": "Comando concluído", + "commandExitFailed": "Falha no comando (código de saída {{code}})", + "commandExited": "O comando terminou (código de saída {{code}})", + "commandTimedOut": "O comando excedeu o tempo limite e foi interrompido", + "commandIdleTimedOut": "O comando foi interrompido após um período sem saída", + "commandCheckedUnknown": "Comando verificado; status desconhecido", + "stopCommandError": "Não foi possível interromper o comando", + "sendCloseInputError": "Não foi possível enviar ou fechar a entrada do comando", + "sendInputError": "Não foi possível enviar a entrada", + "closeInputError": "Não foi possível fechar a entrada do comando", + "checkCommandError": "Não foi possível verificar o comando", + "sentClosedInput": "Entrada do comando enviada e fechada", + "sentCommandInput": "Entrada enviada", + "closedCommandInput": "Entrada do comando fechada", "continuedCommand": "Comando continuado", "continueCommandFailed": "Não foi possível continuar o comando", "checkingRunningCommands": "Verificando comandos em execução", "checkedRunningCommands": "Comandos em execução verificados", "checkRunningCommandsFailed": "Não foi possível verificar os comandos em execução", + "showEarlierCommandChecks": "Mostrar verificações anteriores de comandos ({{count}})", + "hideEarlierCommandChecks": "Ocultar verificações anteriores de comandos ({{count}})", "capturingScreenshot": "Capturando tela", "capturedScreenshot": "Captura de tela realizada", "captureScreenshotFailed": "Não foi possível capturar a tela", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index ea4ba64bb..bfb8da267 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -2271,11 +2271,37 @@ "updatedLongTask": "Đã cập nhật tác vụ dài", "updateLongTaskFailed": "Không thể cập nhật tác vụ dài", "continuingCommand": "Đang tiếp tục lệnh", + "waitingCommandResult": "Đang chờ kết quả lệnh", + "waitingCommandOutput": "Đang chờ đầu ra của lệnh", + "sendingCommandInput": "Đang gửi dữ liệu đầu vào", + "closingCommandInput": "Đang đóng đầu vào của lệnh", + "sendingClosingInput": "Đang gửi và đóng đầu vào của lệnh", + "stoppingCommand": "Đang dừng lệnh", + "commandStatusUnknown": "Không rõ trạng thái lệnh", + "commandWasRunning": "Lệnh vẫn đang chạy tại lần kiểm tra gần nhất", + "commandWaitTimedOut": "Hết thời gian chờ; lệnh vẫn đang chạy tại lần kiểm tra gần nhất", + "commandWasStopping": "Tại lần kiểm tra gần nhất, lệnh đang trong quá trình dừng", + "commandCompleted": "Lệnh đã hoàn tất", + "commandExitFailed": "Lệnh thất bại (mã thoát {{code}})", + "commandExited": "Lệnh đã kết thúc (mã thoát {{code}})", + "commandTimedOut": "Lệnh đã bị dừng do hết thời gian", + "commandIdleTimedOut": "Lệnh bị dừng sau một khoảng thời gian không có đầu ra", + "commandCheckedUnknown": "Đã kiểm tra lệnh; không rõ trạng thái", + "stopCommandError": "Không thể dừng lệnh", + "sendCloseInputError": "Không thể gửi hoặc đóng đầu vào của lệnh", + "sendInputError": "Không thể gửi dữ liệu đầu vào", + "closeInputError": "Không thể đóng đầu vào của lệnh", + "checkCommandError": "Không thể kiểm tra lệnh", + "sentClosedInput": "Đã gửi và đóng đầu vào của lệnh", + "sentCommandInput": "Đã gửi dữ liệu đầu vào", + "closedCommandInput": "Đã đóng đầu vào của lệnh", "continuedCommand": "Đã tiếp tục lệnh", "continueCommandFailed": "Không thể tiếp tục lệnh", "checkingRunningCommands": "Đang kiểm tra lệnh đang chạy", "checkedRunningCommands": "Đã kiểm tra lệnh đang chạy", "checkRunningCommandsFailed": "Không thể kiểm tra lệnh đang chạy", + "showEarlierCommandChecks": "Hiển thị các lần kiểm tra lệnh trước đó ({{count}})", + "hideEarlierCommandChecks": "Ẩn các lần kiểm tra lệnh trước đó ({{count}})", "capturingScreenshot": "Đang chụp màn hình", "capturedScreenshot": "Đã chụp màn hình", "captureScreenshotFailed": "Không thể chụp màn hình", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 0992103d7..ae58bc8be 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -2425,11 +2425,37 @@ "updatedLongTask": "已更新长期任务", "updateLongTaskFailed": "无法更新长期任务", "continuingCommand": "正在继续命令", + "waitingCommandResult": "正在等待命令结果", + "waitingCommandOutput": "正在等待命令输出", + "sendingCommandInput": "正在发送输入", + "closingCommandInput": "正在关闭命令输入", + "sendingClosingInput": "正在发送并关闭命令输入", + "stoppingCommand": "正在停止命令", + "commandStatusUnknown": "命令状态未知", + "commandWasRunning": "上次检查时命令仍在运行", + "commandWaitTimedOut": "等待超时,上次检查时命令仍在运行", + "commandWasStopping": "上次检查时命令正在停止", + "commandCompleted": "命令已完成", + "commandExitFailed": "命令执行失败(退出码 {{code}})", + "commandExited": "命令已结束(退出码 {{code}})", + "commandTimedOut": "命令超时,已终止", + "commandIdleTimedOut": "命令因输出静默超时而终止", + "commandCheckedUnknown": "已检查命令,状态未知", + "stopCommandError": "停止命令时出错", + "sendCloseInputError": "发送或关闭命令输入时出错", + "sendInputError": "发送输入时出错", + "closeInputError": "关闭命令输入时出错", + "checkCommandError": "检查命令时出错", + "sentClosedInput": "已发送并关闭命令输入", + "sentCommandInput": "已发送输入", + "closedCommandInput": "已关闭命令输入", "continuedCommand": "已继续命令", "continueCommandFailed": "无法继续命令", "checkingRunningCommands": "正在检查运行中的命令", "checkedRunningCommands": "已检查运行中的命令", "checkRunningCommandsFailed": "无法检查运行中的命令", + "showEarlierCommandChecks": "展开之前的命令检查({{count}})", + "hideEarlierCommandChecks": "收起之前的命令检查({{count}})", "capturingScreenshot": "正在截取屏幕截图", "capturedScreenshot": "已截取屏幕截图", "captureScreenshotFailed": "无法截取屏幕截图", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 336be0532..12a918888 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -2270,11 +2270,37 @@ "updatedLongTask": "已更新長期任務", "updateLongTaskFailed": "無法更新長期任務", "continuingCommand": "正在繼續命令", + "waitingCommandResult": "正在等待命令結果", + "waitingCommandOutput": "正在等待命令輸出", + "sendingCommandInput": "正在傳送輸入", + "closingCommandInput": "正在關閉命令輸入", + "sendingClosingInput": "正在傳送並關閉命令輸入", + "stoppingCommand": "正在停止命令", + "commandStatusUnknown": "命令狀態未知", + "commandWasRunning": "上次檢查時命令仍在執行", + "commandWaitTimedOut": "等待逾時,上次檢查時命令仍在執行", + "commandWasStopping": "上次檢查時命令正在停止", + "commandCompleted": "命令已完成", + "commandExitFailed": "命令執行失敗(結束代碼 {{code}})", + "commandExited": "命令已結束(結束代碼 {{code}})", + "commandTimedOut": "命令逾時,已終止", + "commandIdleTimedOut": "命令因長時間沒有輸出而終止", + "commandCheckedUnknown": "已檢查命令,狀態未知", + "stopCommandError": "無法停止命令", + "sendCloseInputError": "無法傳送或關閉命令輸入", + "sendInputError": "無法傳送輸入", + "closeInputError": "無法關閉命令輸入", + "checkCommandError": "無法檢查命令", + "sentClosedInput": "已傳送並關閉命令輸入", + "sentCommandInput": "已傳送輸入", + "closedCommandInput": "已關閉命令輸入", "continuedCommand": "已繼續命令", "continueCommandFailed": "無法繼續命令", "checkingRunningCommands": "正在檢查執行中的命令", "checkedRunningCommands": "已檢查執行中的命令", "checkRunningCommandsFailed": "無法檢查執行中的命令", + "showEarlierCommandChecks": "展開先前的命令檢查({{count}})", + "hideEarlierCommandChecks": "收合先前的命令檢查({{count}})", "capturingScreenshot": "正在擷取螢幕截圖", "capturedScreenshot": "已擷取螢幕截圖", "captureScreenshotFailed": "無法擷取螢幕截圖", diff --git a/webui/src/tests/agent-activity-cluster.test.tsx b/webui/src/tests/agent-activity-cluster.test.tsx index e835abf7c..18dd7c8b2 100644 --- a/webui/src/tests/agent-activity-cluster.test.tsx +++ b/webui/src/tests/agent-activity-cluster.test.tsx @@ -2,6 +2,7 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react" import { afterEach, describe, expect, it, vi } from "vitest"; import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster"; +import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context"; import { preloadMarkdownText } from "@/components/MarkdownText"; import { setAppLanguage } from "@/i18n"; import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences"; @@ -106,6 +107,129 @@ function installReducedMotion() { describe("AgentActivityCluster", () => { afterEach(() => { localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); }); + it("keeps repeated session observations in call order and shows their original command", () => { + const id = "012345abcdef"; + const sessionLine = `exec_session(${JSON.stringify({ session_id: id })})`; + const readLine = 'read_file({"path":"README.md"})'; + const messages: UIMessage[] = [{ + id: "session-activity", role: "tool", kind: "trace", content: sessionLine, + traces: [sessionLine, readLine], createdAt: 1, + toolEvents: [ + { name: "exec_session", call_id: "poll-1", arguments: { session_id: id }, phase: "end", result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s` }, + { name: "read_file", call_id: "read-1", arguments: { path: "README.md" }, phase: "end" }, + { name: "exec_session", call_id: "poll-2", arguments: { session_id: id }, phase: "end", result: "Exit code: 7\nElapsed: 2.0s" }, + ], + }]; + const commands = new Map([[id, "npm test --token secret-value"]]); + const { container } = render( + + + , + ); + const rows = screen.getAllByTestId("activity-step").map((row) => row.textContent); + expect(rows).toEqual([ + "Command was still running at the last check npm test --token ••••", + "Read file README.md", + "Command failed (exit code 7) npm test --token ••••", + ]); + expect(container.innerHTML).not.toContain(id); + expect(container.innerHTML).not.toContain("secret-value"); + }); + + it("preserves the order of a structured session check followed by text-only activity", () => { + const id = "012345abcdef"; + const line = `exec_session(${JSON.stringify({ session_id: id })})`; + const legacy = 'read_file({"path":"later.txt"})'; + const message: UIMessage = { id: "mixed-activity", role: "tool", kind: "trace", content: legacy, + traces: [line, legacy], createdAt: 1, toolEvents: [{ name: "exec_session", call_id: "check", + arguments: { session_id: id }, phase: "end", result: "Exit code: 0\nElapsed: 2.0s" }] }; + render(); + expect(screen.getAllByTestId("activity-step").map((row) => row.textContent)).toEqual([ + "Command completed", "Reading file later.txt", + ]); + }); + + it("keeps text-only activity after every repeated structured check preceding it", () => { + const id = "012345abcdef"; + const line = `exec_session(${JSON.stringify({ session_id: id })})`; + const legacy = 'read_file({"path":"later.txt"})'; + const message: UIMessage = { id: "mixed-repeats", role: "tool", kind: "trace", content: legacy, + traces: [line, line, legacy], createdAt: 1, toolEvents: [ + { name: "exec_session", call_id: "check-1", arguments: { session_id: id }, phase: "end", + result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s` }, + { name: "exec_session", call_id: "check-2", arguments: { session_id: id }, phase: "end", result: "Exit code: 0\nElapsed: 2.0s" }, + ] }; + render(); + expect(screen.getAllByTestId("activity-step").map((row) => row.textContent)).toEqual([ + "Command was still running at the last check", "Command completed", "Reading file later.txt", + ]); + }); + + it("does not claim text-only session input succeeded without an observation", () => { + const line = 'exec_session({"session_id":"012345abcdef","input":"private-stdin"})'; + const message: UIMessage = { id: "legacy-session", role: "tool", kind: "trace", content: line, traces: [line], createdAt: 1 }; + const { container } = render(); + expect(container).toHaveTextContent("Command status unknown"); + expect(container).not.toHaveTextContent("Sent input"); + expect(container).not.toHaveTextContent("private-stdin"); + }); + + it("folds only long consecutive passive checks and lets users inspect every observation", () => { + const a = "012345abcdef"; + const b = "fedcba543210"; + const running = (id: string) => `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s`; + const view = (checks: number) => { + const events: NonNullable = [ + ...Array.from({ length: checks }, (_, index) => ({ name: "exec_session", call_id: `a-${index}`, + arguments: { session_id: a }, phase: "end" as const, result: running(a) })), + { name: "exec_session", call_id: "input", arguments: { session_id: a, input: "private" }, phase: "end", result: running(a) }, + ...Array.from({ length: 7 }, (_, index) => ({ name: "exec_session", call_id: `b-${index}`, + arguments: { session_id: b }, phase: "end" as const, result: running(b) })), + { name: "exec_session", call_id: "failed", arguments: { session_id: b }, phase: "error", error: "query failed" }, + { name: "exec_session", call_id: "finished", arguments: { session_id: a }, phase: "end", result: "Exit code: 0\nElapsed: 1.0s" }, + ]; + const message: UIMessage = { id: "many-checks", role: "tool", kind: "trace", content: "exec_session()", + traces: events.map((event) => `exec_session(${JSON.stringify(event.arguments)})`), toolEvents: events, createdAt: 1 }; + return + + ; + }; + const { rerender, container } = render(view(10)); + expect(screen.getAllByTestId("activity-step")).toHaveLength(5); + expect(container).toHaveTextContent("Sent input test-a"); + expect(container).toHaveTextContent("Could not check command test-b"); + expect(container).toHaveTextContent("Command completed test-a"); + expect(container).not.toHaveTextContent("private"); + fireEvent.click(screen.getByRole("button", { name: "Show earlier command checks (9)" })); + expect(screen.getAllByTestId("activity-step")).toHaveLength(14); + expect(screen.getByRole("button", { name: "Hide earlier command checks (9)" })).toHaveAttribute("aria-expanded", "true"); + rerender(view(11)); + expect(screen.getAllByTestId("activity-step")).toHaveLength(15); + fireEvent.click(screen.getByRole("button", { name: "Hide earlier command checks (10)" })); + expect(screen.getAllByTestId("activity-step")).toHaveLength(5); + expect(screen.getByRole("button", { name: "Show earlier command checks (6)" })).toBeInTheDocument(); + }); + + it("shows a generic session label until its source command becomes available", () => { + const id = "012345abcdef"; + const line = `exec_session(${JSON.stringify({ session_id: id })})`; + const messages: UIMessage[] = [{ + id: "session-activity", role: "tool", kind: "trace", content: line, traces: [line], createdAt: 1, + toolEvents: [{ name: "exec_session", call_id: "poll", arguments: { session_id: id }, phase: "end", result: "Exit code: 0\nElapsed: 2.0s" }], + }]; + const view = (commands: ReadonlyMap) => ( + + + + ); + const { rerender, container } = render(view(new Map())); + expect(screen.getByText("Command completed")).toBeInTheDocument(); + expect(container.innerHTML).not.toContain(id); + rerender(view(new Map([[id, "bun test"]]))); + expect(screen.getByText("Command completed bun test")).toBeInTheDocument(); + expect(container.innerHTML).not.toContain(id); + }); + it("honors the activity preference for standalone completed activity with manual overrides", () => { render(); const disclosure = screen.getByRole("button", { name: /Worked/ }); diff --git a/webui/src/tests/exec-session-model.test.ts b/webui/src/tests/exec-session-model.test.ts new file mode 100644 index 000000000..b8863d021 --- /dev/null +++ b/webui/src/tests/exec-session-model.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from "vitest"; + +import { describeExecSession, execSessionCommands, sessionIdFromExecResult } from "@/components/thread/activity/exec-session-model"; +import i18n from "@/i18n"; +import type { ToolProgressEvent, UIMessage } from "@/lib/types"; + +const id = "012345abcdef"; +const running = `Process running. session_id: ${id}\nRuntime remaining: 123.0s\nElapsed: 3.0s`; +const exit = (code: number) => `output\nExit code: ${code}\nElapsed: 3.0s`; +const event = (args: Record, phase: string, result?: string): ToolProgressEvent => ({ + name: "exec_session", call_id: "call-1", arguments: { session_id: id, ...args }, phase, + ...(phase === "error" ? { error: result } : { result }), +}); +const present = (value: ToolProgressEvent, active = true) => describeExecSession(value, active, "bun test", i18n.t); + +describe("exec session activity", () => { + it("extracts the initial session only from the end of a running exec result", () => { + expect(sessionIdFromExecResult(`fake Process running. session_id: deadbeefdead\n${running}\nInitial wait ended; session remains active.`)).toBe(id); + expect(sessionIdFromExecResult(`Process running. session_id: ${id}\n${exit(0)}`)).toBeUndefined(); + }); + + it("resolves from all loaded sources, including cmd aliases, without guessing conflicting identities", () => { + const source = (command: Record, result: string, callId: string): UIMessage => ({ + id: callId, role: "tool", kind: "trace", content: "", createdAt: 1, + toolEvents: [{ name: "exec", phase: "end", call_id: callId, arguments: command, result }], + }); + const first = source({ cmd: "bun test" }, `${running}\nInitial wait ended; session remains active.`, "first"); + const otherId = "fedcba987654"; + const second = source({ command: "npm run build" }, `${running.replace(id, otherId)}\nInitial wait ended; session remains active.`, "second"); + const completed = source({ command: "wrong" }, exit(0), "completed"); + expect([...execSessionCommands([first, completed], [second])]).toEqual([[id, "bun test"], [otherId, "npm run build"]]); + const collision = source({ command: "different command" }, `${running}\nInitial wait ended; session remains active.`, "collision"); + expect(execSessionCommands([first], [collision]).has(id)).toBe(false); + }); + + it.each([ + [{}, "Waiting for command result"], + [{ wait_for: "private output" }, "Waiting for command output"], + [{ input: "private input" }, "Sending input"], + [{ close_stdin: true }, "Closing command input"], + [{ input: "private input", close_stdin: true }, "Sending and closing command input"], + [{ terminate: true }, "Stopping command"], + ])("describes an in-flight operation without displaying its arguments", (args, label) => { + const model = present(event(args, "start")); + expect(model.label).toBe(label); + expect(model.active).toBe(true); + expect(JSON.stringify(model)).not.toMatch(/012345abcdef|private input|private output/); + }); + + it("does not claim an unreturned invocation completed when the turn is no longer active", () => { + expect(present(event({}, "start"), false)).toMatchObject({ label: "Command status unknown", active: false }); + }); + + it.each([ + [running, "Command was still running at the last check"], + [`${running}\nWait timed out after 1s; session remains active.`, "Wait timed out; command was still running at the last check"], + [exit(0), "Command completed"], + [exit(7), "Command failed (exit code 7)"], + [`Session terminated. Reason: cancelled.\nExit code: -15\nElapsed: 3.0s`, "Command exited (exit code -15)"], + ])("shows the observed command state rather than tool-return success", (result, label) => { + expect(present(event({}, "end", result))).toMatchObject({ label, active: false }); + }); + + it("reports a naturally completed process as completed even when terminate was requested", () => { + expect(present(event({ terminate: true }, "end", exit(0))).label).toBe("Command completed"); + }); + + it("keeps a wait target private and does not say it was observed when the process exits", () => { + const result = `${exit(0)}\nWait target not observed: 'private output'`; + const model = present(event({ wait_for: "private output" }, "end", result)); + expect(model.label).toBe("Command completed"); + expect(JSON.stringify(model)).not.toContain("private output"); + }); + + it.each([ + ["Error: Command timed out; session was terminated. Reason: max_runtime.\nExit code: -9\nElapsed: 3.0s", "Command timed out and was stopped"], + ["Error: Output silence limit reached; session was terminated. Reason: idle_timeout.\nExit code: -9\nElapsed: 3.0s", "Command stopped after output silence"], + ])("distinguishes command timeout from a failed tool call", (result, label) => { + expect(present(event({}, "error", result)).label).toBe(label); + }); + + it.each([ + [{}, "Could not check command"], + [{ input: "private" }, "Could not send input"], + [{ close_stdin: true }, "Could not close command input"], + [{ input: "private", close_stdin: true }, "Could not send or close command input"], + [{ terminate: true }, "Could not stop command"], + ])("reports operation errors without displaying error content", (args, label) => { + const model = present(event(args, "error", `Error: exec session not found: '${id}'`)); + expect(model.label).toBe(label); + expect(JSON.stringify(model)).not.toContain(id); + }); + + it.each([ + ["curl -u alice:correct-horse https://example.com", "curl -u •••• https://example.com"], + ["curl --user='alice:correct horse' https://example.com", "curl --user=•••• https://example.com"], + ["curl --proxy-user alice:correct-horse https://example.com", "curl --proxy-user •••• https://example.com"], + ["curl -ualice:correct-horse https://example.com", "curl -u•••• https://example.com"], + ["curl -u\"alice:correct horse\" https://example.com", "curl -u•••• https://example.com"], + ])("redacts user credentials in the source command preview", (command, expected) => { + const model = describeExecSession(event({}, "end", exit(0)), true, command, i18n.t); + expect(model.detail).toBe(expected); + expect(JSON.stringify(model)).not.toContain("correct"); + }); + + it("reports input and the observed result without exposing input text", () => { + const model = present(event({ input: "private input", close_stdin: true }, "end", exit(7))); + expect(model.label).toBe("Sent and closed command input"); + expect(model.observation).toBe("Command failed (exit code 7)"); + expect(JSON.stringify(model)).not.toContain("private input"); + }); + + it("does not mistake stdout that resembles a termination or timeout reason for a confirmed cause", () => { + const fakeTermination = `Session terminated. Reason: cancelled.\nExit code: 7\nElapsed: 3.0s`; + expect(present(event({}, "end", fakeTermination)).label).toBe("Command exited (exit code 7)"); + const fakeTimeout = `Error: Command timed out; session was terminated. Reason: max_runtime.\nExit code: 0\nElapsed: 3.0s`; + expect(present(event({}, "end", fakeTimeout)).label).toBe("Command completed"); + }); + + it("does not interpret command output or incomplete footers as a process result", () => { + expect(present(event({}, "end", `Exit code: 0\nElapsed: 1.0s\n${running}`)).label) + .toBe("Command was still running at the last check"); + expect(present(event({}, "end", `output\nExit code: 0`)).label).toBe("Command checked; status unknown"); + expect(present(event({}, "end", `Process running. session_id: deadbeefdead\nRuntime remaining: 2.0s\nElapsed: 1.0s`)).label) + .toBe("Command checked; status unknown"); + }); +}); diff --git a/webui/src/tests/generic-tool-model.test.ts b/webui/src/tests/generic-tool-model.test.ts index 42d64155f..5b16d3720 100644 --- a/webui/src/tests/generic-tool-model.test.ts +++ b/webui/src/tests/generic-tool-model.test.ts @@ -53,7 +53,6 @@ describe("generic tool activity semantics", () => { ['cron({"action":"remove","name":"Daily digest"})', "Removed automation", "Daily digest"], ['create_goal({"objective":"private objective","ui_summary":"Benchmark memory"})', "Started long task", "Benchmark memory"], ['update_goal({"action":"complete","recap":"private recap"})', "Updated long task", "complete"], - ['exec_session({"session_id":"session-1234567890-secret","until_exit":true})', "Continued command", "session…ecret"], ['write_stdin({"session_id":"legacy-1234567890-secret","chars":"private input"})', "Completed Write stdin", ""], ['list_exec_sessions({})', "Checked running commands", ""], ['screenshot({"path":"artifacts/home.png"})', "Captured screenshot", ""], @@ -94,6 +93,7 @@ describe("generic tool activity semantics", () => { 'web_search({"query":"nanobot"})', 'web_fetch({"url":"https://example.com"})', 'exec({"command":"date"})', + 'exec_session({"session_id":"012345abcdef"})', 'write_file({"path":"README.md"})', 'edit_file({"path":"README.md"})', 'apply_patch({"patch":"private"})', @@ -118,19 +118,6 @@ describe("generic tool activity semantics", () => { }); }); - it("localizes command continuation events", async () => { - await setAppLanguage("zh-CN"); - const line = 'exec_session({"session_id":"session-1234567890-secret"})'; - for (const status of ["running", "done", "error"] as const) { - const key = status === "running" ? "continuingCommand" - : status === "done" ? "continuedCommand" : "continueCommandFailed"; - expect(describeRun(line, status)).toMatchObject({ - label: i18n.t(`message.agentActivity.${key}`), - detail: "session…ecret", - }); - } - }); - it("keeps different subtask actions separate while grouping repeated status checks", () => { const item = (action: string) => ({ trace: parseGenericToolTrace(`subagent("${action}")`)!, status: "done" as const }); expect(canGroupGenericToolRuns(item("create"), item("check"))).toBe(false); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 582c8e3ef..e0fb39ef9 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -818,6 +818,34 @@ describe("ThreadShell", () => { await act(async () => {}); }); + it("resolves a session command from loaded history outside the visible window", async () => { + const client = makeClient(); + const id = "012345abcdef"; + const command = { cmd: "bun run test --token secret-value" }; + const sessionArgs = { session_id: id, until_exit: true }; + const events = [ + { event: "message", chat_id: "command-history", projection_id: "initial-exec", kind: "progress", + text: `exec(${JSON.stringify(command)})`, tool_events: [{ name: "exec", phase: "end", call_id: "exec-1", arguments: command, + result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s\nInitial wait ended; session remains active.` }] }, + ...Array.from({ length: 150 }, (_, index) => ({ event: "user_message", chat_id: "command-history", + projection_id: `old-${index}`, text: `older question ${index}`, starts_turn: true })), + { event: "message", chat_id: "command-history", projection_id: "session-call", kind: "progress", + text: `exec_session(${JSON.stringify(sessionArgs)})`, tool_events: [{ name: "exec_session", phase: "end", + call_id: "poll-1", arguments: sessionArgs, result: "Exit code: 0\nElapsed: 2.0s" }] }, + { event: "message", chat_id: "command-history", projection_id: "final-answer", text: "Command answer" }, + ]; + vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => String(input).includes("/webui-thread") + ? Promise.resolve(httpJson({ schemaVersion: 3, projection: "events", events })) + : Promise.resolve({ ok: false, status: 404, json: async () => ({}) }))); + render(wrap(client, {}} />)); + const menu = await openMessageActions("Command answer"); + fireEvent.click(within(menu).getByRole("button", { name: /Worked/ })); + await waitFor(() => expect(document.body).toHaveTextContent("Command completed bun run test --token ••••")); + expect(document.body).not.toHaveTextContent(id); + expect(document.body).not.toHaveTextContent("secret-value"); + expect(screen.queryByText("older question 0")).not.toBeInTheDocument(); + }); + it("surfaces and retries a deferred trace-detail request failure", async () => { const client = makeClient(); let detailCalls = 0; @@ -893,27 +921,40 @@ describe("ThreadShell", () => { expect(detailCalls).toBe(2); }); - it("hydrates deferred activity in an independently paged navigation window", async () => { + it.each([false, true])("hydrates deferred activity in an independently paged navigation window (fragment=%s)", async (fragment) => { const client = makeClient(); + const id = "012345abcdef"; + let detailCalls = 0; vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => { const url = String(input); if (url.includes("/prompts")) return Promise.resolve(httpJson({ prompts: [{ id: "old-user", preview: "Old question", answerPreview: "old answer", createdAt: 1, cursor: "0", turnId: "old-turn", }] })); - if (url.includes("/trace-detail?")) return Promise.resolve(httpJson({ - message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{ - event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress", - text: 'exec({"command":"echo historical"})', - }], - })); + if (url.includes("/trace-detail?")) { + detailCalls += 1; + return Promise.resolve(httpJson({ + message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{ + event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress", + text: 'exec({"command":"echo historical"})', + tool_events: [{ name: "exec", phase: "end", call_id: "navigation-exec", + arguments: { command: "echo historical" }, + result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s\nInitial wait ended; session remains active.` }], + }], + })); + } if (url.includes("after=0")) return Promise.resolve(httpJson({ schemaVersion: 3, projection: "events", events: [ { event: "user_message", chat_id: "trace-navigation", projection_id: "old-user", text: "Old question", starts_turn: true }, { event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress", text: "exec(…)", trace_detail: { ref: "1.history-aaaaaaaaaaaaaaaaaaaa", bytes: 40_000, traceCount: 1 } }, + { event: "message", chat_id: "trace-navigation", projection_id: "old-check", kind: "progress", + text: `exec_session({"session_id":"${id}"})`, + tool_events: [{ name: "exec_session", phase: "end", call_id: "navigation-check", + arguments: { session_id: id }, result: "Exit code: 0\nElapsed: 2.0s" }] }, { event: "message", chat_id: "trace-navigation", projection_id: "old-answer", text: "old answer" }, - ], page: { user_message_offset: 0, has_more_before: false, has_more_after: true, after_cursor: "1" }, + ], page: { user_message_offset: 0, has_more_before: false, has_more_after: true, after_cursor: "1", + ...(fragment ? { history_generation: "generation-a", record_range: { turn: 0, start: 0, end: 4 } } : {}) }, })); if (url.includes("/webui-thread")) return Promise.resolve(httpJson({ schemaVersion: 3, messages: [{ id: "latest-answer", role: "assistant", content: "latest answer", createdAt: 100 }], @@ -928,12 +969,51 @@ describe("ThreadShell", () => { await screen.findByText("old answer"); const menu = await openMessageActions("old answer"); fireEvent.click(within(menu).getByRole("button", { name: /Worked/ })); - await waitFor(() => expect(document.body).toHaveTextContent("echo historical")); + await waitFor(() => expect(document.body).toHaveTextContent("Command completed echo historical")); + expect(detailCalls).toBe(1); + expect(document.body).not.toHaveTextContent(id); fireEvent.click(screen.getByRole("button", { name: "Scroll to bottom" })); await screen.findByText("latest answer"); expect(screen.queryByText("old answer")).not.toBeInTheDocument(); }); + it("starts a fresh trace-detail read after leaving and returning to the same chat", async () => { + const client = makeClient(); + let resolveOld!: (response: Response) => void; + const oldRequest = new Promise((resolve) => { resolveOld = resolve; }); + let detailCalls = 0; + vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/webui-thread/trace-detail?")) { + detailCalls += 1; + if (detailCalls === 1) return oldRequest; + return Promise.resolve(httpJson({ message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{ + event: "message", chat_id: "detail-return-a", projection_id: "trace-shared", kind: "progress", + text: 'exec({"command":"echo fresh"})', + }] })); + } + if (url.includes("websocket%3Adetail-return-a/webui-thread")) return Promise.resolve(httpJson(traceDetailThread(true, "answer-a"))); + if (url.includes("websocket%3Adetail-return-b/webui-thread")) return Promise.resolve(httpJson(traceDetailThread(false, "answer-b"))); + return Promise.resolve({ ok: false, status: 404, json: async () => ({}) }); + })); + const view = (chatId: string) => wrap(client, + {}} />); + const { rerender } = render(view("detail-return-a")); + fireEvent.click(within(await openMessageActions("answer-a")).getByRole("button", { name: /Worked/ })); + await waitFor(() => expect(detailCalls).toBe(1)); + rerender(view("detail-return-b")); + await screen.findByText("answer-b"); + rerender(view("detail-return-a")); + fireEvent.click(within(await openMessageActions("answer-a")).getByRole("button", { name: /Worked/ })); + await waitFor(() => expect(detailCalls).toBe(2)); + await waitFor(() => expect(document.body).toHaveTextContent("echo fresh")); + await act(async () => resolveOld(httpJson({ message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{ + event: "message", chat_id: "detail-return-a", projection_id: "trace-shared", kind: "progress", + text: 'exec({"command":"echo stale"})', + }] }))); + expect(document.body).not.toHaveTextContent("echo stale"); + }); + it("ignores a deferred trace-detail failure after switching sessions", async () => { const client = makeClient(); const detailUrls: string[] = []; diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsx index 3515a0319..3b1854e70 100644 --- a/webui/src/tests/thread-viewport.test.tsx +++ b/webui/src/tests/thread-viewport.test.tsx @@ -2257,7 +2257,7 @@ describe("ThreadViewport", () => { const navigation = { prompts: [{ id: "u1", label: "hello", preview: "hello", answerPreview: "", createdAt: 1, index: 0 }], window: { messages: [{ id: "old", role: "user" as const, content: "old question", createdAt: 0 }], userMessageOffset: 0, hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null }, - target: null, operation: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() }; + target: null, operation: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), expandTraceDetail: vi.fn() }; const view = render(} navigation={navigation} />); act(() => viewportRef.current?.jumpToUserPrompt("u1")); expect(latest).toHaveBeenCalledOnce(); @@ -2272,7 +2272,7 @@ describe("ThreadViewport", () => { prompts: [], window: { messages: history, userMessageOffset: 0, hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null }, target: null, operation: null, loading: false, error: null, - jump: vi.fn(), older: vi.fn(), newer, cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn(), + jump: vi.fn(), older: vi.fn(), newer, cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), expandTraceDetail: vi.fn(), }; const view = render(} navigation={navigation} />); await flushAnimationFrame(); @@ -2324,7 +2324,7 @@ describe("ThreadViewport", () => { navigation={{ prompts: [], window: { messages: history, userMessageOffset: 0, hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null }, target: { id: "old-user", sequence: 1 }, operation: null, loading: false, error: null, - jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn() }} />); + jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), expandTraceDetail: vi.fn() }} />); await waitFor(() => expect(screen.getByText("Large old turn")).toBeInTheDocument()); }); diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 935a9104c..7a7b7f792 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest"; import { useNanobotStream } from "@/hooks/useNanobotStream"; import { userPromptAnchors } from "@/components/thread/promptNavigation"; +import { execSessionCommands } from "@/components/thread/activity/exec-session-model"; import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility"; import { normalizeActivityTimeline } from "@/lib/activity-timeline"; import { composerUsageSnapshots } from "@/lib/model-request"; @@ -159,6 +160,37 @@ async function flushStreamFrame() { } describe("useNanobotStream", () => { + it("updates the command source on exec results, not on streamed text, and scopes it to the chat", async () => { + const fake = fakeClient(); + const initial: UIMessage[] = Array.from({ length: 500 }, (_, index) => ({ + id: `history-${index}`, role: "user", content: `Earlier ${index}`, createdAt: index, + })); + const { result, rerender } = renderHook(({ chat }: { chat: string }) => useNanobotStream(chat, initial), { + wrapper: wrap(fake.client), initialProps: { chat: "chat-a" }, + }); + const id = "012345abcdef"; + const args = { command: "bun run test" }; + act(() => { + fake.emit("chat-a", { event: "message", chat_id: "chat-a", turn_id: "turn", turn_seq: 1, kind: "tool_hint", + text: `exec(${JSON.stringify(args)})`, tool_events: [{ name: "exec", call_id: "exec-1", phase: "start", arguments: args }] }); + fake.emit("chat-a", { event: "message", chat_id: "chat-a", turn_id: "turn", turn_seq: 2, kind: "tool_hint", + text: `exec(${JSON.stringify(args)})`, tool_events: [{ name: "exec", call_id: "exec-1", phase: "end", arguments: args, + result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s\nInitial wait ended; session remains active.` }] }); + }); + const snapshot = result.current.execSourceMessages; + expect(execSessionCommands(snapshot).get(id)).toBe("bun run test"); + act(() => { + for (let index = 0; index < 100; index++) fake.emit("chat-a", { + event: "delta", chat_id: "chat-a", turn_id: "turn", turn_seq: index + 3, stream_id: "answer", text: "x", + }); + }); + await flushStreamFrame(); + expect(result.current.messages.at(-1)?.content).toBe("x".repeat(100)); + expect(result.current.execSourceMessages).toBe(snapshot); + rerender({ chat: "chat-b" }); + expect(execSessionCommands(result.current.execSourceMessages).has(id)).toBe(false); + }); + it.each([true, false])("keeps temporary and new persistent streams separate when the history key is absent (temporary=%s)", (temporary) => { const fake = fakeClient(); const cache = new ThreadMessageCache(() => temporary);