π OpenHands: AI-Driven Development
fix(automations): page the list by offset so Load more works past 100 (#17839)
Henrique Hirakof1cda49095a0
diff --git a/__tests__/components/features/conversation-panel/conversation-panel.test.tsx b/__tests__/components/features/conversation-panel/conversation-panel.test.tsxindex 6ed0bf867e..7fc5af6ff6 100644--- a/__tests__/components/features/conversation-panel/conversation-panel.test.tsx+++ b/__tests__/components/features/conversation-panel/conversation-panel.test.tsx@@ -373,6 +373,38 @@ describe("ConversationPanel", () => {).not.toBeInTheDocument();});+ it("lists a conversation once when it comes back on the next page", async () => {+ // Arrange β a conversation's updated_at moved between the two requests,+ // so page 2 repeats the last row of page 1.+ const user = userEvent.setup();+ const shifted = createMockConversation({ id: "shifted", title: "Shifted" });+ const page1 = [+ createMockConversation({ id: "first", title: "First" }),+ shifted,+ ];+ const page2 = [+ shifted,+ createMockConversation({ id: "older", title: "Older" }),+ ];+ vi.spyOn(+ AgentServerConversationService,+ "searchConversations",+ ).mockImplementation(async (_limit, pageId) =>+ pageId === "page-2"+ ? { items: page2, next_page_id: null }+ : { items: page1, next_page_id: "page-2" },+ );+ renderConversationPanel();+ await screen.findByText("Shifted");++ // Act+ await user.click(screen.getByTestId("load-more-conversations"));++ // Assert+ await screen.findByText("Older");+ expect(screen.getAllByText("Shifted")).toHaveLength(1);+ });+it("scopes the list to the automation filter mode across hide and only", async () => {// Arrange: two manual conversations plus one automation run recognized// by its tags (local backend) and one by its trigger (cloud backend).diff --git a/__tests__/hooks/query/use-automations-backend-switch.test.tsx b/__tests__/hooks/query/use-automations-backend-switch.test.tsxindex b976c8d87b..30c7248420 100644--- a/__tests__/hooks/query/use-automations-backend-switch.test.tsx+++ b/__tests__/hooks/query/use-automations-backend-switch.test.tsx@@ -148,10 +148,9 @@ afterEach(() => {describe("automation hooks β backend switch", () => {it("useAutomations refetches when the active backend changes", async () => {// Arrange β mount under the local backend; capture the initial fetch.- const { result } = renderHook(- () => useAutomations({ limit: 50, offset: 0 }),- { wrapper: makeWrapper() },- );+ const { result } = renderHook(() => useAutomations(), {+ wrapper: makeWrapper(),+ });await waitFor(() => expect(result.current.isSuccess).toBe(true));expect(AutomationService.getAutomations).toHaveBeenCalledTimes(1);diff --git a/__tests__/routes/automations-list-behavior.test.tsx b/__tests__/routes/automations-list-behavior.test.tsxindex b111d0d06f..a91d15a9e8 100644--- a/__tests__/routes/automations-list-behavior.test.tsx+++ b/__tests__/routes/automations-list-behavior.test.tsx@@ -90,7 +90,7 @@ vi.mock("#/hooks/query/use-automation-health", () => ({vi.mock("#/hooks/query/use-automations", () => ({useAutomations: (options: unknown) => {mocks.useAutomations(options);- return mocks.automationsState;+ return { ...mocks.automationsState, hasNextPage: false };},useToggleAutomation: () => ({ mutate: mocks.toggle }),useDeleteAutomation: () => ({ mutate: mocks.remove }),@@ -531,8 +531,6 @@ describe("automations list states", () => {// The header copy comes from the admitted interface manifest.expect(screen.getByText("Widget automations")).toBeInTheDocument();expect(mocks.useAutomations).toHaveBeenCalledWith({- limit: 50,- offset: 0,enabled: false,});expect(mocks.useTranslation).toHaveBeenCalledWith("openhands");@@ -566,13 +564,13 @@ describe("automations list states", () => {screen.queryByRole("button", { name: "retry-list" }),).not.toBeInTheDocument();expect(mocks.useAutomations).toHaveBeenCalledWith({- limit: 50,- offset: 0,enabled: true,});});it("offers another list request when loading fails", async () => {+ // A failed first load has no data.+ mocks.automationsState.data = undefined;mocks.automationsState.isError = true;const user = userEvent.setup();@@ -1100,36 +1098,4 @@ describe("automations list interactions", () => {"grid",);});-- it("loads the next page size while more automations remain", async () => {- mocks.automationsState.data = {- automations: [makeAutomation()],- total: 51,- };- const user = userEvent.setup();-- renderList();- await user.click(- screen.getByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE }),- );-- expect(mocks.useAutomations).toHaveBeenLastCalledWith({- limit: 100,- offset: 0,- enabled: true,- });- });-- it("does not offer another page when the total is already displayed", () => {- mocks.automationsState.data = {- automations: [makeAutomation()],- total: 1,- };-- renderList();-- expect(- screen.queryByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE }),- ).not.toBeInTheDocument();- });});diff --git a/__tests__/routes/automations-list.test.tsx b/__tests__/routes/automations-list.test.tsxindex e7fcc34ad0..80824ce553 100644--- a/__tests__/routes/automations-list.test.tsx+++ b/__tests__/routes/automations-list.test.tsx@@ -503,3 +503,136 @@ describe("AutomationsList β list freshness on remount", () => {await screen.findByText(newAutomation.name);});});++describe("AutomationsList β Load more", () => {+ // Mirrors GET /api/automation/v1: newest first, `limit` capped at 100.+ function serveAutomations(automations: Automation[]) {+ vi.mocked(AutomationService.getAutomations)+ .mockReset()+ .mockImplementation(async (limit = 50, offset = 0) => {+ if (limit > 100) throw new Error("422: limit must be <= 100");+ return {+ automations: automations.slice(offset, offset + limit),+ total: automations.length,+ };+ });+ }++ function makeAutomations(count: number): Automation[] {+ return Array.from({ length: count }, (_, index) => ({+ ...automation,+ id: `auto-${index + 1}`,+ name: `Automation ${index + 1}`,+ }));+ }++ it("pages through more automations than one request may return", async () => {+ // Arrange+ serveAutomations(makeAutomations(120));+ const user = userEvent.setup();+ renderList();+ await screen.findByText("Automation 50");++ // Act+ await user.click(+ screen.getByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE }),+ );+ await screen.findByText("Automation 100");+ await user.click(+ screen.getByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE }),+ );++ // Assert+ await screen.findByText("Automation 120");+ expect(vi.mocked(AutomationService.getAutomations).mock.calls).toEqual([+ [50, 0],+ [50, 50],+ [50, 100],+ ]);+ expect(+ screen.queryByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE }),+ ).not.toBeInTheDocument();+ });++ it("holds Load more while the list refreshes after a change", async () => {+ // Arrange β turning an automation off refetches the loaded pages; keep+ // that refetch in flight so a Load more click would cancel it.+ serveAutomations(makeAutomations(60));+ const user = userEvent.setup();+ renderList();+ await screen.findByText("Automation 50");+ vi.mocked(AutomationService.getAutomations).mockReturnValue(+ new Promise(() => {}),+ );++ // Act+ await user.click(+ screen.getAllByLabelText(I18nKey.AUTOMATIONS$ACTIONS_MENU)[0],+ );+ await user.click(+ screen.getByRole("button", { name: I18nKey.AUTOMATIONS$TURN_OFF }),+ );++ // Assert+ await waitFor(() =>+ expect(+ screen.getByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE }),+ ).toBeDisabled(),+ );+ });++ it("lists an automation once when it shifts onto the next page", async () => {+ // Arrange β a new automation lands between the two requests, pushing+ // the last row of page one onto page two.+ const [first, ...rest] = makeAutomations(61);+ serveAutomations(rest);+ const user = userEvent.setup();+ renderList();+ await screen.findByText("Automation 51");+ serveAutomations([first, ...rest]);++ // Act+ await user.click(+ screen.getByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE }),+ );++ // Assert+ await screen.findByText("Automation 61");+ expect(screen.getAllByText("Automation 51")).toHaveLength(1);+ });++ it("keeps the loaded rows when Load more fails, and Load more retries", async () => {+ // Arrange β the next page fails once.+ serveAutomations(makeAutomations(60));+ const user = userEvent.setup();+ renderList();+ await screen.findByText("Automation 50");+ vi.mocked(AutomationService.getAutomations).mockRejectedValueOnce(+ new Error("503"),+ );+ const loadMore = () =>+ screen.getByRole("button", { name: I18nKey.AUTOMATIONS$LOAD_MORE });++ // Act+ await user.click(loadMore());+ await waitFor(() => expect(loadMore()).toBeEnabled());++ // Assert β the first page stays, with no full-page error.+ expect(screen.getByText("Automation 50")).toBeInTheDocument();+ expect(+ screen.queryByText(I18nKey.AUTOMATIONS$ERROR_TITLE),+ ).not.toBeInTheDocument();++ // Act β Load more asks for the failed page again.+ await user.click(loadMore());++ // Assert+ await screen.findByText("Automation 60");+ expect(+ vi.mocked(AutomationService.getAutomations).mock.calls.slice(1),+ ).toEqual([+ [50, 50],+ [50, 50],+ ]);+ });+});diff --git a/__tests__/utils/unique-by-id.test.ts b/__tests__/utils/unique-by-id.test.tsnew file mode 100644index 0000000000..fa82f766c9--- /dev/null+++ b/__tests__/utils/unique-by-id.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import { uniqueById } from "#/utils/unique-by-id";++describe("uniqueById", () => {+ it("keeps the first copy of each id in the original order", () => {+ // Arrange+ const items = [+ { id: "a", copy: 1 },+ { id: "b", copy: 1 },+ { id: "a", copy: 2 },+ { id: "c", copy: 1 },+ { id: "b", copy: 2 },+ ];++ // Act+ const result = uniqueById(items);++ // Assert+ expect(result).toEqual([+ { id: "a", copy: 1 },+ { id: "b", copy: 1 },+ { id: "c", copy: 1 },+ ]);+ });+});diff --git a/src/components/features/conversation-panel/conversation-panel.tsx b/src/components/features/conversation-panel/conversation-panel.tsxindex b4b271454f..ca224cfc6a 100644--- a/src/components/features/conversation-panel/conversation-panel.tsx+++ b/src/components/features/conversation-panel/conversation-panel.tsx@@ -60,6 +60,7 @@ import {} from "./conversation-panel-list-helpers";import { useArchivedConversationsStore } from "#/stores/archived-conversations-store";import { usePinnedConversationsStore } from "#/stores/pinned-conversations-store";+import { uniqueById } from "#/utils/unique-by-id";interface ConversationPanelProps {onClose?: () => void;@@ -263,14 +264,7 @@ export function ConversationPanel({// page fetches, a later page can overlap an earlier one and surface the// same conversation twice. Dedupe by id (keeping the first/freshest copy)// so the rendered count reflects real growth and React keys stay unique.- const seen = new Set<string>();- return all.filter((conversation) => {- if (seen.has(conversation.id)) {- return false;- }- seen.add(conversation.id);- return true;- });+ return uniqueById(all);}, [data]);// Grouped pagination is folder-oriented. Record the first backend page fordiff --git a/src/components/features/conversation/conversation-overview-automations-panel.tsx b/src/components/features/conversation/conversation-overview-automations-panel.tsxindex c1a49d790b..1690c4b622 100644--- a/src/components/features/conversation/conversation-overview-automations-panel.tsx+++ b/src/components/features/conversation/conversation-overview-automations-panel.tsx@@ -28,8 +28,6 @@ export function ConversationOverviewAutomationsPanel({refetch: refetchHealth,} = useAutomationHealth();const { data, isLoading, isError, refetch } = useAutomations({- limit: 50,- offset: 0,enabled: health?.status === "ok",});diff --git a/src/components/features/sidebar/use-sidebar-onboarding-checklist.ts b/src/components/features/sidebar/use-sidebar-onboarding-checklist.tsindex 410192d168..2d3909202d 100644--- a/src/components/features/sidebar/use-sidebar-onboarding-checklist.ts+++ b/src/components/features/sidebar/use-sidebar-onboarding-checklist.ts@@ -61,8 +61,7 @@ export function useSidebarOnboardingChecklist() {const { data: healthData } = useAutomationHealth();const isAutomationBackendHealthy = healthData?.status === "ok";const { data: automationsData } = useAutomations({- limit: 1,- offset: 0,+ pageSize: 1,enabled: isAutomationBackendHealthy,});diff --git a/src/hooks/query/use-automations.ts b/src/hooks/query/use-automations.tsindex f4ac927583..49d09fee18 100644--- a/src/hooks/query/use-automations.ts+++ b/src/hooks/query/use-automations.ts@@ -1,8 +1,18 @@-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";+import {+ type InfiniteData,+ useInfiniteQuery,+ useMutation,+ useQueryClient,+} from "@tanstack/react-query";import AutomationService from "#/api/automation-service/automation-service.api";import { useActiveBackend } from "#/contexts/active-backend-context";import { useTracking } from "#/hooks/use-tracking";-import type { Automation, AutomationSpec } from "#/types/automation";+import { uniqueById } from "#/utils/unique-by-id";+import type {+ Automation,+ AutomationSpec,+ AutomationsResponse,+} from "#/types/automation";import {AUTOMATION_DETAIL_QUERY_KEY,AUTOMATION_RUNS_QUERY_KEY,@@ -10,23 +20,51 @@ import {export const AUTOMATIONS_QUERY_KEY = ["automations"] as const;+// The automation service caps `limit` at 100, so lists page by offset.+const AUTOMATIONS_PAGE_SIZE = 50;++// One response from the loaded pages. At module level, so React Query runs it+// only when the pages change, not on every render.+function joinAutomationPages(+ data: InfiniteData<AutomationsResponse>,+): AutomationsResponse {+ return {+ automations: uniqueById(data.pages.flatMap((page) => page.automations)),+ // The last page has the newest count.+ total: data.pages.at(-1)?.total ?? 0,+ };+}+interface UseAutomationsOptions {- limit?: number;- offset?: number;+ /** Automations per request; at most 100. A count-only caller passes 1. */+ pageSize?: number;enabled?: boolean;}+/**+ * The org's automations, newest first, one page at a time. `data` joins the+ * loaded pages into one `AutomationsResponse` and `fetchNextPage` loads the+ * next one. An automation that shifts onto a later page between requests is+ * listed once.+ */export function useAutomations(options: UseAutomationsOptions = {}) {- const { limit = 50, offset = 0, enabled = true } = options;+ const { pageSize = AUTOMATIONS_PAGE_SIZE, enabled = true } = options;const active = useActiveBackend();- return useQuery({+ return useInfiniteQuery({queryKey: [...AUTOMATIONS_QUERY_KEY,- { limit, offset },+ { pageSize },active.backend.id,active.orgId,],- queryFn: () => AutomationService.getAutomations(limit, offset),+ queryFn: ({ pageParam }) =>+ AutomationService.getAutomations(pageSize, pageParam),+ initialPageParam: 0,+ getNextPageParam: (lastPage, _pages, lastOffset) => {+ const nextOffset = lastOffset + lastPage.automations.length;+ return nextOffset < lastPage.total ? nextOffset : undefined;+ },+ select: joinAutomationPages,staleTime: 0,enabled,});diff --git a/src/hooks/query/use-home-automations.ts b/src/hooks/query/use-home-automations.tsindex ed7e501894..ec43f2c26d 100644--- a/src/hooks/query/use-home-automations.ts+++ b/src/hooks/query/use-home-automations.ts@@ -37,8 +37,6 @@ export function useHomeAutomations() {isError,isLoading: isAutomationsLoading,} = useAutomations({- limit: 50,- offset: 0,enabled: !demo && isBackendHealthy,});diff --git a/src/routes/automations-list.tsx b/src/routes/automations-list.tsxindex 17d8ab7fda..73cd22ec94 100644--- a/src/routes/automations-list.tsx+++ b/src/routes/automations-list.tsx@@ -71,8 +71,6 @@ import { ManifestOverviewTiles } from "#/components/features/manifest/manifest-oimport { ManifestSubpageLayout } from "#/components/features/manifest/manifest-subpage-layout";import { cn, downloadBlob } from "#/utils/utils";-const PAGE_SIZE = 50;-/*** The page renders the interface manifest's copy, so without an admitted* manifest there is nothing to render: a 404, which the layout's error@@ -107,7 +105,6 @@ export default function AutomationsList() {const [viewMode, setViewMode] = useState<AutomationViewMode>(() =>readStoredAutomationViewMode(),);- const [limit, setLimit] = useState(PAGE_SIZE);const [deleteTarget, setDeleteTarget] = useState<{id: string;name: string;@@ -132,11 +129,15 @@ export default function AutomationsList() {const isBackendHealthy = healthData?.status === "ok";// Only fetch automations if the backend is healthy- const { data, isLoading, isError, refetch } = useAutomations({- limit,- offset: 0,- enabled: isBackendHealthy,- });+ const {+ data,+ isLoading,+ isError,+ refetch,+ hasNextPage,+ fetchNextPage,+ isFetching,+ } = useAutomations({ enabled: isBackendHealthy });// One runs query per listed automation β dashboard mode only.const runSummaries = useAutomationRunSummaries(data?.automations ?? [], {enabled: isBackendHealthy && dashboard !== null,@@ -327,9 +328,10 @@ export default function AutomationsList() {</div>);- const hasMore = data ? data.total > data.automations.length : false;+ // A failed refetch or Load more keeps the loaded rows; Load more retries.+ const isListError = isError && !data;const hasNoAutomations =- !isLoading && !isError && data?.automations.length === 0;+ !isLoading && !isListError && data?.automations.length === 0;// Show loading state while checking healthif (isHealthLoading) {@@ -440,12 +442,12 @@ export default function AutomationsList() {</div>)}- {isError && !isLoading && <ErrorState onRetry={refetch} />}+ {isListError && !isLoading && <ErrorState onRetry={refetch} />}{hasNoAutomations && <EmptyState />}{!isLoading &&- !isError &&+ !isListError &&data &&data.automations.length > 0 &&(dashboard && visible.length === 0 ? (@@ -487,11 +489,12 @@ export default function AutomationsList() {insights={groupInsights}/>- {hasMore && (+ {hasNextPage && (<buttontype="button"- onClick={() => setLimit((prev) => prev + PAGE_SIZE)}- className="self-center rounded-lg border border-border px-6 py-2 text-sm text-contrast hover:bg-surface-raised"+ onClick={() => fetchNextPage()}+ disabled={isFetching}+ className="self-center rounded-lg border border-border px-6 py-2 text-sm text-contrast hover:bg-surface-raised disabled:cursor-not-allowed disabled:opacity-50">{t(I18nKey.AUTOMATIONS$LOAD_MORE)}</button>diff --git a/src/utils/unique-by-id.ts b/src/utils/unique-by-id.tsnew file mode 100644index 0000000000..966e66d844--- /dev/null+++ b/src/utils/unique-by-id.ts@@ -0,0 +1,13 @@+/**+ * Removes items whose `id` was already seen, keeping the first copy and the+ * original order. Paged lists use it: a row can come back on a later page+ * when the list shifts between requests.+ */+export function uniqueById<T extends { id: string }>(items: T[]): T[] {+ const seen = new Set<string>();+ return items.filter((item) => {+ if (seen.has(item.id)) return false;+ seen.add(item.id);+ return true;+ });+}