From b49218b6a3f7c809c2c7f7e63e6fef32e9f7c36c Mon Sep 17 00:00:00 2001 From: chengyongru Date: Thu, 12 Nov 2026 17:13:52 +0800 Subject: [PATCH] fix(webui): avoid phantom reasoning on empty streams --- webui/browser/answer-order-fixture.tsx | 3 +- webui/browser/answer-order.spec.ts | 102 +++++++++++++++++- .../src/components/thread/ThreadMessages.tsx | 42 +++++--- .../src/components/thread/ThreadViewport.tsx | 6 +- webui/src/lib/activity-timeline.ts | 53 ++++++--- .../src/tests/thread-event-projection.test.ts | 29 ++++- webui/src/tests/thread-messages.test.tsx | 95 +++++++++++++--- webui/src/tests/thread-viewport.test.tsx | 19 ++++ 8 files changed, 299 insertions(+), 50 deletions(-) diff --git a/webui/browser/answer-order-fixture.tsx b/webui/browser/answer-order-fixture.tsx index b0d1085dd..8da973ad3 100644 --- a/webui/browser/answer-order-fixture.tsx +++ b/webui/browser/answer-order-fixture.tsx @@ -8,7 +8,8 @@ import { ClientProvider } from "@/providers/ClientProvider"; export function AnswerOrderFixture() { const [client] = useState(() => new NanobotClient({ - url: `ws://${location.host}/answer-order-socket`, reconnect: false, + url: `ws://${location.host}/answer-order-socket`, + reconnect: new URLSearchParams(location.search).get("reconnect") === "1", })); const [cache] = useState(() => new ThreadMessageCache(() => false)); const [chatId, setChatId] = useState("answer-order"); diff --git a/webui/browser/answer-order.spec.ts b/webui/browser/answer-order.spec.ts index 674209d1d..66c387ebb 100644 --- a/webui/browser/answer-order.spec.ts +++ b/webui/browser/answer-order.spec.ts @@ -6,7 +6,7 @@ const turnId = "answer-order-turn"; const source = { provider: "fixture", model: "fixture", preset: "fixture" }; const base = { chat_id: chatId, turn_id: turnId }; -async function openThread(page: Page, events: ThreadProjectionEvent[] = [], locale = "en") { +async function openThread(page: Page, events: ThreadProjectionEvent[] = [], locale = "en", reconnect = false) { const errors: string[] = []; page.on("pageerror", (error) => errors.push(error.message)); await page.addInitScript((language) => { localStorage.setItem("nanobot.locale", language); }, locale); @@ -21,6 +21,7 @@ async function openThread(page: Page, events: ThreadProjectionEvent[] = [], loca } }); }); let socket!: WebSocketRoute; + let attachmentCount = 0; const attached = new Set(); await page.routeWebSocket("**/answer-order-socket", (route) => { socket = route; @@ -28,14 +29,23 @@ async function openThread(page: Page, events: ThreadProjectionEvent[] = [], loca const frame = JSON.parse(String(raw)); if (frame.type === "attach") { attached.add(frame.chat_id); + if (frame.chat_id === chatId) attachmentCount += 1; route.send(JSON.stringify({ event: "attached", chat_id: frame.chat_id })); } }); }); - await page.goto("/browser/fixture.html?case=answer-order"); + await page.goto(`/browser/fixture.html?case=answer-order${reconnect ? "&reconnect=1" : ""}`); await expect.poll(() => attached.has(chatId)).toBe(true); await expect(page.getByRole("status", { name: "Loading conversation…" })).toHaveCount(0); - return { emit: (...frames: InboundEvent[]) => frames.forEach((frame) => socket.send(JSON.stringify(frame))), errors }; + return { + emit: (...frames: InboundEvent[]) => frames.forEach((frame) => socket.send(JSON.stringify(frame))), + dropAndReconnect: async () => { + const previous = attachmentCount; + await socket.close({ code: 1011, reason: "fixture disconnect" }); + await expect.poll(() => attachmentCount).toBeGreaterThan(previous); + }, + errors, + }; } async function expectAnswerOrder(page: Page) { @@ -115,6 +125,92 @@ test.describe("answer order", () => { }); } + test("shows only real reasoning through restored history, live tools, and reconnect", async ({ page }) => { + const history: ThreadProjectionEvent[] = [ + { event: "user_message", ...base, turn_seq: 1, text: "检查工具", starts_turn: true }, + { event: "stream_end", ...base, stream_id: "empty", turn_seq: 2, text: "", resuming: true }, + ]; + const { emit, dropAndReconnect, errors } = await openThread(page, history, "zh-CN", true); + await expect(page.getByText("检查工具", { exact: true })).toHaveCount(1); + emit( + { event: "goal_status", ...base, status: "running", started_at: 100 }, + { event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "web_search({\"query\":\"alpha\"})" }, + { event: "stream_end", ...base, stream_id: "live-empty", turn_seq: 4, resuming: true }, + { event: "message", ...base, turn_seq: 5, kind: "tool_hint", text: "read_file({\"path\":\"beta\"})" }, + ); + await expect(page.getByTestId("agent-activity-content")).toContainText("网页"); + await expect(page.getByText("思考过程", { exact: true })).toHaveCount(0); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + await page.getByRole("button", { name: "Switch topic" }).click(); + await expect(page.getByText("检查工具", { exact: true })).toHaveCount(0); + await page.getByRole("button", { name: "Switch topic" }).click(); + await expect(page.getByTestId("agent-activity-content")).toContainText("网页"); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + await dropAndReconnect(); + await expect(page.getByTestId("agent-activity-content")).toContainText("网页"); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + + emit( + { event: "delta", ...base, stream_id: "empty", turn_seq: 6, text: "过期内容" }, + { event: "reasoning_delta", ...base, stream_id: "thought", turn_seq: 7, text: "真正的推理" }, + { event: "reasoning_end", ...base, stream_id: "thought", turn_seq: 8, text: "真正的推理" }, + { event: "delta", ...base, stream_id: "answer", turn_seq: 9, text: "最终答案" }, + ); + await expect(page.getByText("最终答案", { exact: true })).toHaveCount(1); + await expect(page.getByText("真正的推理", { exact: true })).toHaveCount(1); + const activity = await page.getByTestId("agent-activity-content").textContent(); + expect(activity).toContain("网页"); + expect(activity).toContain("真正的推理"); + expect(activity!.indexOf("网页")).toBeLessThan(activity!.indexOf("真正的推理")); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(1); + await expect(page.getByText("过期内容", { exact: true })).toHaveCount(0); + expect(errors).toEqual([]); + }); + + test("keeps an assistant-only run visible after an older completed activity", async ({ page }) => { + const previous = { chat_id: chatId, turn_id: "previous-turn" }; + const history: ThreadProjectionEvent[] = [ + { event: "message", ...previous, turn_seq: 1, kind: "tool_hint", text: "read_file(previous)" }, + { event: "message", ...previous, turn_seq: 2, text: "Previous automation answer" }, + { event: "turn_end", ...previous, turn_seq: 3 }, + { event: "stream_end", ...base, stream_id: "empty", turn_seq: 1, text: "", resuming: true }, + ]; + const { emit, errors } = await openThread(page, history); + await expect(page.getByText("Previous automation answer", { exact: true })).toHaveCount(1); + emit({ event: "goal_status", ...base, status: "running", started_at: Date.now() / 1000 }); + await expect(page.getByRole("status", { name: /^Working for / })).toBeVisible(); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + emit({ event: "message", ...base, turn_seq: 2, kind: "tool_hint", text: "web_search({\"query\":\"alpha\"})" }); + await expect(page.getByTestId("agent-activity-content")).toContainText("web"); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + expect(errors).toEqual([]); + }); + + test("replays an empty tool-only answer without a reasoning row", async ({ page }) => { + const events: ThreadProjectionEvent[] = [ + { event: "user_message", ...base, turn_seq: 1, text: "恢复工具", starts_turn: true }, + { event: "stream_end", ...base, stream_id: "empty", turn_seq: 2, text: "", resuming: true }, + { event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "web_search({\"query\":\"beta\"})" }, + ]; + const { emit, errors } = await openThread(page, events, "zh-CN"); + await page.getByRole("button", { name: "已处理" }).click(); + await expect(page.getByTestId("agent-activity-content")).toContainText("网页"); + await expect(page.getByText("思考过程", { exact: true })).toHaveCount(0); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + await page.getByRole("button", { name: "Rebuild subscription" }).click(); + await expect(page.getByTestId("agent-activity-content")).toContainText("网页"); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + emit( + { event: "goal_status", ...base, status: "running", started_at: 100 }, + { event: "delta", ...base, stream_id: "empty", turn_seq: 4, text: "过期内容" }, + { event: "delta", ...base, stream_id: "answer", turn_seq: 5, text: "恢复后的答案" }, + ); + await expect(page.getByText("恢复后的答案", { exact: true })).toHaveCount(1); + await expect(page.getByText("过期内容", { exact: true })).toHaveCount(0); + await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0); + expect(errors).toEqual([]); + }); + test("keeps hosted-tool answer segments after a cached return", async ({ page }) => { const { emit, errors } = await openThread(page); emit( diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsx index 562460e10..49d90c61a 100644 --- a/webui/src/components/thread/ThreadMessages.tsx +++ b/webui/src/components/thread/ThreadMessages.tsx @@ -15,7 +15,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/comp import { useMediaQuery } from "@/hooks/useMediaQuery"; import { useLocalPreferences } from "@/hooks/useLocalPreferences"; import { fmtDateTime, formatMessageHoverTime } from "@/lib/format-time"; -import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline"; +import { leadingDisplayNoopCount, projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline"; import { withoutSubagentCreateActivity } from "@/lib/subagent-create-activity"; import { cn } from "@/lib/utils"; import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types"; @@ -114,10 +114,11 @@ export function ThreadMessages({ const visible = withoutSubagentCreateActivity(message); return visible ? [visible] : []; }) } : unit), [rawUnits]); - const forkBoundaryAfterUnitIndex = useMemo( - () => unitIndexAfterMessageCount(units, forkBoundaryMessageCount), - [forkBoundaryMessageCount, units], - ); + const forkBoundaryAfterUnitIndex = useMemo(() => { + if (forkBoundaryMessageCount != null && forkBoundaryMessageCount > 0 + && forkBoundaryMessageCount <= leadingDisplayNoopCount(messages)) return -1; + return unitIndexAfterMessageCount(units, forkBoundaryMessageCount); + }, [forkBoundaryMessageCount, messages, units]); const forkFlags = useMemo(() => assistantForkFlags(units), [units]); const liveActivityClusterIndices = useMemo( () => isStreaming @@ -251,6 +252,9 @@ export function ThreadMessages({ const prelude = index === preludeIndex ? renderPrelude(prefix, marginTop) : null; return [ prelude, + index === 0 && forkBoundaryAfterUnitIndex === -1 + ? + : null, { if (message.role === "user") return false; - if (activeTurnId && message.turnId && message.turnId !== activeTurnId) return false; - return ( - message.content.trim().length > 0 - || !!message.reasoning?.trim() - || !!message.reasoningStreaming - || message.kind === "trace" - || !!message.media?.length + // Assistant-only runs have no prompt boundary; only their own turn's rows count. + if (activeTurnId && (message.turnId ? message.turnId !== activeTurnId : promptIndex < 0)) return false; + const visible = withoutSubagentCreateActivity(message); + return visible !== null && ( + visible.content.trim().length > 0 + || !!visible.reasoning?.trim() + || !!visible.reasoningStreaming + || visible.kind === "trace" + || !!visible.media?.length ); }); return { - ...(typeof prompt.createdAt === "number" && Number.isFinite(prompt.createdAt) + ...(typeof prompt?.createdAt === "number" && Number.isFinite(prompt.createdAt) ? { startedAtMs: prompt.createdAt } : {}), hasVisibleOutput, @@ -380,6 +387,7 @@ interface ThreadDisplayUnitProps { contextBlockMenuOpen: boolean; deferOffscreenRender: boolean; isTurnStreaming: boolean; + runStartedAtMs?: number; retryStatus: RetryStatus | null; forkIndex?: number; showForkBoundary: boolean; @@ -582,6 +590,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({ contextBlockMenuOpen, deferOffscreenRender, isTurnStreaming, + runStartedAtMs, retryStatus, forkIndex, showForkBoundary, @@ -723,7 +732,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({ retryStatus={retryStatus} hasBodyBelow={hasBodyBelow} turnLatencyMs={unit.turnLatencyMs} - startedAtMs={unit.startedAtMs} + startedAtMs={unit.startedAtMs ?? (isTurnStreaming ? runStartedAtMs : undefined)} cliApps={cliApps} mcpPresets={mcpPresets} traceDetailScope={traceDetailScope} @@ -802,6 +811,7 @@ function threadDisplayUnitPropsEqual( && previous.contextBlockMenuOpen === next.contextBlockMenuOpen && previous.deferOffscreenRender === next.deferOffscreenRender && previous.isTurnStreaming === next.isTurnStreaming + && previous.runStartedAtMs === next.runStartedAtMs && previous.retryStatus === next.retryStatus && previous.forkIndex === next.forkIndex && previous.showForkBoundary === next.showForkBoundary @@ -922,6 +932,8 @@ function currentActivityClusterIndices( let markedCurrentActivity = false; for (let i = units.length - 1; i >= 0; i -= 1) { const unit = units[i]; + const turnId = displayUnitTurnId(unit); + if (activeTurnId && turnId && turnId !== activeTurnId) break; if (unit.type === "activity") { if (!unit.messages.length) continue; if (!markedCurrentActivity) { diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx index 88f990f32..38a56446e 100644 --- a/webui/src/components/thread/ThreadViewport.tsx +++ b/webui/src/components/thread/ThreadViewport.tsx @@ -17,7 +17,7 @@ import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults" import { DiagramScope } from "@/components/markdown-diagrams/context"; import { DiffViewportContext } from "./activity/DiffViewportContext"; import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus"; -import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster"; +import { isActivityWindowMember } from "@/lib/activity-timeline"; import { ThreadCameraController } from "@/components/thread/thread-camera"; import { HISTORY_HOLD_PX, ThreadHistorySpring, type HistoryRevealPhase } from "@/components/thread/thread-history-spring"; import { @@ -160,8 +160,8 @@ export function windowMessages(messages: UIMessage[], visibleCount: number): UIM let start = Math.max(0, messages.length - visibleCount); while ( start > 0 - && isAgentActivityMember(messages[start]) - && isAgentActivityMember(messages[start - 1]) + && isActivityWindowMember(messages[start]) + && isActivityWindowMember(messages[start - 1]) ) { start -= 1; } diff --git a/webui/src/lib/activity-timeline.ts b/webui/src/lib/activity-timeline.ts index 5e1b9eaaf..d820a27d6 100644 --- a/webui/src/lib/activity-timeline.ts +++ b/webui/src/lib/activity-timeline.ts @@ -26,16 +26,33 @@ export function isReasoningOnlyAssistant(message: UIMessage): boolean { || !!message.media?.length || !!message.images?.length ) return false; - return !!(message.reasoning?.length || message.reasoningStreaming || message.isStreaming); + return !!(message.reasoning?.trim() || message.reasoningStreaming); } export function isAgentActivityMember(message: UIMessage): boolean { return isReasoningOnlyAssistant(message) || message.kind === "trace" || message.activityKind === "model"; } +/** Empty transport rows do not split an activity run at the history window boundary. */ +export function isActivityWindowMember(message: UIMessage): boolean { + return isAgentActivityMember(message) || isDisplayNoop(message); +} + +/** Count transport rows before the first displayable row in a history window. */ +export function leadingDisplayNoopCount(messages: UIMessage[]): number { + const first = messages.findIndex((message) => !isDisplayNoop(message)); + return first < 0 ? messages.length : first; +} + +function isPendingActivityMember(message: UIMessage): boolean { + // An empty streamed answer can still indicate an unfinished turn on replay, + // without representing a reasoning step in the visible timeline. + return isAgentActivityMember(message) || (!!message.isStreaming && isDisplayNoop(message)); +} + export function hasPendingAgentActivity(messages: UIMessage[]): boolean { const last = messages.at(-1); - if (!last || !isAgentActivityMember(last)) return false; + if (!last || !isPendingActivityMember(last)) return false; if (last.isStreaming || last.reasoningStreaming) return true; const lastTurnId = last.turnId; @@ -44,7 +61,7 @@ export function hasPendingAgentActivity(messages: UIMessage[]): boolean { // final assistant answer exists after it, the activity is simply history. return !previous || previous.role !== "assistant" - || isAgentActivityMember(previous) + || isPendingActivityMember(previous) || previous.turnId !== lastTurnId; } @@ -54,8 +71,8 @@ export function hasPendingAgentActivity(messages: UIMessage[]): boolean { * when every row provides one, and stable arrival order otherwise. Only contiguous rows of the same * display class are combined: activity rows share a collapsible surface, and * adjacent answer slices share an answer bubble. A visible answer is always a - * hard boundary between activity surfaces; completed empty transport frames - * have no display semantics and therefore create no boundary. + * hard boundary between activity surfaces; empty transport frames have no + * display semantics and therefore create no boundary, even during streaming. */ export function normalizeActivityTimeline( messages: UIMessage[], @@ -64,6 +81,7 @@ export function normalizeActivityTimeline( let turnMessages: UIMessage[] = []; let activeTurnId: string | undefined; let activeTurnStartedAtMs: number | undefined; + let leadingNoopSourceMessageCount = 0; const flushTurn = () => { if (!turnMessages.length) { @@ -77,10 +95,12 @@ export function normalizeActivityTimeline( activeTurnStartedAtMs, ); if (projected.length) { + projected[0].sourceMessageCount += leadingNoopSourceMessageCount; + leadingNoopSourceMessageCount = 0; units.push(...projected); } else if (units.length) { - // A turn containing only completed transport placeholders has no - // display surface. Keep its source count on the preceding prompt so + // A turn containing only transport placeholders has no display surface. + // Keep its source count on the preceding prompt so // persisted fork-boundary offsets still map to a visible unit. const lastIndex = units.length - 1; const last = units[lastIndex]; @@ -88,6 +108,8 @@ export function normalizeActivityTimeline( ...last, sourceMessageCount: last.sourceMessageCount + turnMessages.length, }; + } else { + leadingNoopSourceMessageCount += turnMessages.length; } turnMessages = []; @@ -98,7 +120,8 @@ export function normalizeActivityTimeline( for (const message of messages) { if (message.role === "user") { flushTurn(); - units.push({ type: "message", message, sourceMessageCount: 1 }); + units.push({ type: "message", message, sourceMessageCount: 1 + leadingNoopSourceMessageCount }); + leadingNoopSourceMessageCount = 0; activeTurnId = message.turnId; activeTurnStartedAtMs = validCreatedAtMs(message.createdAt); continue; @@ -169,6 +192,9 @@ function projectOrderedTurn( activitySourceMessageCount += 1; } else if (answers.length) { answerSourceMessageCount += 1; + } else if (units.length) { + const lastIndex = units.length - 1; + units[lastIndex] = { ...units[lastIndex], sourceMessageCount: units[lastIndex].sourceMessageCount + 1 }; } else { leadingNoopSourceMessageCount += 1; } @@ -185,7 +211,7 @@ function projectOrderedTurn( }); continue; } - if (isCompletedDisplayNoop(message)) { + if (isDisplayNoop(message)) { absorbDisplayNoop(); continue; } @@ -233,14 +259,15 @@ function isRawActivity(message: UIMessage): boolean { return isAgentActivityMember(message); } -/** A completed transport placeholder carries ordering/accounting metadata but - * no user-visible semantics, so it cannot define a display boundary. */ -function isCompletedDisplayNoop(message: UIMessage): boolean { +/** A transport placeholder carries ordering/accounting metadata but no + * user-visible semantics, so it cannot define a display boundary. */ +function isDisplayNoop(message: UIMessage): boolean { return ( message.role === "assistant" && message.kind !== "trace" + && message.kind !== "compaction" + && message.renderAs !== "text" && message.activityKind !== "model" - && !message.isStreaming && !message.reasoningStreaming && message.content.trim().length === 0 && !message.reasoning?.trim() diff --git a/webui/src/tests/thread-event-projection.test.ts b/webui/src/tests/thread-event-projection.test.ts index 154ed70d0..9ac75d4bb 100644 --- a/webui/src/tests/thread-event-projection.test.ts +++ b/webui/src/tests/thread-event-projection.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { createThreadProjectionState, projectThreadEvent, projectThreadEvents } from "@/lib/thread-event-projection"; -import { normalizeActivityTimeline } from "@/lib/activity-timeline"; +import { hasPendingAgentActivity, isReasoningOnlyAssistant, normalizeActivityTimeline } from "@/lib/activity-timeline"; import { ThreadProjectionIndex } from "@/lib/thread-projection-index"; import type { ThreadProjectionEvent, UIMessage } from "@/lib/types"; import projectionFixture from "./fixtures/live-replay-event-projection.json"; @@ -99,6 +99,33 @@ describe("canonical thread event projection", () => { expect(state.messages[2]).toMatchObject({ projectionStartSeq: 4, turnSeq: 6, streamId: "second" }); }); + it("keeps empty answer stream state without presenting it as reasoning", () => { + let state = createThreadProjectionState(); + const emit = (event: ThreadProjectionEvent, persisted = false) => { + state = projectThreadEvent(state, event, { createId: () => `live-${state.messages.length}`, now: 100, persisted }); + }; + emit({ event: "user_message", chat_id: "chat", turn_id: "turn", turn_seq: 1, text: "Question", starts_turn: true }, true); + // Persisted stream snapshots contain text: "" even when the live frame does not. + emit({ event: "stream_end", chat_id: "chat", turn_id: "turn", turn_seq: 2, stream_id: "empty", text: "", resuming: true }, true); + const placeholder = state.messages[1]; + expect(placeholder).toMatchObject({ content: "", isStreaming: true, streamId: "empty" }); + expect(hasPendingAgentActivity(state.messages)).toBe(true); + expect(isReasoningOnlyAssistant(placeholder)).toBe(false); + expect(normalizeActivityTimeline(state.messages)).toMatchObject([ + { type: "message", message: { content: "Question" }, sourceMessageCount: 2 }, + ]); + + emit({ event: "delta", chat_id: "chat", turn_id: "turn", turn_seq: 3, stream_id: "empty", text: "Stale" }); + emit({ event: "message", chat_id: "chat", turn_id: "turn", turn_seq: 4, kind: "tool_hint", text: "read_file(first)" }); + expect(hasPendingAgentActivity(state.messages)).toBe(true); + emit({ event: "reasoning_delta", chat_id: "chat", turn_id: "turn", turn_seq: 5, stream_id: "thought", text: "Real thought" }); + emit({ event: "reasoning_end", chat_id: "chat", turn_id: "turn", turn_seq: 6, stream_id: "thought", text: "Real thought" }); + emit({ event: "delta", chat_id: "chat", turn_id: "turn", turn_seq: 7, stream_id: "answer", text: "Answer" }); + const units = normalizeActivityTimeline(state.messages); + expect(units.map((unit) => unit.type === "message" ? unit.message.content : unit.messages.map((row) => row.reasoning || row.content))) + .toEqual(["Question", ["read_file(first)", "Real thought"], "Answer"]); + }); + it("can resume an earlier checkpoint after another branch closes the same stream", () => { const index = new ThreadProjectionIndex(); const options = { createId: () => "answer", now: 100, index }; diff --git a/webui/src/tests/thread-messages.test.tsx b/webui/src/tests/thread-messages.test.tsx index 8c26d9957..02d3bfedc 100644 --- a/webui/src/tests/thread-messages.test.tsx +++ b/webui/src/tests/thread-messages.test.tsx @@ -523,7 +523,7 @@ describe("ThreadMessages", () => { expect(document.querySelectorAll("[data-block-context-rail]")).toHaveLength(0); }); - it("ignores a completed empty answer frame without splitting contiguous activity", () => { + it.each([false, true])("ignores an empty answer frame without splitting contiguous activity (streaming=%s)", (isStreaming) => { const turnId = "turn-empty-answer-frame"; const segmentId = "activity-1"; const messages: UIMessage[] = [ @@ -574,7 +574,7 @@ describe("ThreadMessages", () => { id: "empty-answer-frame", role: "assistant", content: "", - isStreaming: false, + isStreaming, turnId, turnPhase: "answer", turnSeq: 10, @@ -637,12 +637,12 @@ describe("ThreadMessages", () => { expect(screen.getByTestId("agent-activity-content")).toHaveTextContent("Completed Second"); }); - it("keeps empty frame source counts on the nearest visible unit", () => { + it.each([false, true])("keeps empty frame source counts on the nearest visible unit (streaming=%s)", (isStreaming) => { const emptyFrame: UIMessage = { id: "empty", role: "assistant", content: "", - isStreaming: false, + isStreaming, turnPhase: "answer", createdAt: 2, }; @@ -667,16 +667,72 @@ describe("ThreadMessages", () => { sourceMessageCount: 2, }]); - const streamingUnits = buildDisplayUnits([{ - ...emptyFrame, - id: "streaming-placeholder", - isStreaming: true, - }]); - expect(streamingUnits).toMatchObject([{ - type: "activity", - messages: [{ id: "streaming-placeholder" }], - sourceMessageCount: 1, - }]); + const leadingFrameUnits = buildDisplayUnits([ + { ...emptyFrame, turnId: "original" }, + { id: "guidance", role: "user", content: "also check", turnId: "guidance", createdAt: 3 }, + { id: "answer", role: "assistant", content: "done", turnId: "guidance", createdAt: 4 }, + ]); + expect(leadingFrameUnits).toMatchObject([ + { type: "message", message: { id: "guidance" }, sourceMessageCount: 2 }, + { type: "message", message: { id: "answer" }, sourceMessageCount: 1 }, + ]); + + const afterNoticeUnits = buildDisplayUnits([ + { id: "user", role: "user", content: "check", createdAt: 1 }, + { id: "compact", role: "assistant", kind: "compaction", content: "", compaction: { id: "compact", phase: "started" }, createdAt: 2 }, + emptyFrame, + ]); + expect(afterNoticeUnits).toMatchObject([ + { type: "message", message: { id: "user" }, sourceMessageCount: 1 }, + { type: "message", message: { id: "compact" }, sourceMessageCount: 2 }, + ]); + }); + + it("keeps generic turn progress while an empty answer frame has no reasoning", () => { + const messages: UIMessage[] = [ + { id: "user", role: "user", content: "check", turnId: "turn", createdAt: 1 }, + { id: "empty", role: "assistant", content: "", isStreaming: true, turnId: "turn", turnPhase: "answer", createdAt: 2 }, + ]; + render(); + expect(screen.getByRole("status", { name: /^Working for / })).toBeInTheDocument(); + expect(screen.queryByTestId("activity-reasoning-marker")).not.toBeInTheDocument(); + }); + + it("keeps generic progress for an active turn without a user prompt", () => { + vi.useFakeTimers(); + const now = 1_800_000_000_000; + vi.setSystemTime(now); + const messages: UIMessage[] = [ + { id: "old-tool", role: "tool", kind: "trace", content: "old_search()", turnId: "old-turn", createdAt: now - 11_000 }, + { id: "previous", role: "assistant", content: "Previous answer", turnId: "old-turn", createdAt: now - 10_000 }, + { id: "empty", role: "assistant", content: "", isStreaming: true, turnId: "automation", turnPhase: "answer", createdAt: now }, + ]; + const { rerender } = render( + , + ); + expect(screen.getByRole("status", { name: "Working for 3s" })).toBeInTheDocument(); + expect(screen.queryByTestId("activity-reasoning-marker")).not.toBeInTheDocument(); + + rerender(); + expect(screen.getByTestId("agent-activity-content")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: /^Working for 3s/ })).toBeInTheDocument(); + expect(screen.queryByTestId("activity-reasoning-marker")).not.toBeInTheDocument(); + }); + + it("keeps generic progress when the only activity is a hidden subagent create", () => { + const messages: UIMessage[] = [ + { id: "user", role: "user", content: "check", turnId: "turn", createdAt: 1 }, + { id: "empty", role: "assistant", content: "", isStreaming: true, turnId: "turn", createdAt: 2 }, + { id: "create", role: "tool", kind: "trace", content: 'subagent({"action":"create"})', + traces: ['subagent({"action":"create"})'], turnId: "turn", createdAt: 3, + toolEvents: [{ call_id: "call-1", name: "subagent", phase: "end", arguments: { action: "create" } }] }, + ]; + render(); + expect(screen.getByRole("status", { name: /^Working for / })).toBeInTheDocument(); + expect(screen.queryByTestId("activity-reasoning-marker")).not.toBeInTheDocument(); }); it("offers a follow-up action for text selected within one completed answer", async () => { @@ -1180,6 +1236,17 @@ describe("ThreadMessages", () => { expect(dividerIndex).toBe(branchPromptIndex - 1); }); + it("keeps a fork boundary before a prompt when the visible window starts with an empty frame", () => { + const messages: UIMessage[] = [ + { id: "empty", role: "assistant", content: "", isStreaming: true, turnId: "original", createdAt: 1 }, + { id: "branch", role: "user", content: "branch prompt", turnId: "branch", createdAt: 2 }, + { id: "answer", role: "assistant", content: "branch answer", turnId: "branch", createdAt: 3 }, + ]; + render(); + const divider = screen.getByText("Forked from history"); + expect(divider.compareDocumentPosition(screen.getByText("branch prompt")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + }); + it("hides redundant task creation while retaining failed creates and other tool activity", async () => { const messages = projectThreadEvents([ { event: "user_message", chat_id: "a", starts_turn: true, turn_id: "turn", text: "Inspect" }, diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsx index e4e30f265..3515a0319 100644 --- a/webui/src/tests/thread-viewport.test.tsx +++ b/webui/src/tests/thread-viewport.test.tsx @@ -2494,6 +2494,25 @@ describe("ThreadViewport", () => { expect(visible).toHaveLength(INITIAL_HISTORY_WINDOW + 2); }); + it.each([false, true])("keeps an activity cluster together across an empty answer frame (streaming=%s)", (isStreaming) => { + const activity: UIMessage[] = [ + { id: "prompt", role: "user", content: "question", createdAt: 1 }, + { id: "first", role: "tool", kind: "trace", content: "first()", createdAt: 2 }, + { id: "empty", role: "assistant", content: "", turnPhase: "answer", isStreaming, createdAt: 3 }, + { id: "second", role: "tool", kind: "trace", content: "second()", createdAt: 4 }, + ]; + expect(windowMessages(activity, 1).map((message) => message.id)).toEqual(["first", "empty", "second"]); + }); + + it("keeps compaction notices as activity window boundaries", () => { + const activity: UIMessage[] = [ + { id: "first", role: "tool", kind: "trace", content: "first()", createdAt: 1 }, + { id: "compact", role: "assistant", kind: "compaction", content: "", compaction: { id: "compact", phase: "started" }, createdAt: 2 }, + { id: "second", role: "tool", kind: "trace", content: "second()", createdAt: 3 }, + ]; + expect(windowMessages(activity, 1).map((message) => message.id)).toEqual(["second"]); + }); + it("resets to the bottom when opening a different conversation", async () => { const scrollTo = vi.fn(); const { container, rerender } = render(