AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
perf(frontend/copilot): keep the composer still while a reply streams (#15716)
Abhimanyu Yadav72a7214c1820
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex 8d1f5662c8..4ca05c3bce 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -9,7 +9,8 @@ import {import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { UIDataTypes, UIMessage, UITools } from "ai";import { LayoutGroup } from "framer-motion";-import { useCallback, useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";+import { useStableCallback } from "@/hooks/useStableCallback";import type { TurnStatsMap } from "../../helpers/convertChatSessionToUiMessages";import type { WorkspaceAttachment } from "../../helpers/workspaceAttachments";import type { PendingUploadSend } from "../../copilotStreamStore";@@ -264,9 +265,19 @@ export const ChatContainer = ({const initialMode = sessionId? sessionAutopilotMode: (expertIdentity?.autopilotMode ?? null);- const modeSelector = isAutoModeEnabled ? (- <AutopilotModeSelector sessionId={sessionId} persistedMode={initialMode} />- ) : undefined;+ // ChatInput is memoised, and this container renders on every streamed+ // flush: each element and callback it gets keeps its identity until its+ // own inputs change, so a flush leaves the composer alone.+ const modeSelector = useMemo(+ () =>+ isAutoModeEnabled ? (+ <AutopilotModeSelector+ sessionId={sessionId}+ persistedMode={initialMode}+ />+ ) : undefined,+ [isAutoModeEnabled, sessionId, initialMode],+ );const silenceTimeoutMs = useVoiceSilenceTimeout();const voice = useVoiceMode({enabled: isVoiceModeEnabled,@@ -278,6 +289,55 @@ export const ChatContainer = ({silenceTimeoutMs,onSend: guardedOnSend,});+ const toggleVoice = useStableCallback(voice.toggle);+ const retryVoiceUtterance = useStableCallback(voice.retryFailedUtterance);+ const downloadVoiceUtterance = useStableCallback(+ voice.downloadFailedUtterance,+ );+ const isVoiceModeDisabled =+ isInputDisabled || isSendLocked || voice.isStarting;+ const voiceMode = useMemo(+ () =>+ isVoiceModeEnabled+ ? { onStart: toggleVoice, disabled: isVoiceModeDisabled }+ : undefined,+ [isVoiceModeEnabled, toggleVoice, isVoiceModeDisabled],+ );+ const voiceBar = useMemo(+ () =>+ voice.isActive ? (+ <VoiceModeBar+ state={voice.state}+ statusLabel={voice.statusLabel}+ failure={voice.failure}+ onRetry={retryVoiceUtterance}+ onDownload={downloadVoiceUtterance}+ leaveButton={+ <VoiceModeButton+ isActive+ speaking={voice.state === "speaking"}+ onClick={toggleVoice}+ />+ }+ />+ ) : undefined,+ [+ voice.isActive,+ voice.state,+ voice.statusLabel,+ voice.failure,+ retryVoiceUtterance,+ downloadVoiceUtterance,+ toggleVoice,+ ],+ );+ const handleStop = useStableCallback(onStop);+ const handleEnqueue = useStableCallback((message: string) =>+ onEnqueue?.(message),+ );+ const handleDroppedFilesConsumed = useStableCallback(() =>+ onDroppedFilesConsumed?.(),+ );// Measure the usage-limit overlay so the messages scroll area can pad its// bottom — otherwise the last message would sit permanently behind the@@ -337,8 +397,9 @@ export const ChatContainer = ({}// Retry: re-send the last user message (used by ErrorCard on transient errors).+ // Stable, and reads `messages` when clicked rather than when created.const isRetryingRef = useRef(false);- const handleRetry = useCallback(async () => {+ const handleRetry = useStableCallback(async () => {if (isRetryingRef.current) return;isRetryingRef.current = true;try {@@ -387,7 +448,7 @@ export const ChatContainer = ({} finally {isRetryingRef.current = false;}- }, [guardedOnSend, messages]);+ });return (<CopilotChatActionsProvider@@ -480,7 +541,7 @@ export const ChatContainer = ({{isTaskBarEnabled && (<div className="relative z-10"><TaskProgressBar- todos={getLatestTaskList(messages) ?? []}+ todos={getLatestTaskList(messages)}isStreaming={isStreaming}/></div>@@ -511,48 +572,25 @@ export const ChatContainer = ({isStreaming={isStreaming}isTurnStarting={status === "submitted"}isUploadingFiles={isUploadingFiles}- onStop={onStop}- onEnqueue={onEnqueue}+ onStop={handleStop}+ onEnqueue={onEnqueue ? handleEnqueue : undefined}placeholder={(atReset && composer.placeholder) ||"What else can I help with?"}droppedFiles={droppedFiles}- onDroppedFilesConsumed={onDroppedFilesConsumed}+ onDroppedFilesConsumed={+ onDroppedFilesConsumed+ ? handleDroppedFilesConsumed+ : undefined+ }hasSession={!!sessionId}sessionId={sessionId}expertId={expertIdentity?.id ?? null}modeSelector={modeSelector}expertName={expertIdentity?.name ?? null}- voiceMode={- isVoiceModeEnabled- ? {- onStart: voice.toggle,- disabled:- isInputDisabled ||- isSendLocked ||- voice.isStarting,- }- : undefined- }- voiceBar={- voice.isActive ? (- <VoiceModeBar- state={voice.state}- statusLabel={voice.statusLabel}- failure={voice.failure}- onRetry={voice.retryFailedUtterance}- onDownload={voice.downloadFailedUtterance}- leaveButton={- <VoiceModeButton- isActive- speaking={voice.state === "speaking"}- onClick={voice.toggle}- />- }- />- ) : undefined- }+ voiceMode={voiceMode}+ voiceBar={voiceBar}/></div></TooltipTrigger>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/composer-renders.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/composer-renders.test.tsxnew file mode 100644index 0000000000..47169a5d99--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/composer-renders.test.tsx@@ -0,0 +1,205 @@+import React, { useState } from "react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import type { UIMessage } from "ai";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ChatContainer, type ChatContainerProps } from "../ChatContainer";++// Counts the composer's own renders: `useChatInput` runs once per ChatInput+// render, and the real ChatInput (with its memo boundary) stays in the tree.+const composerRenders = vi.hoisted(() => ({ count: 0 }));+vi.mock("../../ChatInput/useChatInput", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("../../ChatInput/useChatInput")>();+ return {+ ...actual,+ useChatInput(...args: Parameters<typeof actual.useChatInput>) {+ composerRenders.count += 1;+ return actual.useChatInput(...args);+ },+ };+});++const enabledFlags = vi.hoisted(() => new Set<string>());+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useGetFlag: (flag: string) => enabledFlags.has(flag),+ };+});++vi.mock("../../ChatMessagesContainer/ChatMessagesContainer", () => ({+ ChatMessagesContainer: ({ onRetry }: { onRetry?: () => void }) => (+ <button type="button" onClick={onRetry}>+ Retry message+ </button>+ ),+}));++vi.mock("../../UsageLimits/useIsUsageLimitReached", () => ({+ useIsUsageLimitReached: () => false,+}));++class MockResizeObserver {+ observe() {}+ disconnect() {}+ unobserve() {}+}++function textMessage(+ id: string,+ role: "user" | "assistant",+ text: string,+): UIMessage {+ return { id, role, parts: [{ type: "text", text }] } as UIMessage;+}++function streamedMessages(reply: string) {+ return [+ textMessage("u1", "user", "Plan my week"),+ textMessage("a1", "assistant", reply),+ ];+}++const baseProps: ChatContainerProps = {+ messages: streamedMessages("Here"),+ status: "streaming",+ error: undefined,+ sessionId: "session-123",+ isLoadingSession: false,+ isCreatingSession: false,+ onCreateSession: vi.fn(),+ onSend: vi.fn(),+ onStop: vi.fn(),+ onEnqueue: vi.fn(),+ droppedFiles: [],+ onDroppedFilesConsumed: vi.fn(),+};++// Updates go through state, not `rerender`, so the test providers above the+// container keep their values and only the container's props change.+let setProps: (update: Partial<ChatContainerProps>) => void = () => {};++function Harness(initial: Partial<ChatContainerProps>) {+ const [props, setState] = useState<ChatContainerProps>({+ ...baseProps,+ ...initial,+ });+ setProps = (update) => setState((prev) => ({ ...prev, ...update }));+ return <ChatContainer {...props} />;+}++function renderContainer(initial: Partial<ChatContainerProps> = {}) {+ render(<Harness {...initial} />);+ return composerRenders.count;+}++function update(props: Partial<ChatContainerProps>) {+ act(() => setProps(props));+}++describe("ChatContainer composer renders", () => {+ beforeEach(() => {+ composerRenders.count = 0;+ enabledFlags.clear();+ vi.stubGlobal("ResizeObserver", MockResizeObserver);+ });++ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ });++ it("does not render the composer for a streamed flush", () => {+ const before = renderContainer();++ update({ messages: streamedMessages("Here is") });+ update({ messages: streamedMessages("Here is the plan") });++ expect(composerRenders.count).toBe(before);+ });++ it("does not render the composer when the host passes new callbacks", () => {+ const before = renderContainer();++ // CopilotPage passes `() => setDroppedFiles([])` inline.+ update({+ messages: streamedMessages("Here is"),+ onStop: vi.fn(),+ onEnqueue: vi.fn(),+ onDroppedFilesConsumed: vi.fn(),+ });++ expect(composerRenders.count).toBe(before);+ });++ it("does not render the composer for a flush with voice and auto mode on", () => {+ enabledFlags.add("copilot-voice-mode");+ enabledFlags.add("copilot-auto-mode");+ const before = renderContainer();++ update({ messages: streamedMessages("Here is") });++ expect(composerRenders.count).toBe(before);+ });++ it("still renders the composer when the turn ends", () => {+ const before = renderContainer();+ expect(screen.getByRole("button", { name: /stop/i })).toBeDefined();++ update({ status: "ready" });++ expect(composerRenders.count).toBeGreaterThan(before);+ expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();+ });++ it("calls the latest onStop after the host replaced it", async () => {+ const firstStop = vi.fn();+ const latestStop = vi.fn();+ renderContainer({ onStop: firstStop });++ update({ onStop: latestStop });+ // Stop arms a second after it appears.+ const stop = screen.getByRole("button", { name: /stop/i });+ await waitFor(() => expect(stop).toHaveProperty("disabled", false), {+ timeout: 2_000,+ });+ fireEvent.click(stop);++ expect(latestStop).toHaveBeenCalledTimes(1);+ expect(firstStop).not.toHaveBeenCalled();+ });++ it("retries the latest user message, not the one from the first render", async () => {+ const onSend = vi.fn();+ renderContainer({ onSend, status: "ready" });++ update({+ messages: [+ ...streamedMessages("Here is the plan"),+ textMessage("u2", "user", "Now the budget"),+ ],+ });+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Retry message" }));+ });++ expect(onSend).toHaveBeenCalledWith(+ "Now the budget",+ undefined,+ undefined,+ undefined,+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsxindex d0af13f44e..60fac3d66f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx@@ -13,6 +13,7 @@ import {ClipboardEvent,KeyboardEvent,ReactNode,+ memo,useEffect,useState,} from "react";@@ -134,7 +135,9 @@ interface Props {atReset?: { onSchedule: (message: string) => Promise<void> };}-export function ChatInput({+// Memoised: the chat page re-renders on every streamed flush, and the+// composer's props stay the same while the reply streams in.+export const ChatInput = memo(function ChatInput({onSend,disabled = false,sendDisabled = false,@@ -666,7 +669,7 @@ export function ChatInput({)}</form>);-}+});function toLocalAttachment(file: File): Attachment {return { kind: "local", file };diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/TailSpacer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/TailSpacer.tsxindex 8c996b8167..a5ab76f5a0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/TailSpacer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/TailSpacer.tsx@@ -1,6 +1,6 @@"use client";-import { useLayoutEffect, useRef, useState } from "react";+import { memo, useLayoutEffect, useRef, useState } from "react";import { useStickToBottomContext } from "use-stick-to-bottom";interface Props {@@ -21,10 +21,22 @@ const TAIL_VIEWPORT_RATIO = 0.5;* the user's message around the middle of the viewport, leaving the lower* half of the screen for the reply. Collapses to zero once the reply is tall* enough to fill that space, handing scrolling back to StickToBottom. */-export function TailSpacer({ messageID, bottomInset }: Props) {+export const TailSpacer = memo(function TailSpacer({+ messageID,+ bottomInset,+}: Props) {const { scrollRef } = useStickToBottomContext();const spacerRef = useRef<HTMLDivElement>(null);const [height, setHeight] = useState(0);+ // The observer fires on every resize of the transcript; only a new height+ // is worth a render.+ const heightRef = useRef(0);++ function applyHeight(next: number) {+ if (next === heightRef.current) return;+ heightRef.current = next;+ setHeight(next);+ }useLayoutEffect(() => {const scroller = scrollRef.current;@@ -33,14 +45,14 @@ export function TailSpacer({ messageID, bottomInset }: Props) {// the element whose growth we care about.const content = spacer?.parentElement;if (!scroller || !content || !spacer || !messageID) {- setHeight(0);+ applyHeight(0);return;}const message = content.querySelector(`[data-message-id="${CSS.escape(messageID)}"]`,);if (!(message instanceof HTMLElement)) {- setHeight(0);+ applyHeight(0);return;}@@ -52,7 +64,7 @@ export function TailSpacer({ messageID, bottomInset }: Props) {spacer.getBoundingClientRect().top -message.getBoundingClientRect().top;const viewport = scroller.clientHeight - bottomInset - TAIL_GAP;- setHeight(Math.max(0, viewport * TAIL_VIEWPORT_RATIO - turnHeight));+ applyHeight(Math.max(0, viewport * TAIL_VIEWPORT_RATIO - turnHeight));}measure();@@ -67,4 +79,4 @@ export function TailSpacer({ messageID, bottomInset }: Props) {return (<div ref={spacerRef} aria-hidden className="-mt-6" style={{ height }} />);-}+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/TailSpacer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/TailSpacer.test.tsxnew file mode 100644index 0000000000..887fd5b4ef--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/TailSpacer.test.tsx@@ -0,0 +1,103 @@+import { act, cleanup, render } from "@/tests/integrations/test-utils";+import { useState } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TailSpacer } from "../TailSpacer";++const scroller = { clientHeight: 900 };+// The spacer calls the context once per render.+const spacerRenders = vi.hoisted(() => ({ count: 0 }));+vi.mock("use-stick-to-bottom", () => ({+ useStickToBottomContext: () => {+ spacerRenders.count += 1;+ return { scrollRef: { current: scroller } };+ },+}));++let resize: () => void = () => {};+class MockResizeObserver {+ constructor(callback: () => void) {+ resize = callback;+ }+ observe() {}+ disconnect() {}+ unobserve() {}+}++// Where the newest turn starts and where the spacer sits below it.+const layout = { messageTop: 0, spacerTop: 100 };++function rect(top: number) {+ return { top } as DOMRect;+}++let rerenderParent: () => void = () => {};++function Transcript() {+ const [, setTick] = useState(0);+ rerenderParent = () => setTick((tick) => tick + 1);+ return (+ <div>+ <div data-message-id="u1" ref={stubTop(() => layout.messageTop)} />+ <TailSpacer messageID="u1" bottomInset={0} />+ </div>+ );+}++function stubTop(top: () => number) {+ return (el: HTMLElement | null) => {+ if (el) el.getBoundingClientRect = () => rect(top());+ };+}++function renderTranscript() {+ const { container } = render(<Transcript />);+ const spacer = container.querySelector<HTMLElement>("[aria-hidden]")!;+ spacer.getBoundingClientRect = () => rect(layout.spacerTop);+ // The stub lands after the first measure, so measure again with it.+ act(() => resize());+ return spacer;+}++describe("TailSpacer", () => {+ beforeEach(() => {+ spacerRenders.count = 0;+ layout.messageTop = 0;+ layout.spacerTop = 100;+ vi.stubGlobal("ResizeObserver", MockResizeObserver);+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("parks a short turn mid-screen and collapses once the reply fills it", () => {+ const spacer = renderTranscript();+ // (900 - 24) * 0.5 - 100+ expect(spacer.style.height).toBe("338px");++ layout.spacerTop = 600;+ act(() => resize());++ expect(spacer.style.height).toBe("0px");+ });++ it("does not render when its parent renders with the same props", () => {+ renderTranscript();+ const before = spacerRenders.count;++ act(() => rerenderParent());++ expect(spacerRenders.count).toBe(before);+ });++ it("does not render for a resize that leaves its height unchanged", () => {+ renderTranscript();+ const before = spacerRenders.count;++ act(() => resize());+ act(() => resize());++ expect(spacerRenders.count).toBe(before);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsxindex 78831ab92b..28880189e5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx@@ -3,8 +3,13 @@import { cn } from "@/lib/utils";import type { UIDataTypes, UIMessage, UITools } from "ai";import { motion, useReducedMotion } from "framer-motion";-import { useMemo, useState } from "react";-import { tickColor, tickScale, toMinimapEntries } from "./helpers";+import { memo, useMemo, useState } from "react";+import {+ haveSameMinimapRows,+ tickColor,+ tickScale,+ toMinimapEntries,+} from "./helpers";import { isKey } from "@/lib/keyboard";const TICK_SPRING = { type: "spring", stiffness: 200, damping: 15 } as const;@@ -20,7 +25,7 @@ interface Props {* one reveals that turn's opening line, and clicking scrolls the transcript to* it, so a long thread stays navigable without dragging the scrollbar.*/-export function ChatMinimap({ messages }: Props) {+export const ChatMinimap = memo(function ChatMinimap({ messages }: Props) {const [hovered, setHovered] = useState<number | null>(null);const reducedMotion = useReducedMotion();const entries = useMemo(() => toMinimapEntries(messages), [messages]);@@ -91,6 +96,10 @@ export function ChatMinimap({ messages }: Props) {</div></div>);+}, areSameMinimapProps);++function areSameMinimapProps(prev: Props, next: Props) {+ return haveSameMinimapRows(prev.messages, next.messages);}function scrollToMessage(id: string) {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsxindex 796c74b256..de5f71c87e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsx@@ -1,9 +1,27 @@import { fireEvent, render, screen } from "@/tests/integrations/test-utils";import type { UIMessage } from "ai";import { describe, expect, it, vi } from "vitest";-import { tickColor, tickScale, toMinimapEntries } from "../helpers";+import {+ haveSameMinimapRows,+ tickColor,+ tickScale,+ toMinimapEntries,+} from "../helpers";import { ChatMinimap } from "../ChatMinimap";+// The rail calls useReducedMotion once per render.+const railRenders = vi.hoisted(() => ({ count: 0 }));+vi.mock("framer-motion", async (importOriginal) => {+ const actual = await importOriginal<typeof import("framer-motion")>();+ return {+ ...actual,+ useReducedMotion: () => {+ railRenders.count += 1;+ return actual.useReducedMotion();+ },+ };+});+function textMessage(id: string, role: "user" | "assistant", text: string) {return {id,@@ -66,7 +84,83 @@ describe("ChatMinimap", () => {});});+describe("ChatMinimap renders", () => {+ it("skips a streamed flush that only grows the reply", () => {+ const { rerender } = render(<ChatMinimap messages={MESSAGES} />);+ const before = railRenders.count;++ rerender(+ <ChatMinimap+ messages={[+ ...MESSAGES.map((message) => ({ ...message })),+ textMessage("m6", "assistant", "Travel booked"),+ ]}+ />,+ );++ expect(railRenders.count).toBe(before);+ });++ it("adds a tick for a new user message", () => {+ const { rerender } = render(<ChatMinimap messages={MESSAGES} />);++ rerender(+ <ChatMinimap+ messages={[...MESSAGES, textMessage("m6", "user", "Book hotels")]}+ />,+ );++ expect(screen.getAllByRole("button")).toHaveLength(4);+ expect(screen.getByLabelText("Jump to: Book hotels")).toBeDefined();+ });++ it("relabels a tick whose message text changed under the same id", () => {+ const { rerender } = render(<ChatMinimap messages={MESSAGES} />);++ rerender(+ <ChatMinimap+ messages={[+ ...MESSAGES.slice(0, 4),+ textMessage("m5", "user", "And hotels"),+ ]}+ />,+ );++ expect(screen.getByLabelText("Jump to: And hotels")).toBeDefined();+ expect(screen.queryByLabelText("Jump to: And travel")).toBeNull();+ });+});+describe("minimap helpers", () => {+ it("compares the user turns, not the array", () => {+ const copy = MESSAGES.map((message) => ({ ...message }));+ expect(haveSameMinimapRows(MESSAGES, copy)).toBe(true);+ expect(+ haveSameMinimapRows(MESSAGES, [+ ...copy,+ textMessage("m6", "assistant", "More reply"),+ ]),+ ).toBe(true);+ expect(+ haveSameMinimapRows(MESSAGES, [+ ...copy,+ textMessage("m6", "user", "Another ask"),+ ]),+ ).toBe(false);+ expect(+ haveSameMinimapRows(MESSAGES, [+ ...copy.slice(0, 4),+ textMessage("m5", "user", "Edited"),+ ]),+ ).toBe(false);+ expect(+ haveSameMinimapRows(MESSAGES, [+ ...copy.slice(0, 4),+ textMessage("m9", "user", "And travel"),+ ]),+ ).toBe(false);+ });+it("drops assistant turns and labels text-free user messages", () => {const entries = toMinimapEntries([{ id: "t1", role: "assistant", parts: [] } as unknown as UIMessage,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.tsindex a0850684ff..81f00aadc8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.ts@@ -16,16 +16,40 @@ const BODY_CHARS = 220;export function toMinimapEntries(messages: UIMessage<unknown, UIDataTypes, UITools>[],): MinimapEntry[] {- return messages- .filter((message) => message.role === "user" && !isHeldCallRow(message))- .map((message) => {- const [title, body] = splitPreview(messageText(message));- return {- id: message.id,- title: title || "Your message",- body,- };- });+ return messages.filter(isMinimapRow).map((message) => {+ const [title, body] = splitPreview(messageText(message));+ return {+ id: message.id,+ title: title || "Your message",+ body,+ };+ });+}++/** True when both lists hold the same ticks: the same user messages, by id+ * and text, in the same order. A streamed flush only grows the reply, so the+ * rail need not render for it. */+export function haveSameMinimapRows(+ a: UIMessage<unknown, UIDataTypes, UITools>[],+ b: UIMessage<unknown, UIDataTypes, UITools>[],+): boolean {+ if (a === b) return true;+ const left = a.filter(isMinimapRow);+ const right = b.filter(isMinimapRow);+ if (left.length !== right.length) return false;+ return left.every((message, i) => {+ const other = right[i];+ return (+ message === other ||+ (message.id === other.id && messageText(message) === messageText(other))+ );+ });+}++function isMinimapRow(+ message: UIMessage<unknown, UIDataTypes, UITools>,+): boolean {+ return message.role === "user" && !isHeldCallRow(message);}function messageText(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/TaskProgressBar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/TaskProgressBar.tsxindex e16c2e6433..2885f1776f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/TaskProgressBar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/TaskProgressBar.tsx@@ -2,13 +2,14 @@import { Text } from "@/components/atoms/Text/Text";import { AnimatePresence, motion, useReducedMotion } from "framer-motion";-import { useState } from "react";+import { memo, useState } from "react";import { EASE_OUT } from "./animations";import { StatusIcon } from "./components/StatusIcon/StatusIcon";import { TaskRow } from "./components/TaskRow/TaskRow";import {getCurrentLabel,getCurrentTask,+ haveSameTodos,isAllComplete,toDisplayStatus,type TodoItem,@@ -49,7 +50,9 @@ interface Props {defaultExpanded?: boolean;}-export function TaskProgressBar({+// The chat derives `todos` afresh on every streamed flush; the bar only+// renders again when the tasks themselves change.+export const TaskProgressBar = memo(function TaskProgressBar({todos,isStreaming = false,defaultExpanded = false,@@ -166,4 +169,12 @@ export function TaskProgressBar({</AnimatePresence></div>);+}, areSameTaskBarProps);++function areSameTaskBarProps(prev: Props, next: Props) {+ return (+ prev.isStreaming === next.isStreaming &&+ prev.defaultExpanded === next.defaultExpanded &&+ haveSameTodos(prev.todos, next.todos)+ );}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/TaskProgressBar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/TaskProgressBar.test.tsxindex 9b861430e7..badd851d79 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/TaskProgressBar.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/TaskProgressBar.test.tsx@@ -7,7 +7,10 @@ import {} from "@/tests/integrations/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import { TaskProgressBar } from "../TaskProgressBar";-import type { TodoItem } from "../helpers";+import { EMPTY_TODOS, type TodoItem } from "../helpers";++// The bar calls useReducedMotion once per render.+const barRenders = vi.hoisted(() => ({ count: 0 }));vi.mock("framer-motion", () => {const MOTION_PROPS = [@@ -39,7 +42,10 @@ vi.mock("framer-motion", () => {AnimatePresence: ({ children }: { children: React.ReactNode }) => (<>{children}</>),- useReducedMotion: () => false,+ useReducedMotion: () => {+ barRenders.count += 1;+ return false;+ },motion: {div: makeMotion("div"),span: makeMotion("span"),@@ -128,4 +134,64 @@ describe("TaskProgressBar", () => {);expect(screen.getAllByLabelText("in progress").length).toBeGreaterThan(0);});++ it("skips a render when the chat passes an equal task list again", () => {+ const { rerender } = render(+ <TaskProgressBar+ todos={[todo("Step 1", "completed"), todo("Step 2", "in_progress")]}+ isStreaming+ />,+ );+ const before = barRenders.count;++ rerender(+ <TaskProgressBar+ todos={[todo("Step 1", "completed"), todo("Step 2", "in_progress")]}+ isStreaming+ />,+ );++ expect(barRenders.count).toBe(before);+ });++ it("skips a render while there is still no task list", () => {+ const { rerender } = render(+ <TaskProgressBar todos={EMPTY_TODOS} isStreaming />,+ );+ const before = barRenders.count;++ rerender(<TaskProgressBar todos={EMPTY_TODOS} isStreaming />);++ expect(barRenders.count).toBe(before);+ });++ it("renders again when a task changes state", () => {+ const { rerender } = render(+ <TaskProgressBar+ todos={[todo("Step 1", "in_progress", "Doing step 1")]}+ isStreaming+ />,+ );+ expect(screen.getByText("Doing step 1")).toBeDefined();++ rerender(+ <TaskProgressBar todos={[todo("Step 1", "completed")]} isStreaming />,+ );++ expect(screen.getByText("All tasks complete")).toBeDefined();+ });++ it("renders again when the reply stops streaming", () => {+ const todos = [todo("Halted step", "in_progress", "Running step")];+ const { rerender } = render(+ <TaskProgressBar todos={todos} isStreaming defaultExpanded />,+ );+ expect(screen.getAllByLabelText("in progress").length).toBeGreaterThan(0);++ rerender(+ <TaskProgressBar todos={todos} isStreaming={false} defaultExpanded />,+ );++ expect(screen.getAllByLabelText("stopped").length).toBeGreaterThan(0);+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/helpers.test.tsindex 79f4fe1045..c57c3f7821 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/__tests__/helpers.test.ts@@ -1,10 +1,12 @@import type { UIMessage } from "ai";import { describe, expect, it } from "vitest";import {+ EMPTY_TODOS,countCompleted,getCurrentLabel,getCurrentTask,getLatestTaskList,+ haveSameTodos,isAllComplete,type TodoItem,} from "../helpers";@@ -26,11 +28,25 @@ function messageWithTodoWrite(todos: unknown, state?: string): UIMessage {}describe("getLatestTaskList", () => {- it("returns null when there are no TodoWrite parts", () => {+ it("returns the shared empty list when there are no TodoWrite parts", () => {const messages = [{ id: "m1", role: "assistant", parts: [{ type: "text", text: "hi" }] },] as unknown as UIMessage[];- expect(getLatestTaskList(messages)).toBeNull();+ expect(getLatestTaskList(messages)).toBe(EMPTY_TODOS);+ expect(getLatestTaskList([])).toBe(EMPTY_TODOS);+ expect(EMPTY_TODOS).toHaveLength(0);+ });++ it("keeps finding an earlier turn's list when the newest turn has none", () => {+ const messages = [+ messageWithTodoWrite([todo("Earlier plan", "in_progress")]),+ {+ id: "m2",+ role: "assistant",+ parts: [{ type: "text", text: "no tasks here" }],+ } as unknown as UIMessage,+ ];+ expect(getLatestTaskList(messages)[0].content).toBe("Earlier plan");});it("returns the todos from the most recent TodoWrite part", () => {@@ -69,8 +85,34 @@ describe("getLatestTaskList", () => {expect(result?.[0].content).toBe("Valid");});- it("returns null when todos is not an array", () => {- expect(getLatestTaskList([messageWithTodoWrite({})])).toBeNull();+ it("returns the shared empty list when todos is not an array", () => {+ expect(getLatestTaskList([messageWithTodoWrite({})])).toBe(EMPTY_TODOS);+ });+});++describe("haveSameTodos", () => {+ it("matches lists with the same tasks in the same states", () => {+ expect(+ haveSameTodos(+ [todo("a", "completed"), todo("b", "in_progress", "Doing b")],+ [todo("a", "completed"), todo("b", "in_progress", "Doing b")],+ ),+ ).toBe(true);+ });++ it("tells apart a changed status, label, order or length", () => {+ const base = [todo("a", "completed"), todo("b", "in_progress")];+ expect(+ haveSameTodos(base, [todo("a", "completed"), todo("b", "completed")]),+ ).toBe(false);+ expect(+ haveSameTodos(base, [+ todo("a", "completed"),+ todo("b", "in_progress", "Doing b"),+ ]),+ ).toBe(false);+ expect(haveSameTodos(base, [...base].reverse())).toBe(false);+ expect(haveSameTodos(base, base.slice(0, 1))).toBe(false);});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/helpers.tsindex 2042e6c456..eb99e3e19c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TaskProgressBar/helpers.ts@@ -6,6 +6,10 @@ export interface TodoItem {activeForm?: string;}+// Shared by every chat with no task list, so the bar's props keep their+// identity from one streamed flush to the next.+export const EMPTY_TODOS: TodoItem[] = [];+function isTodoItem(value: unknown): value is TodoItem {if (!value || typeof value !== "object") return false;const v = value as Record<string, unknown>;@@ -18,8 +22,8 @@ function isTodoItem(value: unknown): value is TodoItem {}// Walks the message history backwards for the most recent TodoWrite tool call-// and returns its task list (the copilot's live plan).-export function getLatestTaskList(messages: UIMessage[]): TodoItem[] | null {+// and returns its task list (the copilot's live plan), or EMPTY_TODOS.+export function getLatestTaskList(messages: UIMessage[]): TodoItem[] {for (let i = messages.length - 1; i >= 0; i--) {const parts = messages[i]?.parts;if (!parts) continue;@@ -44,7 +48,21 @@ export function getLatestTaskList(messages: UIMessage[]): TodoItem[] | null {if (filtered.length > 0) return filtered;}}- return null;+ return EMPTY_TODOS;+}++// Same tasks in the same order and states: the bar would draw the same thing.+export function haveSameTodos(a: TodoItem[], b: TodoItem[]): boolean {+ if (a === b) return true;+ if (!a || !b || a.length !== b.length) return false;+ return a.every((todo, i) => {+ const other = b[i];+ return (+ todo.content === other.content &&+ todo.status === other.status &&+ todo.activeForm === other.activeForm+ );+ });}export function countCompleted(todos: TodoItem[]): number {