🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(agent): Smoother streaming (#15118)
Ben Bachemf0389d1c4400
diff --git a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsxindex e72a9d1a75..febc105fba 100644--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx@@ -5,6 +5,7 @@ import { useRouter } from "next/router";import { InAppAgentWindow } from "./InAppAgentWindow";import type { InAppAgentWindowConversation } from "./InAppAgentWindow";import { useInAppAiAgent } from "./InAppAiAgentProvider";+import { useSmoothStreamingMessages } from "./useSmoothStreamingMessages";import { getDrawerMessages } from "./utils/utils";import { getInAppAgentScreenContextDescription } from "@/src/ee/features/in-app-agent/context";import {@@ -48,6 +49,7 @@ export function ControlledInAppAgentWindow(isSubmitting,invalidateConversations,loadMoreConversations,+ liveMessageVersion,messages,pendingToolApprovals,approveToolCall,@@ -58,8 +60,20 @@ export function ControlledInAppAgentWindow(submit,submitFeedback,} = useInAppAiAgent();+ const {+ isAnimating,+ messages: displayedMessages,+ pendingToolApprovals: displayedPendingToolApprovals,+ runningToolCallIds,+ } = useSmoothStreamingMessages({+ messages,+ liveMessageVersion,+ pendingToolApprovals,+ shouldFlush: error !== null,+ });const isInputDisabled =isRunning ||+ isAnimating ||isSubmitting ||selectedConversationIsWriteLocked ||isSelectedConversationHydrating ||@@ -86,11 +100,19 @@ export function ControlledInAppAgentWindow(() =>getDrawerMessages({error,- isRunning,- messages,- pendingToolApprovals,+ isRunning: isRunning || isAnimating,+ messages: displayedMessages,+ pendingToolApprovals: displayedPendingToolApprovals,+ runningToolCallIds,}),- [error, isRunning, messages, pendingToolApprovals],+ [+ displayedMessages,+ displayedPendingToolApprovals,+ error,+ isAnimating,+ isRunning,+ runningToolCallIds,+ ],);const closeButtonProps =@@ -101,7 +123,9 @@ export function ControlledInAppAgentWindow(return (<InAppAgentWindowerror={displayError}- isAssistantTurnInProgress={isRunning || pendingToolApprovals.length > 0}+ isAssistantTurnInProgress={+ isRunning || isAnimating || displayedPendingToolApprovals.length > 0+ }isHeaderDragHandleEnabled={props.isHeaderDragHandleEnabled}isExpanded={props.isExpanded}isInputDisabled={isInputDisabled}diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 63afe63a69..17549694f9 100644--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -100,6 +100,7 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {isSelectedConversationHydrating: false,error: null,messages: [],+ liveMessageVersion: 0,conversations: [],hasMoreConversations: false,isLoadingMoreConversations: false,@@ -149,6 +150,7 @@ type InAppAiAgentContextType = {isSelectedConversationHydrating: boolean;error: InAppAgentError | null;messages: InAppAiAgentMessage[];+ liveMessageVersion: number;conversations: InAppAiAgentConversation[];hasMoreConversations: boolean;isLoadingMoreConversations: boolean;@@ -254,6 +256,10 @@ function InAppAiAgentProviderInner({{},);const [messages, setMessages] = useState<AgUiMessage[]>([]);+ // Only live AG-UI publications increment this version. The display smoother+ // uses it to distinguish stream updates from history hydration, including+ // updates where the agent mutates message objects in place.+ const [liveMessageVersion, setLiveMessageVersion] = useState(0);const [pendingToolApprovals, setPendingToolApprovals] = useState<InAppAgentPendingToolApproval[]>([]);@@ -269,6 +275,7 @@ function InAppAiAgentProviderInner({const activeRunIdRef = useRef<string | null>(null);const intentionalAbortRef = useRef(false);const submitInFlightRef = useRef(false);+ const runInFlightRef = useRef(false);const subscriptionRef = useRef<ReturnType<HttpAgent["subscribe"]> | null>(null,);@@ -443,6 +450,10 @@ function InAppAiAgentProviderInner({currentIds.size > 0 ? new Set() : currentIds,);}, []);+ const publishLiveMessages = useCallback((messages: AgUiMessage[]) => {+ setMessages(messages);+ setLiveMessageVersion((currentVersion) => currentVersion + 1);+ }, []);const resetAgent = useCallback(() => {if (agentRef.current?.isRunning) {@@ -590,7 +601,7 @@ function InAppAiAgentProviderInner({console.error("In-app agent drawer run error", event);},onMessagesChanged: ({ messages }) => {- setMessages(+ publishLiveMessages(attachActiveRunIdToAssistantMessages(messages.filter(isAgentConversationMessage),activeRunIdRef.current,@@ -598,7 +609,7 @@ function InAppAiAgentProviderInner({);},onStateChanged: ({ messages }) => {- setMessages(+ publishLiveMessages(attachActiveRunIdToAssistantMessages(messages.filter(isAgentConversationMessage),activeRunIdRef.current,@@ -607,7 +618,12 @@ function InAppAiAgentProviderInner({},});},- [clearLoadingEvents, updateLoadingEvent, updatePendingToolApprovals],+ [+ clearLoadingEvents,+ publishLiveMessages,+ updateLoadingEvent,+ updatePendingToolApprovals,+ ],);const getOrCreateAgent = useCallback(@@ -653,34 +669,40 @@ function InAppAiAgentProviderInner({quickActionAttribution?: InAppAgentQuickActionAttribution,messageEntryPoint?: InAppAgentMessageEntryPoint,) => {+ if (runInFlightRef.current) {+ return Promise.resolve(false);+ }++ runInFlightRef.current = true;clearLoadingEvents();setIsRunning(true);- return agent- .runAgent({- ...runParameters,- context: createInAppAgentScreenContext({- currentUrl: window.location.href,- }).concat(- createInAppAgentUserContext({- userName: session.data?.user?.name,- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- languages:- navigator.languages.length > 0- ? Array.from(navigator.languages)- : [navigator.language],- }),- quickActionAttribution- ? createInAppAgentQuickActionAttributionContext(- quickActionAttribution,- )- : [],- messageEntryPoint- ? createInAppAgentMessageEntryPointContext(messageEntryPoint)- : [],- ),- })- .then(() => true)- .catch((error) => {+ return (async () => {+ try {+ await agent.runAgent({+ ...runParameters,+ context: createInAppAgentScreenContext({+ currentUrl: window.location.href,+ }).concat(+ createInAppAgentUserContext({+ userName: session.data?.user?.name,+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ languages:+ navigator.languages.length > 0+ ? Array.from(navigator.languages)+ : [navigator.language],+ }),+ quickActionAttribution+ ? createInAppAgentQuickActionAttributionContext(+ quickActionAttribution,+ )+ : [],+ messageEntryPoint+ ? createInAppAgentMessageEntryPointContext(messageEntryPoint)+ : [],+ ),+ });+ return true;+ } catch (error) {if (intentionalAbortRef.current) {return false;}@@ -692,12 +714,11 @@ function InAppAiAgentProviderInner({setError(getInAppAgentError(error));console.error("In-app agent drawer error", error);return false;- })- .finally(() => {+ } finally {const runId = activeRunIdRef.current;clearLoadingEvents();setIsRunning(false);- setMessages(+ publishLiveMessages(attachActiveRunIdToAssistantMessages(agent.messages.filter(isAgentConversationMessage),runId,@@ -711,11 +732,14 @@ function InAppAiAgentProviderInner({releaseSubmitLock();activeRunIdRef.current = null;intentionalAbortRef.current = false;- });+ runInFlightRef.current = false;+ }+ })();},[projectId,clearLoadingEvents,+ publishLiveMessages,releaseSubmitLock,session.data?.user?.name,utils.inAppAgent.getConversation,@@ -802,7 +826,8 @@ function InAppAiAgentProviderInner({isInAppAgentRateLimited(error) ||(options?.newConversation !== true &&isSelectedConversationHydrating) ||- submitInFlightRef.current+ submitInFlightRef.current ||+ runInFlightRef.current) {return false;}@@ -1009,6 +1034,7 @@ function InAppAiAgentProviderInner({!approval ||!selectedConversationId ||isRunning ||+ runInFlightRef.current ||isInAppAgentRateLimited(error)) {return;@@ -1127,6 +1153,7 @@ function InAppAiAgentProviderInner({isSelectedConversationHydrating,error,messages: messagesWithUiState,+ liveMessageVersion,conversations,hasMoreConversations,isLoadingMoreConversations,@@ -1155,6 +1182,7 @@ function InAppAiAgentProviderInner({isSelectedConversationNotFound,deleteConversation,loadMoreConversations,+ liveMessageVersion,messagesWithUiState,open,openAssistant,diff --git a/web/src/ee/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx b/web/src/ee/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsxnew file mode 100644index 0000000000..ff3c8fe32c--- /dev/null+++ b/web/src/ee/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx@@ -0,0 +1,750 @@+import { act, render, screen } from "@testing-library/react";+import { StrictMode } from "react";++import type { InAppAgentPendingToolApproval } from "./InAppAiAgentProvider";+import type { AgUiMessage } from "@/src/ee/features/in-app-agent/schema";+import { useSmoothStreamingMessages } from "./useSmoothStreamingMessages";++const userMessage = {+ id: "user",+ role: "user",+ content: "Investigate this",+} satisfies AgUiMessage;++const assistantMessage = (content: string) =>+ ({+ id: "assistant",+ role: "assistant",+ content,+ }) satisfies AgUiMessage;++const reasoningMessage = (content: string) =>+ ({+ id: "reasoning",+ role: "reasoning",+ content,+ }) satisfies AgUiMessage;++const assistantToolMessage = (toolCallIds: string[], isLoading: boolean) =>+ ({+ id: "assistant-tools",+ role: "assistant",+ content: "",+ isLoading,+ toolCalls: toolCallIds.map((toolCallId) => ({+ id: toolCallId,+ type: "function" as const,+ function: {+ name: `tool-${toolCallId}`,+ arguments: "{}",+ },+ })),+ }) satisfies AgUiMessage & { isLoading: boolean };++const toolResultMessage = (toolCallId: string) =>+ ({+ id: `result-${toolCallId}`,+ role: "tool",+ toolCallId,+ content: "done",+ }) satisfies AgUiMessage;++const pendingToolApproval = (+ id: string,+ status: InAppAgentPendingToolApproval["status"],+) =>+ ({+ id,+ status,+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: id,+ toolName: `tool-${id}`,+ args: {},+ runId: "run-1",+ },+ }) satisfies InAppAgentPendingToolApproval;++let prefersReducedMotion = false;+const noPendingToolApprovals: InAppAgentPendingToolApproval[] = [];++function runAllAnimationFrames() {+ while (vi.getTimerCount() > 0) {+ act(() => {+ vi.advanceTimersByTime(40);+ });+ }+}++function advanceAnimationFrames(frameCount: number) {+ for (let frame = 0; frame < frameCount; frame += 1) {+ act(() => {+ vi.advanceTimersByTime(40);+ });+ }+}++function TestConsumer({+ liveMessageVersion,+ messages,+ pendingToolApprovals = noPendingToolApprovals,+}: {+ liveMessageVersion: number;+ messages: AgUiMessage[];+ pendingToolApprovals?: InAppAgentPendingToolApproval[];+}) {+ const smoothStreaming = useSmoothStreamingMessages({+ messages,+ liveMessageVersion,+ pendingToolApprovals,+ shouldFlush: false,+ });+ const latestMessage = smoothStreaming.messages.at(-1);+ const isLoading =+ latestMessage &&+ "isLoading" in latestMessage &&+ latestMessage.isLoading === true;+ const toolCallIds = smoothStreaming.messages.flatMap((message) =>+ message.role === "assistant"+ ? (message.toolCalls?.map((toolCall) => toolCall.id) ?? [])+ : [],+ );+ const toolResultIds = smoothStreaming.messages.flatMap((message) =>+ message.role === "tool" ? [message.toolCallId] : [],+ );++ return (+ <>+ <span data-testid="content">+ {typeof latestMessage?.content === "string"+ ? latestMessage.content+ : ""}+ </span>+ <span data-testid="animating">+ {smoothStreaming.isAnimating ? "true" : "false"}+ </span>+ <span data-testid="loading">{isLoading ? "true" : "false"}</span>+ <span data-testid="message-ids">+ {smoothStreaming.messages.map((message) => message.id).join(",")}+ </span>+ {smoothStreaming.messages.map((message) =>+ typeof message.content === "string" ? (+ <span key={message.id} data-testid={`content-${message.id}`}>+ {message.content}+ </span>+ ) : null,+ )}+ <span data-testid="approval-ids">+ {smoothStreaming.pendingToolApprovals+ .map((approval) => approval.id)+ .join(",")}+ </span>+ <span data-testid="approval-statuses">+ {smoothStreaming.pendingToolApprovals+ .map((approval) => approval.status)+ .join(",")}+ </span>+ <span data-testid="running-tool-call-ids">+ {smoothStreaming.runningToolCallIds.join(",")}+ </span>+ <span data-testid="tool-call-ids">{toolCallIds.join(",")}</span>+ <span data-testid="tool-result-ids">{toolResultIds.join(",")}</span>+ </>+ );+}++describe("useSmoothStreamingMessages", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ prefersReducedMotion = false;+ vi.stubGlobal(+ "matchMedia",+ vi.fn(() => ({ matches: prefersReducedMotion })),+ );+ });++ afterEach(() => {+ vi.runOnlyPendingTimers();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ it("keeps display pacing and loading state local to the transcript", () => {+ const content =+ "This coarse canonical update should be revealed smoothly by the transcript only.";+ const assistantMessage = (isLoading: boolean) =>+ ({+ id: "assistant",+ role: "assistant",+ content,+ isLoading,+ }) satisfies AgUiMessage & { isLoading: boolean };+ const { rerender } = render(+ <StrictMode>+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />+ </StrictMode>,+ );++ rerender(+ <StrictMode>+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(true)]}+ />+ </StrictMode>,+ );++ expect(screen.getByTestId("content")).not.toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("true");++ rerender(+ <StrictMode>+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(false)]}+ />+ </StrictMode>,+ );++ expect(screen.getByTestId("loading")).toHaveTextContent("true");++ act(() => {+ vi.advanceTimersByTime(300);+ });++ expect(screen.getByTestId("content")).not.toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("true");++ runAllAnimationFrames();++ expect(screen.getByTestId("content")).toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ expect(screen.getByTestId("loading")).toHaveTextContent("false");+ });++ it("does not animate hydrated history", () => {+ const content =+ "This historical assistant response is long but should appear immediately.";+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={0}+ messages={[+ {+ id: "assistant",+ role: "assistant",+ content,+ },+ ]}+ />,+ );++ expect(screen.getByTestId("content")).toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ });++ it("animates a live message that completes in one update", () => {+ const content =+ "This final response arrived atomically but should still be displayed smoothly.";+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[+ userMessage,+ {+ id: "assistant",+ role: "assistant",+ content,+ },+ ]}+ />,+ );++ expect(screen.getByTestId("content")).not.toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("true");++ runAllAnimationFrames();++ expect(screen.getByTestId("content")).toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ });++ it("matches the observed generation rate for the next text chunk", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );+ const emptyAssistantMessage = assistantMessage("");++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, emptyAssistantMessage]}+ />,+ );+ act(() => {+ vi.advanceTimersByTime(2_000);+ });++ const generatedContent = "x".repeat(200);+ rerender(+ <TestConsumer+ liveMessageVersion={2}+ messages={[userMessage, assistantMessage(generatedContent)]}+ />,+ );+ advanceAnimationFrames(25);++ const displayedLength =+ screen.getByTestId("content-assistant").textContent?.length ?? 0;+ expect(displayedLength).toBeGreaterThanOrEqual(75);+ expect(displayedLength).toBeLessThanOrEqual(85);+ runAllAnimationFrames();+ });++ it("keeps pacing headroom when the next chunk arrives late", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage("")]}+ />,+ );+ act(() => {+ vi.advanceTimersByTime(2_000);+ });++ const generatedContent = "x".repeat(200);+ rerender(+ <TestConsumer+ liveMessageVersion={2}+ messages={[userMessage, assistantMessage(generatedContent)]}+ />,+ );+ advanceAnimationFrames(50);++ const displayedLength =+ screen.getByTestId("content-assistant").textContent?.length ?? 0;+ expect(displayedLength).toBeGreaterThanOrEqual(155);+ expect(displayedLength).toBeLessThanOrEqual(165);+ expect(screen.getByTestId("animating")).toHaveTextContent("true");+ runAllAnimationFrames();+ });++ it("limits acceleration from one unusually fast chunk", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage("")]}+ />,+ );+ act(() => {+ vi.advanceTimersByTime(2_000);+ });+ rerender(+ <TestConsumer+ liveMessageVersion={2}+ messages={[userMessage, assistantMessage("x".repeat(100))]}+ />,+ );+ act(() => {+ vi.advanceTimersByTime(100);+ });++ rerender(+ <TestConsumer+ liveMessageVersion={3}+ messages={[userMessage, assistantMessage("x".repeat(200))]}+ />,+ );+ const displayedBeforeFastChunk =+ screen.getByTestId("content-assistant").textContent?.length ?? 0;+ advanceAnimationFrames(25);++ const displayedAfterOneSecond =+ screen.getByTestId("content-assistant").textContent?.length ?? 0;+ expect(+ displayedAfterOneSecond - displayedBeforeFastChunk,+ ).toBeGreaterThanOrEqual(45);+ expect(+ displayedAfterOneSecond - displayedBeforeFastChunk,+ ).toBeLessThanOrEqual(51);+ runAllAnimationFrames();+ });++ it("reveals reasoning and assistant text before later tools", () => {+ const reasoningContent = "r".repeat(40);+ const assistantContent = "a".repeat(40);+ const toolMessage = {+ id: "tool-result",+ role: "tool",+ toolCallId: "tool-call",+ content: "done",+ } satisfies AgUiMessage;+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[+ userMessage,+ reasoningMessage(reasoningContent),+ {+ id: "assistant-2",+ role: "assistant",+ content: assistantContent,+ },+ toolMessage,+ ]}+ />,+ );+ advanceAnimationFrames(30);++ expect(screen.getByTestId("content-reasoning")).toHaveTextContent(+ reasoningContent,+ );+ expect(screen.getByTestId("content-assistant-2")).not.toHaveTextContent(+ assistantContent,+ );+ expect(screen.getByTestId("message-ids")).not.toHaveTextContent(+ "tool-result",+ );+ });++ it("smooths reasoning without splitting graphemes", () => {+ const content =+ "Checking 👨👩👧👦 cafe\u0301 latency across the selected traces.";+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, reasoningMessage(content)]}+ />,+ );++ const renderedContent = [screen.getByTestId("content").textContent];+ while (vi.getTimerCount() > 0) {+ act(() => {+ vi.advanceTimersByTime(40);+ });+ renderedContent.push(screen.getByTestId("content").textContent);+ }++ expect(renderedContent).not.toContain("Checking 👨");+ expect(renderedContent).not.toContain("Checking 👨");+ expect(screen.getByTestId("content")).toHaveTextContent(content);+ });++ it("detects content when the agent mutates a message in place", () => {+ const reasoning = reasoningMessage("");+ const messages = [userMessage, reasoning];+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={messages} />,+ );++ reasoning.content =+ "The agent mutated this reasoning object with a large chunk instead of replacing it.";+ rerender(<TestConsumer liveMessageVersion={1} messages={messages} />);++ expect(screen.getByTestId("content")).not.toHaveTextContent(+ reasoning.content,+ );++ runAllAnimationFrames();+ expect(screen.getByTestId("content")).toHaveTextContent(reasoning.content);+ });++ it("applies small chunks immediately", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage("Short")]}+ />,+ );++ expect(screen.getByTestId("content")).toHaveTextContent("Short");+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ expect(vi.getTimerCount()).toBe(0);+ });++ it("holds structural messages behind buffered text", () => {+ const content =+ "First reveal this complete explanation before showing the tool result that follows it.";+ const toolMessage = {+ id: "tool-result",+ role: "tool",+ toolCallId: "tool-call",+ content: "done",+ } satisfies AgUiMessage;+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(content)]}+ />,+ );+ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(content), toolMessage]}+ />,+ );++ expect(screen.getByTestId("message-ids")).not.toHaveTextContent(+ "tool-result",+ );++ runAllAnimationFrames();+ expect(screen.getByTestId("message-ids")).toHaveTextContent(+ "user,assistant,tool-result",+ );+ });++ it("reveals at most two tools per second", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[+ userMessage,+ assistantToolMessage(["tool-1", "tool-2", "tool-3"], true),+ ]}+ />,+ );++ expect(screen.getByTestId("tool-call-ids")).toHaveTextContent("tool-1");+ expect(screen.getByTestId("tool-call-ids")).not.toHaveTextContent("tool-2");++ act(() => {+ vi.advanceTimersByTime(499);+ });+ expect(screen.getByTestId("tool-call-ids")).not.toHaveTextContent("tool-2");++ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(screen.getByTestId("tool-call-ids")).toHaveTextContent(+ "tool-1,tool-2",+ );++ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(screen.getByTestId("tool-call-ids")).toHaveTextContent(+ "tool-1,tool-2,tool-3",+ );+ });++ it("preserves tool pacing across loading-only updates", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );+ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[+ userMessage,+ assistantToolMessage(["tool-1", "tool-2"], true),+ ]}+ />,+ );++ act(() => {+ vi.advanceTimersByTime(100);+ });+ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[+ userMessage,+ assistantToolMessage(["tool-1", "tool-2"], false),+ ]}+ />,+ );++ expect(screen.getByTestId("tool-call-ids")).toHaveTextContent("tool-1");+ expect(screen.getByTestId("tool-call-ids")).not.toHaveTextContent("tool-2");+ expect(screen.getByTestId("running-tool-call-ids")).toHaveTextContent(+ "tool-1",+ );++ act(() => {+ vi.advanceTimersByTime(649);+ });+ expect(screen.getByTestId("running-tool-call-ids")).toHaveTextContent(+ "tool-1",+ );+ });++ it("keeps a completed tool running for at least 750 ms", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );+ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantToolMessage(["tool-1"], true)]}+ />,+ );++ act(() => {+ vi.advanceTimersByTime(100);+ });+ rerender(+ <TestConsumer+ liveMessageVersion={2}+ messages={[+ userMessage,+ assistantToolMessage(["tool-1"], false),+ toolResultMessage("tool-1"),+ ]}+ />,+ );++ expect(screen.getByTestId("tool-result-ids")).toBeEmptyDOMElement();+ expect(screen.getByTestId("animating")).toHaveTextContent("true");++ act(() => {+ vi.advanceTimersByTime(649);+ });+ expect(screen.getByTestId("tool-result-ids")).toBeEmptyDOMElement();++ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(screen.getByTestId("tool-result-ids")).toHaveTextContent("tool-1");+ });++ it("paces approval appearance but applies submitting immediately", () => {+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );+ const firstApproval = pendingToolApproval("approval-1", "pending");+ const secondApproval = pendingToolApproval("approval-2", "pending");++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage]}+ pendingToolApprovals={[firstApproval, secondApproval]}+ />,+ );++ expect(screen.getByTestId("approval-ids")).toHaveTextContent("approval-1");+ expect(screen.getByTestId("approval-ids")).not.toHaveTextContent(+ "approval-2",+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage]}+ pendingToolApprovals={[+ pendingToolApproval("approval-1", "submitting"),+ secondApproval,+ ]}+ />,+ );+ expect(screen.getByTestId("approval-statuses")).toHaveTextContent(+ "submitting",+ );++ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(screen.getByTestId("approval-ids")).toHaveTextContent(+ "approval-1,approval-2",+ );+ });++ it("does not animate for reduced-motion users", () => {+ prefersReducedMotion = true;+ const content =+ "This large chunk should be applied at once when reduced motion is enabled.";+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(content)]}+ />,+ );++ expect(screen.getByTestId("content")).toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ expect(vi.getTimerCount()).toBe(0);+ });++ it("flushes active animation when animation becomes disabled", () => {+ const content =+ "This active animation should finish when reduced motion becomes enabled.";+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(content)]}+ />,+ );+ prefersReducedMotion = true;+ act(() => {+ document.dispatchEvent(new Event("visibilitychange"));+ });++ expect(screen.getByTestId("content")).toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ expect(vi.getTimerCount()).toBe(0);+ });++ it("cancels animation when the transcript unmounts", () => {+ const content =+ "This buffered response must not update the transcript after it unmounts.";+ const { rerender, unmount } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(content)]}+ />,+ );+ expect(vi.getTimerCount()).toBeGreaterThan(0);++ unmount();++ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/web/src/ee/features/in-app-agent/components/useSmoothStreamingMessages.ts b/web/src/ee/features/in-app-agent/components/useSmoothStreamingMessages.tsnew file mode 100644index 0000000000..558e66ca8a--- /dev/null+++ b/web/src/ee/features/in-app-agent/components/useSmoothStreamingMessages.ts@@ -0,0 +1,886 @@+import { useEffect, useEffectEvent, useReducer } from "react";++import type { InAppAgentPendingToolApproval } from "./InAppAiAgentProvider";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";+import type { AgUiMessage } from "@/src/ee/features/in-app-agent/schema";+import { assertUnreachable } from "@/src/utils/types";++const FRAME_DURATION_MS = 40;+const DEFAULT_GRAPHEMES_PER_SECOND = 40;+const MIN_GRAPHEMES_PER_SECOND = 20;+const MAX_GRAPHEMES_PER_SECOND = 400;+const PACING_EMA_WEIGHT = 0.35;+const PACING_TARGET_UTILIZATION = 0.8;+const MAX_PACING_INCREASE_FACTOR = 1.2;+const MIN_SMOOTHED_GRAPHEMES = 16;+const TOOL_TRANSITION_INTERVAL_MS = 500;+const MIN_TOOL_RUNNING_DURATION_MS = 750;++type ToolDisplayState = Record<+ string,+ {+ visibleAtMs: number;+ terminalVisible: boolean;+ order: number;+ }+>;++type SmoothStreamingState = {+ displayedMessages: AgUiMessage[];+ targetMessages: AgUiMessage[];+ liveMessageVersion: number;+ textPacingByMessageId: Record<+ string,+ {+ lastPublishedAtMs: number;+ graphemesPerSecond: number | null;+ }+ >;+ targetToolApprovals: InAppAgentPendingToolApproval[];+ displayedToolApprovals: InAppAgentPendingToolApproval[];+ toolDisplayById: ToolDisplayState;+ lastToolTransitionAtMs: number | null;+ nowMs: number;+ animation: {+ messageId: string;+ graphemeBudget: number;+ } | null;+};++/**+ * Keeps canonical AG-UI messages untouched while exposing a paced display copy.+ * `liveMessageVersion` changes only for live stream publications, so hydrated+ * history appears immediately. The reducer owns display progress; effects only+ * integrate it with the browser timer and visibility lifecycle.+ */+export function useSmoothStreamingMessages({+ messages,+ liveMessageVersion,+ pendingToolApprovals,+ shouldFlush,+}: {+ messages: AgUiMessage[];+ liveMessageVersion: number;+ pendingToolApprovals: InAppAgentPendingToolApproval[];+ shouldFlush: boolean;+}) {+ const [state, dispatch] = useReducer(+ smoothStreamingReducer,+ { messages, liveMessageVersion },+ ({ messages: initialMessages, liveMessageVersion: initialVersion }) => {+ const initialSnapshot = snapshotMessages(initialMessages);+ const initialToolDisplay = createImmediateToolDisplay(+ initialSnapshot,+ pendingToolApprovals,+ );++ return {+ displayedMessages: initialSnapshot,+ targetMessages: initialSnapshot,+ liveMessageVersion: initialVersion,+ textPacingByMessageId: {},+ targetToolApprovals: pendingToolApprovals,+ displayedToolApprovals: pendingToolApprovals,+ toolDisplayById: initialToolDisplay,+ lastToolTransitionAtMs: null,+ nowMs: performance.now(),+ animation: null,+ } satisfies SmoothStreamingState;+ },+ );++ const canAnimate = useEffectEvent(+ () =>+ !shouldFlush &&+ document.visibilityState === "visible" &&+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches,+ );++ useEffect(() => {+ dispatch({+ type: "enqueue",+ messages,+ liveMessageVersion,+ pendingToolApprovals,+ canAnimate: canAnimate(),+ publishedAtMs: performance.now(),+ });+ }, [liveMessageVersion, messages, pendingToolApprovals]);++ const animation = state.animation;+ const nextToolTransitionAtMs = getNextToolTransitionAtMs(state);+ useEffect(() => {+ if (animation === null && nextToolTransitionAtMs === null) {+ return;+ }++ const delayMs =+ animation === null && nextToolTransitionAtMs !== null+ ? Math.max(0, nextToolTransitionAtMs - performance.now())+ : FRAME_DURATION_MS;+ const timeoutId = window.setTimeout(() => {+ dispatch({+ type: canAnimate() ? "tick" : "finish",+ nowMs: performance.now(),+ });+ }, delayMs);++ return () => {+ window.clearTimeout(timeoutId);+ };+ }, [animation, nextToolTransitionAtMs]);++ const isAnimating = animation !== null || nextToolTransitionAtMs !== null;+ useEffect(() => {+ if (!isAnimating) {+ return;+ }++ const handleVisibilityChange = () => {+ if (!canAnimate()) {+ dispatch({ type: "finish", nowMs: performance.now() });+ }+ };++ document.addEventListener("visibilitychange", handleVisibilityChange);+ return () => {+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ };+ }, [isAnimating]);++ const activeMessageId = animation?.messageId ?? null;+ const projectedMessages = projectToolMessages(+ state.displayedMessages,+ state.toolDisplayById,+ );+ const runningToolCallIds = getRunningToolCallIds(state.toolDisplayById);++ return {+ isAnimating,+ pendingToolApprovals: state.displayedToolApprovals,+ runningToolCallIds,+ messages:+ activeMessageId === null+ ? projectedMessages+ : projectedMessages.map((message) =>+ message.id === activeMessageId+ ? { ...message, isLoading: true }+ : message,+ ),+ };+}++type SmoothStreamingAction =+ | {+ type: "enqueue";+ messages: AgUiMessage[];+ liveMessageVersion: number;+ pendingToolApprovals: InAppAgentPendingToolApproval[];+ canAnimate: boolean;+ publishedAtMs: number;+ }+ | { type: "tick"; nowMs: number }+ | { type: "finish"; nowMs: number };++function smoothStreamingReducer(+ state: SmoothStreamingState,+ action: SmoothStreamingAction,+) {+ if (action.type === "enqueue") {+ return enqueueStreamingUpdate(state, action);+ }++ if (action.type === "tick") {+ const nextState = {+ ...state,+ nowMs: action.nowMs,+ };+ const nextTextState = nextState.animation+ ? advanceStreamingFrame(nextState)+ : nextState;++ return nextTextState.animation === null+ ? applyNextToolTransition(nextTextState, action.nowMs)+ : nextTextState;+ }++ if (action.type === "finish") {+ return flushStreaming(state, action.nowMs);+ }++ return assertUnreachable(action);+}++function enqueueStreamingUpdate(+ state: SmoothStreamingState,+ action: Extract<SmoothStreamingAction, { type: "enqueue" }>,+) {+ const nextMessages = snapshotMessages(action.messages);+ const isLivePublication =+ action.liveMessageVersion !== state.liveMessageVersion;+ const isLoadingOnlyUpdate =+ !isLivePublication &&+ areMessagesEqualExceptLoading(state.targetMessages, nextMessages);+ const publishedTexts = isLivePublication+ ? findPublishedTexts(state.targetMessages, nextMessages)+ : [];+ const nextState = {+ ...state,+ targetMessages: nextMessages,+ liveMessageVersion: action.liveMessageVersion,+ targetToolApprovals: action.pendingToolApprovals,+ displayedToolApprovals: mergeDisplayedToolApprovals(+ state.displayedToolApprovals,+ action.pendingToolApprovals,+ ),+ nowMs: action.publishedAtMs,+ textPacingByMessageId: isLivePublication+ ? updateTextPacing(+ state.textPacingByMessageId,+ publishedTexts,+ nextMessages,+ action.publishedAtMs,+ )+ : state.textPacingByMessageId,+ };+ const nextTextState = updateTextStreaming(+ nextState,+ publishedTexts,+ action.canAnimate,+ );+ const approvalsChanged = !areToolApprovalsEqual(+ state.targetToolApprovals,+ action.pendingToolApprovals,+ );++ if (+ !action.canAnimate ||+ (!isLivePublication &&+ !isLoadingOnlyUpdate &&+ !approvalsChanged &&+ nextTextState.animation === null)+ ) {+ return flushStreaming(nextTextState, action.publishedAtMs);+ }++ if (nextTextState.animation !== null) {+ return nextTextState;+ }++ return applyNextToolTransition(nextTextState, action.publishedAtMs);+}++function updateTextStreaming(+ state: SmoothStreamingState,+ publishedTexts: ReturnType<typeof findPublishedTexts>,+ canAnimate: boolean,+) {+ const appendedText = publishedTexts.find(+ (+ publishedText,+ ): publishedText is { messageId: string; appendedText: string } =>+ typeof publishedText.appendedText === "string" &&+ publishedText.appendedText.length > 0,+ );++ if (!appendedText) {+ return state.animation === null ? finishTextStreaming(state) : state;+ }++ if (!canAnimate) {+ return finishTextStreaming(state);+ }++ if (state.animation !== null) {+ return state;+ }++ if (+ splitGraphemes(appendedText.appendedText).length < MIN_SMOOTHED_GRAPHEMES+ ) {+ return finishTextStreaming(state);+ }++ return advanceStreamingFrame({+ ...state,+ animation: {+ messageId: appendedText.messageId,+ graphemeBudget: 0,+ },+ });+}++function advanceStreamingFrame(state: SmoothStreamingState) {+ if (state.animation === null) {+ return state;+ }++ const pendingText = findPendingText(+ state.displayedMessages,+ state.targetMessages,+ );+ if (!pendingText) {+ return finishTextStreaming(state);+ }++ const remainingGraphemes = splitGraphemes(+ pendingText.targetText.slice(pendingText.displayedText.length),+ );+ const graphemeBudget =+ state.animation.graphemeBudget ++ (state.textPacingByMessageId[pendingText.targetMessage.id]+ ?.graphemesPerSecond ?? DEFAULT_GRAPHEMES_PER_SECOND) *+ (FRAME_DURATION_MS / 1_000);+ const graphemesThisFrame = Math.floor(graphemeBudget);+ const nextText =+ pendingText.displayedText ++ remainingGraphemes.slice(0, graphemesThisFrame).join("");++ if (nextText === pendingText.targetText) {+ const displayedMessages = state.targetMessages.slice(+ 0,+ pendingText.targetIndex + 1,+ );+ const nextPendingText = findPendingText(+ displayedMessages,+ state.targetMessages,+ );++ if (!nextPendingText) {+ return finishTextStreaming(state);+ }++ return advanceStreamingFrame({+ ...state,+ displayedMessages,+ animation: {+ messageId: nextPendingText.targetMessage.id,+ graphemeBudget: 0,+ },+ });+ }++ return {+ ...state,+ displayedMessages: state.targetMessages+ .slice(0, pendingText.targetIndex)+ .concat(withTextContent(pendingText.targetMessage, nextText)),+ animation: {+ messageId: pendingText.targetMessage.id,+ graphemeBudget: graphemeBudget - graphemesThisFrame,+ },+ };+}++function finishTextStreaming(state: SmoothStreamingState) {+ return {+ ...state,+ displayedMessages: state.targetMessages,+ animation: null,+ };+}++function flushStreaming(state: SmoothStreamingState, nowMs: number) {+ const finishedTextState = finishTextStreaming(state);++ return {+ ...finishedTextState,+ displayedToolApprovals: state.targetToolApprovals,+ toolDisplayById: createImmediateToolDisplay(+ state.targetMessages,+ state.targetToolApprovals,+ nowMs,+ ),+ lastToolTransitionAtMs: null,+ nowMs,+ };+}++function getTargetTools(+ messages: AgUiMessage[],+ pendingToolApprovals: InAppAgentPendingToolApproval[],+) {+ const resultToolCallIds = new Set(+ messages.flatMap((message) =>+ message.role === "tool" ? [message.toolCallId] : [],+ ),+ );+ const approvalIds = new Set(+ pendingToolApprovals.map((approval) => approval.id),+ );+ const tools: Array<{+ id: string;+ isTerminal: boolean;+ order: number;+ }> = [];+ const seenToolCallIds = new Set<string>();++ for (const message of messages) {+ if (message.role !== "assistant") {+ continue;+ }++ for (const toolCall of message.toolCalls ?? []) {+ if (toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME) {+ continue;+ }++ seenToolCallIds.add(toolCall.id);+ tools.push({+ id: toolCall.id,+ isTerminal:+ resultToolCallIds.has(toolCall.id) ||+ (!isMessageLoading(message) && !approvalIds.has(toolCall.id)),+ order: tools.length,+ });+ }+ }++ for (const approval of pendingToolApprovals) {+ if (seenToolCallIds.has(approval.id)) {+ continue;+ }++ tools.push({+ id: approval.id,+ isTerminal: false,+ order: tools.length,+ });+ }++ return tools;+}++function createImmediateToolDisplay(+ messages: AgUiMessage[],+ pendingToolApprovals: InAppAgentPendingToolApproval[],+ visibleAtMs = 0,+) {+ const toolDisplayById: ToolDisplayState = {};++ for (const tool of getTargetTools(messages, pendingToolApprovals)) {+ toolDisplayById[tool.id] = {+ visibleAtMs,+ terminalVisible: tool.isTerminal,+ order: tool.order,+ };+ }++ return toolDisplayById;+}++function getToolTransitionCandidates(state: SmoothStreamingState) {+ const targetTools = getTargetTools(+ state.targetMessages,+ state.targetToolApprovals,+ );+ const targetToolsById = new Map(targetTools.map((tool) => [tool.id, tool]));+ const nextGlobalTransitionAtMs =+ state.lastToolTransitionAtMs === null+ ? state.nowMs+ : state.lastToolTransitionAtMs + TOOL_TRANSITION_INTERVAL_MS;+ const candidates: Array<{+ id: string;+ type: "appearance" | "terminal";+ dueAtMs: number;+ order: number;+ }> = [];++ for (const tool of targetTools) {+ if (!state.toolDisplayById[tool.id]) {+ candidates.push({+ id: tool.id,+ type: "appearance",+ dueAtMs: nextGlobalTransitionAtMs,+ order: tool.order,+ });+ }+ }++ for (const [toolCallId, display] of Object.entries(state.toolDisplayById)) {+ const targetTool = targetToolsById.get(toolCallId);+ if (!display.terminalVisible && (!targetTool || targetTool.isTerminal)) {+ candidates.push({+ id: toolCallId,+ type: "terminal",+ dueAtMs: Math.max(+ nextGlobalTransitionAtMs,+ display.visibleAtMs + MIN_TOOL_RUNNING_DURATION_MS,+ ),+ order: display.order,+ });+ }+ }++ return candidates;+}++function getNextToolTransitionAtMs(state: SmoothStreamingState) {+ const candidates = getToolTransitionCandidates(state);+ if (candidates.length === 0) {+ return null;+ }++ return Math.min(...candidates.map((candidate) => candidate.dueAtMs));+}++function applyNextToolTransition(state: SmoothStreamingState, nowMs: number) {+ const candidate = getToolTransitionCandidates(state)+ .filter((transition) => transition.dueAtMs <= nowMs)+ .sort((left, right) => left.order - right.order)[0];++ if (!candidate) {+ return state;+ }++ if (candidate.type === "appearance") {+ const targetTool = getTargetTools(+ state.targetMessages,+ state.targetToolApprovals,+ ).find((tool) => tool.id === candidate.id);+ if (!targetTool) {+ return state;+ }++ const approval = state.targetToolApprovals.find(+ (currentApproval) => currentApproval.id === candidate.id,+ );+ return {+ ...state,+ displayedToolApprovals:+ approval &&+ !state.displayedToolApprovals.some(+ (displayedApproval) => displayedApproval.id === approval.id,+ )+ ? state.displayedToolApprovals.concat(approval)+ : state.displayedToolApprovals,+ toolDisplayById: {+ ...state.toolDisplayById,+ [candidate.id]: {+ visibleAtMs: nowMs,+ terminalVisible: false,+ order: targetTool.order,+ },+ },+ lastToolTransitionAtMs: nowMs,+ nowMs,+ };+ }++ const display = state.toolDisplayById[candidate.id];+ if (!display) {+ return state;+ }++ return {+ ...state,+ displayedToolApprovals: state.displayedToolApprovals.filter(+ (approval) => approval.id !== candidate.id,+ ),+ toolDisplayById: {+ ...state.toolDisplayById,+ [candidate.id]: {+ ...display,+ terminalVisible: true,+ },+ },+ lastToolTransitionAtMs: nowMs,+ nowMs,+ };+}++function mergeDisplayedToolApprovals(+ displayedApprovals: InAppAgentPendingToolApproval[],+ targetApprovals: InAppAgentPendingToolApproval[],+) {+ const targetApprovalsById = new Map(+ targetApprovals.map((approval) => [approval.id, approval]),+ );++ return displayedApprovals.map(+ (approval) => targetApprovalsById.get(approval.id) ?? approval,+ );+}++function areToolApprovalsEqual(+ currentApprovals: InAppAgentPendingToolApproval[],+ nextApprovals: InAppAgentPendingToolApproval[],+) {+ return (+ currentApprovals.length === nextApprovals.length &&+ currentApprovals.every(+ (approval, index) =>+ approval.id === nextApprovals[index]?.id &&+ approval.status === nextApprovals[index]?.status,+ )+ );+}++function projectToolMessages(+ messages: AgUiMessage[],+ toolDisplayById: ToolDisplayState,+) {+ const knownToolCallIds = new Set(Object.keys(toolDisplayById));+ for (const message of messages) {+ if (message.role !== "assistant") {+ continue;+ }++ for (const toolCall of message.toolCalls ?? []) {+ if (toolCall.function.name !== IN_APP_AGENT_REDIRECT_TOOL_NAME) {+ knownToolCallIds.add(toolCall.id);+ }+ }+ }++ return messages.flatMap<AgUiMessage>((message) => {+ if (message.role === "tool") {+ if (!knownToolCallIds.has(message.toolCallId)) {+ return [message];+ }++ return toolDisplayById[message.toolCallId]?.terminalVisible+ ? [message]+ : [];+ }++ if (message.role !== "assistant" || !message.toolCalls) {+ return [message];+ }++ const toolCalls = message.toolCalls.filter(+ (toolCall) =>+ toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME ||+ Boolean(toolDisplayById[toolCall.id]),+ );+ const hasPendingTool = message.toolCalls.some((toolCall) => {+ if (toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME) {+ return false;+ }++ return !toolDisplayById[toolCall.id]?.terminalVisible;+ });++ return [+ {+ ...message,+ toolCalls,+ ...(hasPendingTool ? { isLoading: true } : {}),+ },+ ];+ });+}++function getRunningToolCallIds(toolDisplayById: ToolDisplayState) {+ return Object.entries(toolDisplayById).flatMap(([toolCallId, display]) =>+ display.terminalVisible ? [] : [toolCallId],+ );+}++function isMessageLoading(message: AgUiMessage) {+ return "isLoading" in message && message.isLoading === true;+}++function snapshotMessages(messages: AgUiMessage[]) {+ // AG-UI may mutate message objects in place; snapshots keep reducer history+ // stable so appended text remains detectable on the next publication.+ return messages.map((message) => {+ if (message.role !== "assistant" || !message.toolCalls) {+ return { ...message };+ }++ return {+ ...message,+ toolCalls: message.toolCalls.map((toolCall) => ({+ ...toolCall,+ function: { ...toolCall.function },+ })),+ };+ });+}++function areMessagesEqualExceptLoading(+ currentMessages: AgUiMessage[],+ nextMessages: AgUiMessage[],+) {+ if (currentMessages.length !== nextMessages.length) {+ return false;+ }++ return currentMessages.every((message, index) => {+ const nextMessage = nextMessages[index];+ if (!nextMessage) {+ return false;+ }++ return (+ JSON.stringify(withoutLoadingState(message)) ===+ JSON.stringify(withoutLoadingState(nextMessage))+ );+ });+}++function withoutLoadingState(message: AgUiMessage) {+ const result: AgUiMessage & { isLoading?: boolean } = { ...message };+ delete result.isLoading;+ return result;+}++function getSmoothableText(message: AgUiMessage | undefined) {+ if (message?.role === "reasoning") {+ return message.content;+ }++ if (message?.role === "assistant" && typeof message.content === "string") {+ return message.content;+ }++ return null;+}++function findPublishedTexts(+ previousMessages: AgUiMessage[],+ nextMessages: AgUiMessage[],+) {+ const previousTextByMessageId = new Map(+ previousMessages.map((message) => [message.id, getSmoothableText(message)]),+ );+ const publishedTexts: Array<{+ messageId: string;+ appendedText: string | null;+ }> = [];++ for (const nextMessage of nextMessages) {+ const nextText = getSmoothableText(nextMessage);+ if (nextText === null) {+ continue;+ }++ const hasPreviousText = previousTextByMessageId.has(nextMessage.id);+ const previousText = previousTextByMessageId.get(nextMessage.id) ?? "";+ if (!hasPreviousText || nextText !== previousText) {+ publishedTexts.push({+ messageId: nextMessage.id,+ appendedText: nextText.startsWith(previousText)+ ? nextText.slice(previousText.length)+ : null,+ });+ }+ }++ return publishedTexts;+}++function updateTextPacing(+ currentPacing: SmoothStreamingState["textPacingByMessageId"],+ publishedTexts: ReturnType<typeof findPublishedTexts>,+ nextMessages: AgUiMessage[],+ publishedAtMs: number,+) {+ const nextPacing: SmoothStreamingState["textPacingByMessageId"] = {};+ const smoothableMessageIds = new Set(+ nextMessages.flatMap((message) =>+ getSmoothableText(message) === null ? [] : [message.id],+ ),+ );++ for (const messageId of smoothableMessageIds) {+ const pacing = currentPacing[messageId];+ if (pacing) {+ nextPacing[messageId] = pacing;+ }+ }++ for (const publishedText of publishedTexts) {+ const current = currentPacing[publishedText.messageId];+ const appendedGraphemes =+ publishedText.appendedText === null+ ? 0+ : splitGraphemes(publishedText.appendedText).length;+ const elapsedMs = current ? publishedAtMs - current.lastPublishedAtMs : 0;+ let graphemesPerSecond = current?.graphemesPerSecond ?? null;++ if (appendedGraphemes > 0 && elapsedMs > 0) {+ const targetRate = Math.min(+ MAX_GRAPHEMES_PER_SECOND,+ Math.max(+ MIN_GRAPHEMES_PER_SECOND,+ appendedGraphemes * (1_000 / elapsedMs) * PACING_TARGET_UTILIZATION,+ ),+ );+ if (graphemesPerSecond === null) {+ graphemesPerSecond = targetRate;+ } else {+ const smoothedRate =+ graphemesPerSecond * (1 - PACING_EMA_WEIGHT) ++ targetRate * PACING_EMA_WEIGHT;+ graphemesPerSecond = Math.min(+ smoothedRate,+ graphemesPerSecond * MAX_PACING_INCREASE_FACTOR,+ );+ }+ }++ nextPacing[publishedText.messageId] = {+ lastPublishedAtMs: publishedAtMs,+ graphemesPerSecond,+ };+ }++ return nextPacing;+}++function findPendingText(+ displayedMessages: AgUiMessage[],+ targetMessages: AgUiMessage[],+) {+ const displayedTextByMessageId = new Map(+ displayedMessages.map((message) => [+ message.id,+ getSmoothableText(message),+ ]),+ );++ for (const [targetIndex, targetMessage] of targetMessages.entries()) {+ const targetText = getSmoothableText(targetMessage);+ if (targetText === null) {+ continue;+ }++ const displayedText = displayedTextByMessageId.get(targetMessage.id) ?? "";+ if (+ targetText.startsWith(displayedText) &&+ targetText.length > displayedText.length+ ) {+ return {+ targetIndex,+ targetMessage,+ targetText,+ displayedText,+ };+ }+ }++ return null;+}++function withTextContent(message: AgUiMessage, content: string) {+ if (message.role === "reasoning" || message.role === "assistant") {+ return { ...message, content };+ }++ throw new Error("Only assistant and reasoning messages can be smoothed");+}++const graphemeSegmenter =+ typeof Intl.Segmenter === "function"+ ? new Intl.Segmenter(undefined, { granularity: "grapheme" })+ : null;++function splitGraphemes(value: string) {+ if (!graphemeSegmenter) {+ return Array.from(value);+ }++ return Array.from(graphemeSegmenter.segment(value), ({ segment }) => segment);+}diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.ts b/web/src/ee/features/in-app-agent/components/utils/utils.tsindex 2aa5fbf38a..69c684687c 100644--- a/web/src/ee/features/in-app-agent/components/utils/utils.ts+++ b/web/src/ee/features/in-app-agent/components/utils/utils.ts@@ -198,11 +198,13 @@ export function getDrawerMessages({isRunning,messages,pendingToolApprovals = [],+ runningToolCallIds,}: {error: unknown;isRunning: boolean;messages: unknown;pendingToolApprovals?: readonly InAppAgentPendingToolApproval[];+ runningToolCallIds?: readonly string[];}): InAppAgentWindowMessage[] {const parsedMessages = z.array(InAppAiAgentMessageSchema).parse(messages);const toolResults = getToolResultsByToolCallId(parsedMessages);@@ -210,6 +212,9 @@ export function getDrawerMessages({const pendingApprovalsByToolCallId = new Map(pendingToolApprovals.map((approval) => [approval.id, approval]),);+ const runningToolCallIdSet = runningToolCallIds+ ? new Set(runningToolCallIds)+ : null;const mappedPendingApprovalIds = new Set<string>();const mappedMessages: InAppAgentWindowMessage[] = [];@@ -356,7 +361,11 @@ export function getDrawerMessages({resultState = "error";} else if (result?.content !== undefined) {resultState = "result";- } else if (isRunning && !error) {+ } else if (+ runningToolCallIdSet+ ? runningToolCallIdSet.has(toolCall.id)+ : isRunning && !error+ ) {resultState = "pending";} else {resultState = "incomplete";