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/library): re-render only the new row when a run is added (#15713)
Abhimanyu Yadav160a72eccb64
diff --git a/autogpt_platform/frontend/scripts/perf/__tests__/routes.test.ts b/autogpt_platform/frontend/scripts/perf/__tests__/routes.test.tsindex 8853df2e3b..fe88c1c029 100644--- a/autogpt_platform/frontend/scripts/perf/__tests__/routes.test.ts+++ b/autogpt_platform/frontend/scripts/perf/__tests__/routes.test.ts@@ -13,6 +13,10 @@ const all: RouteHandlers = {graph: handler,libraryAgents: handler,executions: handler,+ libraryAgent: handler,+ graphExecutions: handler,+ graphSchedules: handler,+ libraryPresets: handler,};function nameOf(url: string, handlers: RouteHandlers = all) {@@ -45,6 +49,20 @@ describe("matchRoute", () => {expect(nameOf(`${base}?version=1`)).toBe("graph");});+ it("tells a workflow's runs, schedules and presets apart from one run", () => {+ const base = "http://localhost:3000/api/proxy/api";+ expect(nameOf(`${base}/graphs/g1/executions?page=1&page_size=20`)).toBe(+ "graphExecutions",+ );+ expect(nameOf(`${base}/graphs/g1/executions/e1`)).toBe("graphExecution");+ expect(nameOf(`${base}/graphs/g1/schedules`)).toBe("graphSchedules");+ expect(nameOf(`${base}/library/presets?graph_id=g1`)).toBe(+ "libraryPresets",+ );+ expect(nameOf(`${base}/library/agents/a1`)).toBe("libraryAgent");+ expect(nameOf(`${base}/library/agents?page_size=20`)).toBe("libraryAgents");+ });+it("leaves pages, other endpoints and unhandled routes alone", () => {expect(nameOf("http://localhost:3000/home?sessionId=s1")).toBeNull();expect(diff --git a/autogpt_platform/frontend/scripts/perf/lib/library-agent-fixture.ts b/autogpt_platform/frontend/scripts/perf/lib/library-agent-fixture.tsnew file mode 100644index 0000000000..32231b40b5--- /dev/null+++ b/autogpt_platform/frontend/scripts/perf/lib/library-agent-fixture.ts@@ -0,0 +1,126 @@+import { buildLibraryAgents } from "./library-fixture";+import { fulfillJSON, type RouteHandlers } from "./routes";++const RUN_COUNT = 20;+const PAGE_SIZE = 20;+const FIRST_STARTED_AT = Date.parse("2026-01-05T09:00:00.000Z");++function runID(index: number) {+ return `00000000-0000-4000-c300-${String(index).padStart(12, "0")}`;+}++type Agent = ReturnType<typeof buildLibraryAgents>[number];++function buildRun(+ agent: Agent,+ userID: string,+ index: number,+ running = false,+) {+ const startedAt = FIRST_STARTED_AT + index * 60_000;+ return {+ id: runID(index),+ user_id: userID,+ graph_id: agent.graph_id,+ graph_version: agent.graph_version,+ inputs: {},+ credential_inputs: {},+ nodes_input_masks: null,+ preset_id: null,+ status: running ? "RUNNING" : "COMPLETED",+ started_at: new Date(startedAt).toISOString(),+ ended_at: running ? null : new Date(startedAt + 30_000).toISOString(),+ is_shared: false,+ share_token: null,+ is_dry_run: false,+ stats: { node_exec_count: 4, node_error_count: 0, cost: 0, duration: 30 },+ };+}++export type LibraryAgentRun = ReturnType<typeof buildRun>;++/**+ * One workflow with 20 runs, newest first. The newest is RUNNING, so its+ * detail view polls; each poll answers with one more finished node, as a run+ * that makes progress would. `addRun()` puts a new RUNNING run at the top of+ * the list, as starting a task does.+ */+export function createLibraryAgentFixture(userID: string) {+ const [agent] = buildLibraryAgents(1);+ let nextIndex = RUN_COUNT;+ const runs: LibraryAgentRun[] = Array.from(+ { length: RUN_COUNT },+ (_, index) => buildRun(agent, userID, index, index === RUN_COUNT - 1),+ ).reverse();+ const selectedRun = runs[0];+ const stats = { detailRequests: 0, listRequests: 0 };++ function addRun() {+ const run = buildRun(agent, userID, nextIndex, true);+ nextIndex += 1;+ runs.unshift(run);+ return run;+ }++ const handlers: RouteHandlers = {+ libraryAgent: async (route, match) => {+ if (match[1] !== agent.id || route.request().method() !== "GET") {+ return route.fallback();+ }+ await fulfillJSON(route, agent);+ },+ graphExecutions: async (route, match) => {+ if (match[1] !== agent.graph_id || route.request().method() !== "GET") {+ return route.fallback();+ }+ stats.listRequests += 1;+ const params = new URL(route.request().url()).searchParams;+ const page = Number(params.get("page") ?? 1);+ const pageSize = Number(params.get("page_size") ?? PAGE_SIZE);+ await fulfillJSON(route, {+ executions: runs.slice((page - 1) * pageSize, page * pageSize),+ pagination: {+ total_items: runs.length,+ total_pages: Math.ceil(runs.length / pageSize),+ current_page: page,+ page_size: pageSize,+ },+ });+ },+ graphExecution: async (route, match) => {+ if (match[1] !== agent.graph_id || match[2] !== selectedRun.id) {+ return route.fallback();+ }+ stats.detailRequests += 1;+ await fulfillJSON(route, {+ ...selectedRun,+ stats: {+ ...selectedRun.stats,+ node_exec_count:+ selectedRun.stats.node_exec_count + stats.detailRequests,+ },+ outputs: {},+ node_executions: [],+ });+ },+ graphSchedules: async (route, match) => {+ if (match[1] !== agent.graph_id || route.request().method() !== "GET") {+ return route.fallback();+ }+ await fulfillJSON(route, []);+ },+ libraryPresets: async (route) => {+ if (route.request().method() !== "GET") return route.fallback();+ await fulfillJSON(route, {+ presets: [],+ pagination: {+ total_items: 0,+ total_pages: 0,+ current_page: 1,+ page_size: 100,+ },+ });+ },+ };+ return { handlers, agent, runs, selectedRun, stats, addRun };+}diff --git a/autogpt_platform/frontend/scripts/perf/lib/routes.ts b/autogpt_platform/frontend/scripts/perf/lib/routes.tsindex 8644bd072d..f146f75c84 100644--- a/autogpt_platform/frontend/scripts/perf/lib/routes.ts+++ b/autogpt_platform/frontend/scripts/perf/lib/routes.ts@@ -23,6 +23,10 @@ const ROUTE_TABLE = [["graph", /^\/api\/proxy\/api\/graphs\/([^/]+)$/],["libraryAgents", /^\/api\/proxy\/api\/library\/agents$/],["executions", /^\/api\/proxy\/api\/executions$/],+ ["libraryAgent", /^\/api\/proxy\/api\/library\/agents\/([^/]+)$/],+ ["graphExecutions", /^\/api\/proxy\/api\/graphs\/([^/]+)\/executions$/],+ ["graphSchedules", /^\/api\/proxy\/api\/graphs\/([^/]+)\/schedules$/],+ ["libraryPresets", /^\/api\/proxy\/api\/library\/presets$/],] as const;export type RouteName = (typeof ROUTE_TABLE)[number][0];diff --git a/autogpt_platform/frontend/scripts/perf/scenarios/library-agent-runs.ts b/autogpt_platform/frontend/scripts/perf/scenarios/library-agent-runs.tsnew file mode 100644index 0000000000..273f9a3f6e--- /dev/null+++ b/autogpt_platform/frontend/scripts/perf/scenarios/library-agent-runs.ts@@ -0,0 +1,112 @@+import type { Page, WebSocketRoute } from "@playwright/test";+import {+ createLibraryAgentFixture,+ type LibraryAgentRun,+} from "../lib/library-agent-fixture";+import { installRoutes } from "../lib/routes";+import { settle, type Scenario } from "../lib/scenario";++const READY_TIMEOUT_MS = 60_000;+const SUBSCRIBE_TIMEOUT_MS = 15_000;+const NEW_RUNS = 3;+// Longer than the 2 s execution-event throttle, so every event refetches.+const NEW_RUN_INTERVAL_MS = 2_500;++/**+ * Stands in for the websocket server: acknowledges every subscription and+ * lets the scenario push `graph_execution_event`s at the page.+ */+async function mockExecutionSocket(page: Page) {+ const sockets = new Set<WebSocketRoute>();+ const subscribedGraphIDs = new Set<string>();+ await page.routeWebSocket(/\/ws(\?|$)/, (ws) => {+ sockets.add(ws);+ ws.onClose(() => sockets.delete(ws));+ ws.onMessage((raw) => {+ const message = JSON.parse(String(raw));+ if (message.method === "heartbeat") {+ ws.send(JSON.stringify({ method: "heartbeat", data: "pong" }));+ return;+ }+ if (message.method === "subscribe_graph_executions") {+ subscribedGraphIDs.add(String(message.data?.graph_id));+ }+ ws.send(+ JSON.stringify({+ method: message.method,+ success: true,+ channel: message.data?.graph_id ?? "",+ }),+ );+ });+ });+ function push(run: LibraryAgentRun) {+ const frame = JSON.stringify({+ method: "graph_execution_event",+ success: true,+ data: { ...run, outputs: {}, event_type: "graph_exec_update" },+ });+ for (const ws of sockets) ws.send(frame);+ }+ async function waitForSubscription(graphID: string) {+ const deadline = Date.now() + SUBSCRIBE_TIMEOUT_MS;+ while (!subscribedGraphIDs.has(graphID)) {+ if (Date.now() > deadline) {+ throw new Error(+ `The page never subscribed to ${graphID}; events would reach no one.`,+ );+ }+ await page.waitForTimeout(100);+ }+ }+ return { push, waitForSubscription };+}++export const libraryAgentRuns: Scenario = {+ name: "library-agent-runs",+ description:+ "A workflow's page with 20 runs, the newest RUNNING and selected (it polls every 1.5 s): 3 new runs arrive at the top, 2.5 s apart.",+ readyWhen:+ "the selected run's detail and the 20th run are on screen, network idle + 1 s, and the socket has a subscription for the workflow",+ windowMs: 1_000,+ async setup(ctx) {+ const { page } = ctx;+ const fixture = createLibraryAgentFixture(ctx.userID);+ const socket = await mockExecutionSocket(page);+ await installRoutes(page, fixture.handlers);+ // With both params already in the URL the page does not rewrite it on+ // load, which would otherwise hold back the websocket token action.+ await page.goto(+ `/library/agents/${fixture.agent.id}?activeTab=runs&activeItem=${fixture.selectedRun.id}`,+ );+ const lastRun = fixture.runs[fixture.runs.length - 1];+ await page+ .getByTestId(`library-run-item-${lastRun.id}`)+ .waitFor({ state: "visible", timeout: READY_TIMEOUT_MS });+ await page+ .getByRole("button", { name: "Output" })+ .first()+ .waitFor({ state: "visible", timeout: READY_TIMEOUT_MS });+ await settle(page);+ await socket.waitForSubscription(fixture.agent.graph_id);+ return {+ async run() {+ const detailStart = fixture.stats.detailRequests;+ const listStart = fixture.stats.listRequests;+ for (let index = 0; index < NEW_RUNS; index += 1) {+ const run = fixture.addRun();+ socket.push(run);+ await page+ .getByTestId(`library-run-item-${run.id}`)+ .waitFor({ state: "visible", timeout: READY_TIMEOUT_MS });+ await page.waitForTimeout(NEW_RUN_INTERVAL_MS);+ }+ console.log(+ `[library-agent-runs] ${NEW_RUNS} new runs: ` ++ `${fixture.stats.detailRequests - detailStart} run-detail GETs, ` ++ `${fixture.stats.listRequests - listStart} run-list GETs`,+ );+ },+ };+ },+};diff --git a/autogpt_platform/frontend/scripts/perf/scenarios/registry.ts b/autogpt_platform/frontend/scripts/perf/scenarios/registry.tsindex 573658d09f..dc49e348e5 100644--- a/autogpt_platform/frontend/scripts/perf/scenarios/registry.ts+++ b/autogpt_platform/frontend/scripts/perf/scenarios/registry.ts@@ -11,6 +11,7 @@ import { copilotStreamReply } from "./copilot-stream-reply";import { copilotSwitchThreads } from "./copilot-switch-threads";import { copilotToolWait } from "./copilot-tool-wait";import { copilotType } from "./copilot-type";+import { libraryAgentRuns } from "./library-agent-runs";import { libraryRunning } from "./library-running";import { libraryRunningEvents } from "./library-running-events";@@ -29,6 +30,7 @@ export const SCENARIOS: Scenario[] = [copilotToolWait,copilotResizeDrag,builderRunBeads,+ libraryAgentRuns,];export function findScenario(name: string) {diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/runs-list-prepend.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/runs-list-prepend.test.tsxnew file mode 100644index 0000000000..7ae150af41--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/runs-list-prepend.test.tsx@@ -0,0 +1,215 @@+import { getGetV1ListGraphExecutionsQueryKey } from "@/app/api/__generated__/endpoints/graphs/graphs";+import { getGetV1ListGraphExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import { getGetV2GetLibraryAgentResponseMock } from "@/app/api/__generated__/endpoints/library/library.msw";+import { getGetV2ListPresetsMockHandler } from "@/app/api/__generated__/endpoints/presets/presets.msw";+import { getGetV1ListExecutionSchedulesForAGraphMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import type { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";+import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";+import { server } from "@/mocks/mock-server";+import { act, render, screen } from "@/tests/integrations/test-utils";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import userEvent from "@testing-library/user-event";+import { NuqsTestingAdapter } from "nuqs/adapters/testing";+import { ReactNode } from "react";+import { beforeEach, expect, test, vi } from "vitest";+import { SidebarRunsList } from "../components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList";++const GRAPH_ID = "graph-1";++const renderedRunIDs = vi.hoisted(() => [] as string[]);++vi.mock(+ "../components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem")+ >();+ function CountedTaskListItem(+ props: Parameters<typeof actual.TaskListItem>[0],+ ) {+ renderedRunIDs.push(props.run.id);+ return <actual.TaskListItem {...props} />;+ }+ return { TaskListItem: CountedTaskListItem };+ },+);++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >()),+ useGetFlag: () => false,+ useFlagStatus: () => ({ enabled: false, ready: true }),+}));++function makeRun(id: string): GraphExecutionMeta {+ return {+ id,+ user_id: "user-1",+ graph_id: GRAPH_ID,+ graph_version: 1,+ inputs: {},+ credential_inputs: {},+ nodes_input_masks: {},+ preset_id: null,+ status: AgentExecutionStatus.COMPLETED,+ started_at: new Date("2026-01-05T09:00:00Z"),+ ended_at: new Date("2026-01-05T09:00:30Z"),+ stats: { node_exec_count: 2, node_error_count: 0 },+ };+}++function page(executions: GraphExecutionMeta[]) {+ return {+ executions,+ pagination: {+ total_items: executions.length,+ total_pages: 1,+ current_page: 1,+ page_size: 20,+ },+ };+}++const agent = getGetV2GetLibraryAgentResponseMock({+ id: "library-agent",+ graph_id: GRAPH_ID,+ name: "Prepend workflow",+});++let listedRuns: GraphExecutionMeta[] = [];++beforeEach(() => {+ renderedRunIDs.length = 0;+ listedRuns = [makeRun("run-a"), makeRun("run-b")];+ server.use(+ getGetV1ListGraphExecutionsMockHandler(() => page(listedRuns)),+ getGetV1ListExecutionSchedulesForAGraphMockHandler([]),+ getGetV2ListPresetsMockHandler({+ presets: [],+ pagination: {+ total_items: 0,+ total_pages: 0,+ current_page: 1,+ page_size: 100,+ },+ }),+ );+});++function withProviders(ui: ReactNode, queryClient: QueryClient) {+ return (+ <QueryClientProvider client={queryClient}>+ <NuqsTestingAdapter searchParams="activeTab=runs&activeItem=run-a">+ <BackendAPIProvider>+ <TooltipProvider>{ui}</TooltipProvider>+ </BackendAPIProvider>+ </NuqsTestingAdapter>+ </QueryClientProvider>+ );+}++function renderList(ui: ReactNode, queryClient: QueryClient) {+ return render(withProviders(ui, queryClient));+}++function rendersOf(id: string) {+ return renderedRunIDs.filter((renderedID) => renderedID === id).length;+}++test("a run prepended to the list renders only the new row and keeps the others' elements", async () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ renderList(+ <SidebarRunsList+ agent={agent}+ selectedRunId="run-a"+ onSelectRun={vi.fn()}+ />,+ queryClient,+ );++ const runA = await screen.findByTestId("library-run-item-run-a");+ const runB = screen.getByTestId("library-run-item-run-b");+ const rendersBefore = { a: rendersOf("run-a"), b: rendersOf("run-b") };++ listedRuns = [makeRun("run-new"), makeRun("run-a"), makeRun("run-b")];+ await act(async () => {+ await queryClient.refetchQueries({+ queryKey: getGetV1ListGraphExecutionsQueryKey(GRAPH_ID),+ });+ });++ expect(await screen.findByTestId("library-run-item-run-new")).toBeDefined();+ expect(screen.getByTestId("library-run-item-run-a")).toBe(runA);+ expect(screen.getByTestId("library-run-item-run-b")).toBe(runB);+ expect(rendersOf("run-a")).toBe(rendersBefore.a);+ expect(rendersOf("run-b")).toBe(rendersBefore.b);+ expect(rendersOf("run-new")).toBe(1);+ expect(+ screen+ .getAllByTestId(/^library-run-item-/)+ .map((row) => row.dataset.testid),+ ).toEqual([+ "library-run-item-run-new",+ "library-run-item-run-a",+ "library-run-item-run-b",+ ]);+});++test("clicking a run selects it through the latest onSelectRun", async () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const firstOnSelectRun = vi.fn();+ const { rerender } = renderList(+ <SidebarRunsList+ agent={agent}+ selectedRunId="run-a"+ onSelectRun={firstOnSelectRun}+ />,+ queryClient,+ );++ await userEvent.click(await screen.findByTestId("library-run-item-run-b"));+ expect(firstOnSelectRun).toHaveBeenCalledWith("run-b", "runs");++ const nextOnSelectRun = vi.fn();+ rerender(+ withProviders(+ <SidebarRunsList+ agent={agent}+ selectedRunId="run-a"+ onSelectRun={nextOnSelectRun}+ />,+ queryClient,+ ),+ );+ await userEvent.click(screen.getByTestId("library-run-item-run-b"));+ expect(nextOnSelectRun).toHaveBeenCalledWith("run-b", "runs");+ expect(firstOnSelectRun).toHaveBeenCalledTimes(1);+});++test("a run's label shows when it started, relative to now", async () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ listedRuns = [+ { ...makeRun("run-a"), started_at: new Date(Date.now() - 5 * 60_000) },+ ];+ renderList(+ <SidebarRunsList+ agent={agent}+ selectedRunId="run-a"+ onSelectRun={vi.fn()}+ />,+ queryClient,+ );++ const row = await screen.findByTestId("library-run-item-run-a");+ expect(row.textContent).toContain("5 minutes ago");+});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/__tests__/useSelectedRunView.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/__tests__/useSelectedRunView.test.tsxnew file mode 100644index 0000000000..8698b12901--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/__tests__/useSelectedRunView.test.tsx@@ -0,0 +1,70 @@+import {+ getGetV1GetExecutionDetailsMockHandler,+ getGetV1GetExecutionDetailsResponseMock,+} from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import { server } from "@/mocks/mock-server";+import { renderHook, waitFor } from "@/tests/integrations/test-utils";+import {+ focusManager,+ QueryClient,+ QueryClientProvider,+} from "@tanstack/react-query";+import { ReactNode } from "react";+import { afterEach, expect, test, vi } from "vitest";+import { useSelectedRunView } from "../useSelectedRunView";++const POLL_MS = 1500;+const TEST_TIMEOUT_MS = 20_000;++afterEach(() => {+ focusManager.setFocused(undefined);+});++function wait(ms: number) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++test(+ "polls a running run while the tab is visible and pauses while it is hidden",+ async () => {+ const detailRequests = vi.fn(() => ({+ ...getGetV1GetExecutionDetailsResponseMock(),+ id: "run-1",+ graph_id: "graph-1",+ status: AgentExecutionStatus.RUNNING,+ preset_id: null,+ node_executions: [],+ }));+ server.use(getGetV1GetExecutionDetailsMockHandler(detailRequests));+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ );+ }++ renderHook(() => useSelectedRunView("graph-1", "run-1"), { wrapper });+ await waitFor(() => expect(detailRequests).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(detailRequests).toHaveBeenCalledTimes(2), {+ timeout: POLL_MS * 2,+ });++ focusManager.setFocused(false);+ const whileHidden = detailRequests.mock.calls.length;+ await wait(POLL_MS * 2);+ expect(detailRequests).toHaveBeenCalledTimes(whileHidden);++ focusManager.setFocused(true);+ await waitFor(+ () =>+ expect(detailRequests.mock.calls.length).toBeGreaterThan(whileHidden),+ { timeout: POLL_MS * 2 },+ );+ },+ TEST_TIMEOUT_MS,+);diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/useSelectedRunView.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/useSelectedRunView.tsindex e3e035cea0..f2258c3201 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/useSelectedRunView.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/useSelectedRunView.ts@@ -26,7 +26,6 @@ export function useSelectedRunView(graphId: string, runId: string) {return 1500;return false;},- refetchIntervalInBackground: true,refetchOnWindowFocus: false,},});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsxindex a72eecf010..c661a431c3 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx@@ -12,16 +12,18 @@ import {TabsLineList,TabsLineTrigger,} from "@/components/molecules/TabsLine/TabsLine";+import { useStableCallback } from "@/hooks/useStableCallback";import { cn } from "@/lib/utils";import {activeItemParamFor,AGENT_LIBRARY_SECTION_PADDING_X,} from "../../../helpers";import { ScheduleListItem } from "./components/ScheduleListItem";-import { TaskListItem } from "./components/TaskListItem";+import { TaskListRow } from "./components/TaskListRow";import { TemplateListItem } from "./components/TemplateListItem";import { TriggerAgentListItem } from "./components/TriggerAgentListItem";import { TriggerListItem } from "./components/TriggerListItem";+import { uniqueRunsByID } from "./helpers";import { useSidebarRunsList } from "./useSidebarRunsList";interface Props {@@ -53,6 +55,9 @@ export function SidebarRunsList({onTabChange,onCountsChange,}: Props) {+ // Stable, so the memoised run rows and the auto-select effects in+ // useSidebarRunsList do not re-run on every parent render.+ const selectRun = useStableCallback(onSelectRun);const {runs,schedules,@@ -72,7 +77,7 @@ export function SidebarRunsList({tabValue,} = useSidebarRunsList({agent,- onSelectRun,+ onSelectRun: selectRun,onCountsChange,});@@ -157,22 +162,20 @@ export function SidebarRunsList({)}><InfiniteList- items={runs}+ items={uniqueRunsByID(runs)}hasMore={!!hasMoreRuns}isFetchingMore={isFetchingMoreRuns}onEndReached={fetchMoreRuns}className="flex min-h-0 flex-1 flex-nowrap items-center justify-start gap-4 overflow-x-scroll px-1 pb-4 pt-1 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-zinc-300 lg:flex-col lg:gap-3 lg:overflow-y-auto lg:overflow-x-hidden"itemWrapperClassName="w-auto lg:w-full"+ getKey={(run) => run.id}renderItem={(run) => (- <div className="w-[15rem] lg:w-full">- <TaskListItem- run={run}- title={agent.name}- agent={agent}- selected={selectedRunId === run.id}- onClick={() => onSelectRun && onSelectRun(run.id, "runs")}- />- </div>+ <TaskListRow+ run={run}+ agent={agent}+ selected={selectedRunId === run.id}+ onSelectRun={selectRun}+ />)}/></TabsLineContent>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/__tests__/helpers.test.tsnew file mode 100644index 0000000000..c3b2167c36--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/__tests__/helpers.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";+import { uniqueRunsByID } from "../helpers";++describe("uniqueRunsByID", () => {+ it("keeps the first copy of a run that two pages both returned", () => {+ const first = { id: "b", page: 1 };+ const runs = [{ id: "a" }, first, { id: "b", page: 2 }, { id: "c" }];++ const unique = uniqueRunsByID(runs);++ expect(unique.map((run) => run.id)).toEqual(["a", "b", "c"]);+ expect(unique[1]).toBe(first);+ });++ it("returns every run when none repeat", () => {+ const runs = [{ id: "a" }, { id: "b" }];+ expect(uniqueRunsByID(runs)).toEqual(runs);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/SidebarItemCard.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/SidebarItemCard.tsxindex 438fc4798d..42fe34e089 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/SidebarItemCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/SidebarItemCard.tsx@@ -6,7 +6,7 @@ import React from "react";interface Props {title: string;- description?: string;+ description?: React.ReactNode;descriptionTitle?: string;icon?: React.ReactNode;selected?: boolean;diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsxindex 8250bf20c7..b42ea4b1a5 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx@@ -3,7 +3,6 @@import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";import { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";-import { formatDistanceToNow } from "date-fns";import React from "react";import {describeFailedSteps,@@ -24,6 +23,7 @@ import {StopCircleIcon,} from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { RelativeTime } from "@/components/atoms/RelativeTime/RelativeTime";const statusIconMap: Record<AgentExecutionStatus, React.ReactNode> = {INCOMPLETE: (@@ -96,18 +96,24 @@ export function TaskListItem({) : (statusIconMap[run.status]);- const startedAgo = run.started_at- ? formatDistanceToNow(run.started_at, { addSuffix: true })- : "—";+ const startedAgo = run.started_at ? (+ <RelativeTime date={run.started_at} />+ ) : (+ "—"+ );return (<SidebarItemCardicon={icon}title={run.is_dry_run ? `${title} (Simulated)` : title}description={- withErrors- ? `${describeFailedSteps(getFailedStepCount(run))} · ${startedAgo}`- : startedAgo+ withErrors ? (+ <>+ {describeFailedSteps(getFailedStepCount(run))} · {startedAgo}+ </>+ ) : (+ startedAgo+ )}descriptionTitle={run.started_at ? new Date(run.started_at).toString() : undefineddiff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListRow.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListRow.tsxnew file mode 100644index 0000000000..b4ebb41234--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListRow.tsx@@ -0,0 +1,41 @@+"use client";++import type { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import isEqual from "lodash/isEqual";+import { memo } from "react";+import { TaskListItem } from "./TaskListItem";++interface Props {+ run: GraphExecutionMeta;+ agent: LibraryAgent;+ selected: boolean;+ onSelectRun: (id: string, tab: "runs") => void;+}++function TaskListRowComponent({ run, agent, selected, onSelectRun }: Props) {+ return (+ <div className="w-[15rem] lg:w-full">+ <TaskListItem+ run={run}+ title={agent.name}+ agent={agent}+ selected={selected}+ onClick={() => onSelectRun(run.id, "runs")}+ />+ </div>+ );+}++// A refetch after a run is prepended hands every row a new `run` object even+// when its fields are unchanged, so the run is compared by value.+function areRowPropsEqual(prev: Props, next: Props) {+ return (+ prev.agent === next.agent &&+ prev.selected === next.selected &&+ prev.onSelectRun === next.onSelectRun &&+ isEqual(prev.run, next.run)+ );+}++export const TaskListRow = memo(TaskListRowComponent, areRowPropsEqual);diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/helpers.tsnew file mode 100644index 0000000000..7fca9c2e4f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/helpers.ts@@ -0,0 +1,12 @@+/**+ * Pages are fetched by offset, so a run started between two page loads can+ * come back on both. Rows are keyed by run id, so each run is listed once.+ */+export function uniqueRunsByID<T extends { id: string }>(runs: T[]) {+ const seen = new Set<string>();+ return runs.filter((run) => {+ if (seen.has(run.id)) return false;+ seen.add(run.id);+ return true;+ });+}diff --git a/autogpt_platform/frontend/src/components/atoms/RelativeTime/RelativeTime.tsx b/autogpt_platform/frontend/src/components/atoms/RelativeTime/RelativeTime.tsxnew file mode 100644index 0000000000..1ba73ee081--- /dev/null+++ b/autogpt_platform/frontend/src/components/atoms/RelativeTime/RelativeTime.tsx@@ -0,0 +1,18 @@+"use client";++import { useNowMinute } from "@/hooks/useNowMinute";+import { formatDistanceToNow } from "date-fns";++interface Props {+ date: Date | string | number;+}++/**+ * `date` relative to now, e.g. "5 minutes ago". It re-renders on the shared+ * minute clock, so the label keeps up with time without a timer of its own+ * and without its parent re-rendering.+ */+export function RelativeTime({ date }: Props) {+ useNowMinute();+ return <>{formatDistanceToNow(date, { addSuffix: true })}</>;+}diff --git a/autogpt_platform/frontend/src/components/atoms/RelativeTime/__tests__/RelativeTime.test.tsx b/autogpt_platform/frontend/src/components/atoms/RelativeTime/__tests__/RelativeTime.test.tsxnew file mode 100644index 0000000000..f51ef7a742--- /dev/null+++ b/autogpt_platform/frontend/src/components/atoms/RelativeTime/__tests__/RelativeTime.test.tsx@@ -0,0 +1,65 @@+import { act, cleanup, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { RelativeTime } from "../RelativeTime";++let parentRenders = 0;++function Row({ id, date }: { id: string; date: Date }) {+ parentRenders += 1;+ return (+ <span data-testid={id}>+ <RelativeTime date={date} />+ </span>+ );+}++function label(id: string) {+ return screen.getByTestId(id).textContent;+}++describe("RelativeTime", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-04-23T10:00:30.000Z"));+ parentRenders = 0;+ });+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ });++ it("shows the time relative to now, as formatDistanceToNow does", () => {+ render(<Row id="a" date={new Date("2026-04-23T09:55:30.000Z")} />);+ expect(label("a")).toBe("5 minutes ago");+ });++ it("updates on the minute without its parent re-rendering", () => {+ vi.setSystemTime(new Date("2026-04-23T10:00:20.000Z"));+ render(<Row id="a" date={new Date("2026-04-23T10:00:00.000Z")} />);+ expect(label("a")).toBe("less than a minute ago");++ act(() => {+ vi.advanceTimersByTime(39_999);+ });+ expect(label("a")).toBe("less than a minute ago");++ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(label("a")).toBe("1 minute ago");+ expect(parentRenders).toBe(1);+ });++ it("shares one timer between every label on the page", () => {+ render(+ <>+ <Row id="a" date={new Date("2026-04-23T10:00:00.000Z")} />+ <Row id="b" date={new Date("2026-04-23T09:00:00.000Z")} />+ <Row id="c" date={new Date("2026-04-22T10:00:00.000Z")} />+ </>,+ );+ expect(vi.getTimerCount()).toBe(1);+ expect(label("b")).toBe("about 1 hour ago");+ expect(label("c")).toBe("1 day ago");+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/InfiniteList/InfiniteList.tsx b/autogpt_platform/frontend/src/components/molecules/InfiniteList/InfiniteList.tsxindex 4bbdc99432..4352e555c6 100644--- a/autogpt_platform/frontend/src/components/molecules/InfiniteList/InfiniteList.tsx+++ b/autogpt_platform/frontend/src/components/molecules/InfiniteList/InfiniteList.tsx@@ -5,6 +5,9 @@ import React from "react";interface InfiniteListProps<T> {items: T[];renderItem: (item: T, index: number) => React.ReactNode;+ /** A stable identity per item, so rows keep their state when items are+ * inserted above them. Falls back to the index. */+ getKey?: (item: T, index: number) => React.Key;onEndReached: () => void;hasMore: boolean;isFetchingMore?: boolean;@@ -16,6 +19,7 @@ export function InfiniteList<T>(props: InfiniteListProps<T>) {const {items,renderItem,+ getKey,onEndReached,hasMore,isFetchingMore,@@ -43,7 +47,10 @@ export function InfiniteList<T>(props: InfiniteListProps<T>) {return (<div className={className}>{items.map((item, idx) => (- <div key={idx} className={itemWrapperClassName}>+ <div+ key={getKey ? getKey(item, idx) : idx}+ className={itemWrapperClassName}+ >{renderItem(item, idx)}</div>))}diff --git a/autogpt_platform/frontend/src/components/molecules/InfiniteList/__tests__/InfiniteList.test.tsx b/autogpt_platform/frontend/src/components/molecules/InfiniteList/__tests__/InfiniteList.test.tsxnew file mode 100644index 0000000000..e2b421d268--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/InfiniteList/__tests__/InfiniteList.test.tsx@@ -0,0 +1,55 @@+import { render, screen } from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { useState } from "react";+import { describe, expect, it } from "vitest";+import { InfiniteList } from "../InfiniteList";++interface Item {+ id: string;+}++function Row({ item }: { item: Item }) {+ const [note, setNote] = useState("");+ return (+ <input+ aria-label={item.id}+ value={note}+ onChange={(event) => setNote(event.target.value)}+ />+ );+}++function List({ items, keyed }: { items: Item[]; keyed: boolean }) {+ return (+ <InfiniteList+ items={items}+ hasMore={false}+ onEndReached={() => undefined}+ getKey={keyed ? (item) => item.id : undefined}+ renderItem={(item) => <Row item={item} />}+ />+ );+}++describe("InfiniteList", () => {+ it("keeps each row's state with its item when an item is prepended", async () => {+ const { rerender } = render(<List keyed items={[{ id: "b" }]} />);+ const rowB = screen.getByLabelText("b");+ await userEvent.type(rowB, "kept");++ rerender(<List keyed items={[{ id: "a" }, { id: "b" }]} />);++ expect(screen.getByLabelText("b")).toBe(rowB);+ expect(screen.getByLabelText<HTMLInputElement>("b").value).toBe("kept");+ expect(screen.getByLabelText<HTMLInputElement>("a").value).toBe("");+ });++ it("keys rows by position when no getKey is given", async () => {+ const { rerender } = render(<List keyed={false} items={[{ id: "b" }]} />);+ await userEvent.type(screen.getByLabelText("b"), "moved");++ rerender(<List keyed={false} items={[{ id: "a" }, { id: "b" }]} />);++ expect(screen.getByLabelText<HTMLInputElement>("a").value).toBe("moved");+ });+});diff --git a/docs/engineering/frontend-perf-baseline.md b/docs/engineering/frontend-perf-baseline.mdindex e1319548f8..69fee1f1b5 100644--- a/docs/engineering/frontend-perf-baseline.md+++ b/docs/engineering/frontend-perf-baseline.md@@ -678,3 +678,51 @@ Added with SECRT-3009: `dev` app code at `6d793e53d` on a similar 16 GB cloud sa| `Primitive.div.SlotClone props:children` | 1,407 || `Popper props:children` | 1,269 || `PopperAnchor props:children` | 1,269 |++## library-agent-runs · baseline — median of 3 runs++Added with SECRT-3010 and measured on `dev` at `ede2df2ae`, before that change. The websocket is mocked; every run printed the same: 3 new runs caused 3 `GET` refetches of the run list and the selected RUNNING run polled its detail 5 times. Each new run re-rendered every row of the list about twice (20 to 23 cards, each with its actions menu and two dialogs). Total renders move by one full-list re-render (about 1,300 renders) from run to run.++| metric | median | range | spread |+| --- | --- | --- | --- |+| commits | 40 | 38 – 41 | 7.5% |+| total renders | 9,722 | 8,462 – 9,722 | 13.0% |+| renders per commit | 237.1 | 222.7 – 243.1 | 8.6% |+| max renders in one commit | 1,252 | 1,252 – 1,260 | 0.6% |+| script time (ms) | 785 | 720 – 789 | 8.7% |+| task time (ms) | 978 | 918 – 999 | 8.2% |+| layout time (ms) | 9 | 8 – 10 | 24.7% |+| style recalc time (ms) | 13 | 12 – 13 | 8.9% |+| long tasks (≥ 50 ms) | 6 | 6 – 6 | 0.0% |+| long task total (ms) | 579 | 539 – 588 | 8.5% |+| heap used after GC (MB) | 43.3 | 43.2 – 44.0 | 1.8% |++**Top components (median renders)**++| name | renders |+| --- | --- |+| `Presence` | 926 |+| `Dialog` | 687 |+| `Text` | 390 |+| `DialogPortal` | 344 |+| `DialogPortalProvider` | 344 |+| `DialogProvider` | 344 |+| `BaseContent` | 343 |+| `DialogWrap` | 343 |+| `MenuProvider` | 302 |+| `Primitive.div` | 259 |++**Top render causes (median renders)**++| name | renders |+| --- | --- |+| `Presence props:children` | 926 |+| `Dialog props:onOpenChange,children` | 344 |+| `DialogPortal props:children` | 344 |+| `DialogPortalProvider props:children` | 344 |+| `DialogProvider props:children` | 344 |+| `BaseContent props:children` | 343 |+| `DialogWrap props:styling,handleOpen,handleClose,children` | 343 |+| `Dialog props:controlled,styling,children` | 328 |+| `MenuProvider props:scope,children` | 302 |+| `Primitive.div props:children` | 224 |diff --git a/docs/engineering/frontend-perf-measurement.md b/docs/engineering/frontend-perf-measurement.mdindex b0cc20db55..65ed2cb604 100644--- a/docs/engineering/frontend-perf-measurement.md+++ b/docs/engineering/frontend-perf-measurement.md@@ -126,6 +126,7 @@ Names come from the component function. Third-party code bundled already minifie| `copilot-tool-wait` | Open the 200-message chat, send "go", and wait until the reply's one tool call shows "Running Perf lookup…". The reply then sends only `: heartbeat` comments, so the turn stays on that tool | Nothing | 20 s || `copilot-resize-drag` | Open the 200-message chat and click "Open files" so the files panel docks on the right | Drag the panel's resize handle 120 px wider with 60 pointer moves over 1 s | 1 s after the drop || `builder-run-beads` | Open the same 50-node workflow with its RUNNING run; the harness answers the websocket subscribe for that run itself | 10 new node executions over the websocket (a second, finished run of nodes 30 to 39 with new `node_exec_id`s), one every 150 ms, so each edge into one of those StoreValue nodes gets a new bead that travels the edge and is removed on arrival | 2 s after the last event |+| `library-agent-runs` | Open a workflow's page with 20 runs; the newest is RUNNING and selected, so its detail polls every 1.5 s. The websocket is mocked | Three new RUNNING runs arrive at the top of the list, 2.5 s apart: each is pushed as a `graph_execution_event`, the list refetches and the scenario waits for its row; prints the run-list and run-detail `GET`s seen | 1 s after the last run's 2.5 s |Each scenario's `readyWhen` field says exactly what setup waits for before the window opens. Most wait for the page's own content, then for network idle (at most 15 s, because some pages poll), then one more second.