diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md
index f0bdce50a5e..983c0f6b5e2 100644
--- a/doc/PRODUCT.md
+++ b/doc/PRODUCT.md
@@ -102,6 +102,13 @@ Tasks have parentage. Every task exists in service of a parent task, all the way
The current issue model includes stable issue identifiers, parent/sub-issues, blockers, a single assignee, comments, issue documents, attachments and work products, and review/approval handoffs. That structure keeps work inspectable by both the board and agents while still allowing agents to decompose work into smaller tasks.
+Task lists load additional pages as you scroll, with a **Load more tasks** button
+available as well. This applies to personal views, including Mine, Recent, Unread,
+Everything, and Blocked, and to organization views and their board layouts.
+Recent has no fixed 100-task cutoff. Needs attention loads task details in pages
+from its attention index. With search or task filters active, use the button to
+include older tasks. A failed page keeps loaded tasks visible and offers a retry.
+
Canceling a task with active subtasks opens a modal headed “Cancel N active subtasks?”
The modal lists each readable active descendant's status icon and title, without task IDs or links.
Done and canceled tasks are excluded. The person can cancel only the parent,
diff --git a/ui/src/components/BlockedInboxView.tsx b/ui/src/components/BlockedInboxView.tsx
index b279c36ed80..6d090462216 100644
--- a/ui/src/components/BlockedInboxView.tsx
+++ b/ui/src/components/BlockedInboxView.tsx
@@ -1,5 +1,5 @@
import { AgentIdentity } from "@/components/AgentIdentity";
-import { useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { AlertTriangle, CheckCircle2 } from "lucide-react";
import type { Issue } from "@paperclipai/shared";
@@ -7,7 +7,9 @@ import { describeError } from "../api/errors";
import { issuesApi } from "../api/issues";
import { queryKeys } from "../lib/queryKeys";
import { cn } from "../lib/utils";
-import { applyIssueFilters, type IssueFilterState, type IssueFilterWorkspaceContext } from "../lib/issue-filters";
+import { applyIssueFilters, countActiveIssueFilters, type IssueFilterState, type IssueFilterWorkspaceContext } from "../lib/issue-filters";
+import { useIssueListPages } from "../hooks/useIssueListPages";
+import { TaskListPagination } from "./TaskListPagination";
import { useIssueUpdatedFilterNow } from "../hooks/useIssueUpdatedFilterNow";
import { resolveInboxIssueBlockerAttention } from "../lib/inbox-live-descendants";
import {
@@ -30,8 +32,6 @@ import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
-const EMPTY_BLOCKED_ISSUES: Issue[] = [];
-
interface BlockedInboxViewProps {
companyId: string;
searchQuery: string;
@@ -75,25 +75,20 @@ export function BlockedInboxView({
}: BlockedInboxViewProps) {
const [collapsedVariants, setCollapsedVariants] = useState>(() => new Set());
- const blockedQuery = useQuery({
- queryKey: [...queryKeys.issues.listBlockedAttention(companyId), "live-descendant-summary", issueFilters.showAgentCreatedTasks],
- queryFn: () =>
- issuesApi.list(companyId, {
- attention: "blocked",
- includeRoutineExecutions: true,
- includeAgentCreatedTasks: issueFilters.showAgentCreatedTasks,
- includeParticipatedTasks: true,
- includeBlockedInboxAttention: true,
- includeBlockedBy: true,
- includeLiveDescendantSummary: true,
- limit: BLOCKED_LIST_LIMIT,
- }),
- });
- const {
- data: issues,
- isLoading,
- } = blockedQuery;
- const blockedIssues = issues ?? EMPTY_BLOCKED_ISSUES;
+ const queryKey = useMemo(() => [...queryKeys.issues.listBlockedAttention(companyId), "live-descendant-summary", issueFilters.showAgentCreatedTasks, BLOCKED_LIST_LIMIT], [companyId, issueFilters.showAgentCreatedTasks]);
+ const fetchPage = useCallback((offset: number, signal: AbortSignal) => issuesApi.list(companyId, {
+ attention: "blocked", includeRoutineExecutions: true,
+ includeAgentCreatedTasks: issueFilters.showAgentCreatedTasks, includeParticipatedTasks: true,
+ includeBlockedInboxAttention: true, includeBlockedBy: true, includeLiveDescendantSummary: true,
+ sortField: "updated", sortDir: "desc", limit: BLOCKED_LIST_LIMIT, offset,
+ }, { signal }), [companyId, issueFilters.showAgentCreatedTasks]);
+ const blockedQuery = useQuery({ queryKey, queryFn: ({ signal }) => fetchPage(0, signal) });
+ const pages = useIssueListPages({ queryKey, query: blockedQuery, fetchPage, pageSize: BLOCKED_LIST_LIMIT });
+ const { isLoading } = blockedQuery;
+ const blockedIssues = pages.issues;
+ const pagination = ;
const blockedView = useQueryView(blockedQuery);
const allRows = useMemo(() => buildBlockedInboxRows(blockedIssues), [blockedIssues]);
@@ -192,7 +187,7 @@ export function BlockedInboxView({
if (allRows.length === 0) {
return (
-
@@ -205,7 +200,7 @@ export function BlockedInboxView({
Tasks that need a decision, recovery, or external action will appear here.
-
+ {pagination}
);
}
@@ -218,6 +213,7 @@ export function BlockedInboxView({
>
No stopped items match your search.
+ {pagination}
);
}
@@ -278,6 +274,7 @@ export function BlockedInboxView({
})
)}
+ {pagination}
);
}
diff --git a/ui/src/components/IssuesList.paging.test.tsx b/ui/src/components/IssuesList.paging.test.tsx
new file mode 100644
index 00000000000..461075234ff
--- /dev/null
+++ b/ui/src/components/IssuesList.paging.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+import { act, type ComponentProps, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { Issue } from "@paperclipai/shared";
+import { queryKeys } from "@/lib/queryKeys";
+import { IssuesList } from "./IssuesList";
+
+const api = vi.hoisted(() => ({ listCompact: vi.fn(), listLabels: vi.fn() }));
+const settings = vi.hoisted(() => ({ streamlined: false, navigate: vi.fn() }));
+vi.mock("@/api/issues", () => ({ issuesApi: api }));
+vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company-1" }) }));
+vi.mock("@/context/DialogContext", () => ({ useDialogActions: () => ({ openNewIssue: () => {} }) }));
+vi.mock("@/hooks/useStreamlinedUiEnabled", () => ({ useStreamlinedUiEnabled: () => ({ enabled: settings.streamlined }) }));
+vi.mock("@/hooks/useShowAgentCreatedTasks", () => ({ useShowAgentCreatedTasks: () => false }));
+vi.mock("@/hooks/useWarmTaskDetailCode", () => ({ useWarmTaskDetailCode: () => {} }));
+vi.mock("@/hooks/useIssueRowDetails", () => ({ useIssueRowDetails: () => ({ enrichIssueRow: (issue: Issue) => issue }) }));
+vi.mock("@/lib/router", () => ({ useNavigate: () => settings.navigate, Link: ({ children }: { children: ReactNode }) => {children} }));
+vi.mock("./IssueRow", async importOriginal => ({ ...await importOriginal(),
+ IssueRow: ({ issue }: { issue: Issue }) => {issue.title},
+}));
+vi.mock("./KanbanBoard", async importOriginal => ({ ...await importOriginal(),
+ KanbanBoard: ({ issues }: { issues: Issue[] }) => {issues.map(issue => {issue.title})}
,
+}));
+
+let client: QueryClient;
+let container: HTMLDivElement;
+let root: Root;
+let tasks: Issue[];
+let listProps: Partial>;
+const titles = () => [...container.querySelectorAll("[data-task-row]")].map(row => row.textContent);
+const render = (issues: Issue[], initialSearch = "", searchWithinLoadedIssues = false) => act(async () => root.render(
+ {}} pagedIssuesProvided initialSearch={initialSearch} searchWithinLoadedIssues={searchWithinLoadedIssues} {...listProps} />,
+));
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ listProps = {};
+ localStorage.clear();
+ const { createIssue } = await vi.importActual("../../storybook/fixtures/paperclipData");
+ tasks = ["First supplied task", "Second supplied task", "Later supplied task"].map((title, index) => createIssue({
+ id: `provided-${index}`, companyId: "company-1", title, parentId: null,
+ }));
+ api.listCompact.mockResolvedValue([createIssue({ id: "capped-query", companyId: "company-1", title: "Capped query result" })]);
+ api.listLabels.mockResolvedValue([]);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
+ client.setQueryData(queryKeys.access.companyUserDirectory("company-1"), { users: [] });
+ client.setQueryData(queryKeys.instance.experimentalSettings, { enableIsolatedWorkspaces: false, enableExternalObjects: false });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); client.clear(); });
+
+it.each([
+ { streamlined: false, viewMode: "list" }, { streamlined: true, viewMode: "list" },
+ { streamlined: false, viewMode: "board" }, { streamlined: true, viewMode: "board" },
+])("owns one paging control and an explicit retry in %j", async ({ streamlined, viewMode }) => {
+ settings.streamlined = streamlined;
+ localStorage.setItem("provided-pages:company-1", JSON.stringify({ viewMode, groupBy: "none", nestingEnabled: false }));
+ const loadMore = vi.fn();
+ const retry = vi.fn();
+ listProps = { hasMoreIssues: true, onLoadMoreIssues: loadMore };
+ await render(tasks);
+ const buttons = () => [...container.querySelectorAll("button")].filter(button => /Load more tasks|Retry loading tasks/.test(button.textContent ?? ""));
+ expect(buttons()).toHaveLength(1);
+ await act(async () => buttons()[0]!.click());
+ expect(loadMore).toHaveBeenCalledTimes(1);
+ listProps = { hasMoreIssues: false, loadMoreIssuesError: new Error("later page failed"), onRetryLoadMoreIssues: retry };
+ await render(tasks);
+ expect(titles()).toHaveLength(3);
+ expect(buttons()).toHaveLength(1);
+ expect(buttons()[0]?.textContent).toBe("Retry loading tasks");
+ await act(async () => buttons()[0]!.click());
+ expect(retry).toHaveBeenCalledTimes(1);
+});
+
+it.each([false, true])("renders provided board pages without per-status requests with streamlined=%s", async streamlined => {
+ settings.streamlined = streamlined;
+ localStorage.setItem("provided-pages:company-1", JSON.stringify({ viewMode: "board", groupBy: "none", nestingEnabled: false }));
+ await render(tasks.slice(0, 2));
+ expect(container.querySelector("[data-board]")).not.toBeNull();
+ expect(titles()).toEqual(expect.arrayContaining(tasks.slice(0, 2).map(task => task.title)));
+ await render(tasks);
+ expect(titles()).toHaveLength(3);
+ expect(titles()).toContain("Later supplied task");
+ expect(api.listCompact).not.toHaveBeenCalled();
+});
+
+it.each([
+ { streamlined: false, local: false }, { streamlined: true, local: false },
+ { streamlined: false, local: true }, { streamlined: true, local: true },
+])("uses provided search pages without replacement or local filtering (%j)", async ({ streamlined, local }) => {
+ settings.streamlined = streamlined;
+ localStorage.setItem("provided-pages:company-1", JSON.stringify({ viewMode: "list", groupBy: "none", nestingEnabled: false }));
+ await render(tasks.slice(0, 2), "match-in-a-comment", local);
+ expect(titles()).toHaveLength(2);
+ await render(tasks, "match-in-a-comment", local);
+ expect(titles()).toHaveLength(3);
+ expect(titles()).toContain("Later supplied task");
+ expect(api.listCompact).not.toHaveBeenCalled();
+});
diff --git a/ui/src/components/IssuesList.tsx b/ui/src/components/IssuesList.tsx
index fd04ee7f22a..471d016d785 100644
--- a/ui/src/components/IssuesList.tsx
+++ b/ui/src/components/IssuesList.tsx
@@ -75,6 +75,7 @@ import {
} from "./IssueColumns";
import { StatusIcon } from "./StatusIcon";
import { EmptyState } from "./EmptyState";
+import { TaskListPagination } from "./TaskListPagination";
import { Identity } from "./Identity";
import { IssueGroupHeader } from "./IssueGroupHeader";
import { IssueFiltersPopover } from "./IssueFiltersPopover";
@@ -493,6 +494,7 @@ interface IssuesListProps {
initialSearch?: string;
searchFilters?: Omit;
searchWithinLoadedIssues?: boolean;
+ pagedIssuesProvided?: boolean;
baseCreateIssueDefaults?: Record;
createIssueLabel?: string;
defaultSortField?: IssueSortField;
@@ -510,6 +512,8 @@ interface IssuesListProps {
mutedIssueIds?: Set;
issueBadgeById?: Map;
onLoadMoreIssues?: () => void;
+ loadMoreIssuesError?: unknown;
+ onRetryLoadMoreIssues?: () => void;
onSearchChange?: (search: string) => void;
/** Opt in per surface while the canonical task row rolls out across collections. */
rowPresentation?: IssueRowPresentation;
@@ -750,6 +754,7 @@ function StreamlinedIssuesList({
initialSearch,
searchFilters,
searchWithinLoadedIssues = false,
+ pagedIssuesProvided = false,
baseCreateIssueDefaults,
createIssueLabel,
defaultSortField,
@@ -762,6 +767,8 @@ function StreamlinedIssuesList({
mutedIssueIds,
issueBadgeById,
onLoadMoreIssues,
+ loadMoreIssuesError,
+ onRetryLoadMoreIssues,
onSearchChange,
rowPresentation = "legacy",
toolbarContext,
@@ -985,7 +992,7 @@ function StreamlinedIssuesList({
...searchFilters,
...creationRequestFilters,
}, { signal }).then((rows) => rows as Issue[]),
- enabled: !!selectedCompanyId && normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues,
+ enabled: !!selectedCompanyId && normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues && !pagedIssuesProvided,
placeholderData: (previousData) => previousData,
});
const boardIssueQueries = useQueries({
@@ -1010,7 +1017,7 @@ function StreamlinedIssuesList({
limit: ISSUE_BOARD_COLUMN_RESULT_LIMIT,
...creationRequestFilters,
}, { signal }).then((rows) => rows as Issue[]),
- enabled: !!selectedCompanyId && viewState.viewMode === "board" && !searchWithinLoadedIssues,
+ enabled: !!selectedCompanyId && viewState.viewMode === "board" && !searchWithinLoadedIssues && !pagedIssuesProvided,
placeholderData: (previousData: Issue[] | undefined) => previousData,
})),
});
@@ -1209,7 +1216,7 @@ function StreamlinedIssuesList({
}, [issues]);
const boardIssues = useMemo(() => {
- if (viewState.viewMode !== "board" || searchWithinLoadedIssues) return null;
+ if (viewState.viewMode !== "board" || searchWithinLoadedIssues || pagedIssuesProvided) return null;
const merged = new Map();
let isPending = false;
for (const query of boardIssueQueries) {
@@ -1220,25 +1227,25 @@ function StreamlinedIssuesList({
}
if (merged.size > 0) return [...merged.values()];
return isPending ? issues : [];
- }, [boardIssueQueries, issues, searchWithinLoadedIssues, viewState.viewMode]);
+ }, [boardIssueQueries, issues, searchWithinLoadedIssues, pagedIssuesProvided, viewState.viewMode]);
const boardColumnLimitReached = useMemo(
() =>
viewState.viewMode === "board" &&
- !searchWithinLoadedIssues &&
+ !searchWithinLoadedIssues && !pagedIssuesProvided &&
boardIssueQueries.some((query) => (query.data?.length ?? 0) === ISSUE_BOARD_COLUMN_RESULT_LIMIT),
- [boardIssueQueries, searchWithinLoadedIssues, viewState.viewMode],
+ [boardIssueQueries, searchWithinLoadedIssues, pagedIssuesProvided, viewState.viewMode],
);
const sourceIssues = useMemo(() => {
- const useRemoteSearch = normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues;
+ const useRemoteSearch = normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues && !pagedIssuesProvided;
return boardIssues ?? (useRemoteSearch ? searchedIssues : issues);
- }, [boardIssues, issues, normalizedIssueSearch, searchedIssues, searchWithinLoadedIssues]);
+ }, [boardIssues, issues, normalizedIssueSearch, searchedIssues, searchWithinLoadedIssues, pagedIssuesProvided]);
const searchScopedIssues = useMemo(
- () => normalizedIssueSearch.length > 0 && searchWithinLoadedIssues
+ () => normalizedIssueSearch.length > 0 && searchWithinLoadedIssues && !pagedIssuesProvided
? sourceIssues.filter((issue) => issueMatchesLocalSearch(issue, normalizedIssueSearch))
: sourceIssues,
- [normalizedIssueSearch, searchWithinLoadedIssues, sourceIssues],
+ [normalizedIssueSearch, searchWithinLoadedIssues, pagedIssuesProvided, sourceIssues],
);
const hasExternalObjectStatusFilters = viewState.externalObjectStatuses.length > 0;
const issueIdsForExternalObjectSummaries = useMemo(
@@ -1730,6 +1737,15 @@ function StreamlinedIssuesList({
&& !isLoading
&& (hasMoreRenderedRows || (hasMoreHierarchyRows && !hierarchy.isFetching) || (hasMoreIssues && !isLoadingMoreIssues));
+ const pagination = {
+ if (loadMoreIssuesError) (onRetryLoadMoreIssues ?? onLoadMoreIssues)?.();
+ else if (viewState.viewMode === "board") onLoadMoreIssues?.();
+ else loadMoreIssueRows();
+ }} autoLoad={false} />;
+
useEffect(() => {
if (!canLoadMoreIssues) return;
let animationFrameId: number | null = null;
@@ -2660,19 +2676,17 @@ function StreamlinedIssuesList({
);
})}
- {(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues) && (
+ {(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues || Boolean(loadMoreIssuesError)) && (
-
- {isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)
- ? "Loading more tasks..."
- : remainingIssueRowCount > 0
- ? `Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`
- : "Scroll to load more tasks"}
-
+ {remainingIssueRowCount > 0 &&
+ {`Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`}
+
}
+ {pagination}
)}
))}
+ {viewState.viewMode === "board" && (hasMoreIssues || isLoadingMoreIssues || loadMoreIssuesError) ? pagination : null}
);
}
diff --git a/ui/src/components/LegacyIssuesList.tsx b/ui/src/components/LegacyIssuesList.tsx
index 14dbb3e4801..0971118747c 100644
--- a/ui/src/components/LegacyIssuesList.tsx
+++ b/ui/src/components/LegacyIssuesList.tsx
@@ -72,6 +72,7 @@ import {
} from "./IssueColumns";
import { StatusIcon } from "./StatusIcon";
import { EmptyState } from "./EmptyState";
+import { TaskListPagination } from "./TaskListPagination";
import { Identity } from "./Identity";
import { IssueGroupHeader } from "./IssueGroupHeader";
import { IssueFiltersPopover } from "./IssueFiltersPopover";
@@ -471,6 +472,7 @@ interface IssuesListProps {
initialSearch?: string;
searchFilters?: Omit;
searchWithinLoadedIssues?: boolean;
+ pagedIssuesProvided?: boolean;
baseCreateIssueDefaults?: Record;
createIssueLabel?: string;
defaultSortField?: IssueSortField;
@@ -488,6 +490,8 @@ interface IssuesListProps {
mutedIssueIds?: Set;
issueBadgeById?: Map;
onLoadMoreIssues?: () => void;
+ loadMoreIssuesError?: unknown;
+ onRetryLoadMoreIssues?: () => void;
onSearchChange?: (search: string) => void;
onUpdateIssue: (id: string, data: Record) => void;
}
@@ -698,6 +702,7 @@ export function IssuesList({
initialSearch,
searchFilters,
searchWithinLoadedIssues = false,
+ pagedIssuesProvided = false,
baseCreateIssueDefaults,
createIssueLabel,
defaultSortField,
@@ -710,6 +715,8 @@ export function IssuesList({
mutedIssueIds,
issueBadgeById,
onLoadMoreIssues,
+ loadMoreIssuesError,
+ onRetryLoadMoreIssues,
onSearchChange,
onUpdateIssue,
}: IssuesListProps) {
@@ -880,7 +887,7 @@ export function IssuesList({
...searchFilters,
...creationRequestFilters,
}, { signal }).then((rows) => rows as Issue[]),
- enabled: !!selectedCompanyId && normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues,
+ enabled: !!selectedCompanyId && normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues && !pagedIssuesProvided,
placeholderData: (previousData) => previousData,
});
const boardIssueQueries = useQueries({
@@ -905,7 +912,7 @@ export function IssuesList({
limit: ISSUE_BOARD_COLUMN_RESULT_LIMIT,
...creationRequestFilters,
}, { signal }).then((rows) => rows as Issue[]),
- enabled: !!selectedCompanyId && viewState.viewMode === "board" && !searchWithinLoadedIssues,
+ enabled: !!selectedCompanyId && viewState.viewMode === "board" && !searchWithinLoadedIssues && !pagedIssuesProvided,
placeholderData: (previousData: Issue[] | undefined) => previousData,
})),
});
@@ -1100,7 +1107,7 @@ export function IssuesList({
}, [issues]);
const boardIssues = useMemo(() => {
- if (viewState.viewMode !== "board" || searchWithinLoadedIssues) return null;
+ if (viewState.viewMode !== "board" || searchWithinLoadedIssues || pagedIssuesProvided) return null;
const merged = new Map();
let isPending = false;
for (const query of boardIssueQueries) {
@@ -1111,25 +1118,25 @@ export function IssuesList({
}
if (merged.size > 0) return [...merged.values()];
return isPending ? issues : [];
- }, [boardIssueQueries, issues, searchWithinLoadedIssues, viewState.viewMode]);
+ }, [boardIssueQueries, issues, searchWithinLoadedIssues, pagedIssuesProvided, viewState.viewMode]);
const boardColumnLimitReached = useMemo(
() =>
viewState.viewMode === "board" &&
- !searchWithinLoadedIssues &&
+ !searchWithinLoadedIssues && !pagedIssuesProvided &&
boardIssueQueries.some((query) => (query.data?.length ?? 0) === ISSUE_BOARD_COLUMN_RESULT_LIMIT),
- [boardIssueQueries, searchWithinLoadedIssues, viewState.viewMode],
+ [boardIssueQueries, searchWithinLoadedIssues, pagedIssuesProvided, viewState.viewMode],
);
const sourceIssues = useMemo(() => {
- const useRemoteSearch = normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues;
+ const useRemoteSearch = normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues && !pagedIssuesProvided;
return boardIssues ?? (useRemoteSearch ? searchedIssues : issues);
- }, [boardIssues, issues, normalizedIssueSearch, searchedIssues, searchWithinLoadedIssues]);
+ }, [boardIssues, issues, normalizedIssueSearch, searchedIssues, searchWithinLoadedIssues, pagedIssuesProvided]);
const searchScopedIssues = useMemo(
- () => normalizedIssueSearch.length > 0 && searchWithinLoadedIssues
+ () => normalizedIssueSearch.length > 0 && searchWithinLoadedIssues && !pagedIssuesProvided
? sourceIssues.filter((issue) => issueMatchesLocalSearch(issue, normalizedIssueSearch))
: sourceIssues,
- [normalizedIssueSearch, searchWithinLoadedIssues, sourceIssues],
+ [normalizedIssueSearch, searchWithinLoadedIssues, pagedIssuesProvided, sourceIssues],
);
const hasExternalObjectStatusFilters = viewState.externalObjectStatuses.length > 0;
const issueIdsForExternalObjectSummaries = useMemo(
@@ -1608,6 +1615,15 @@ export function IssuesList({
&& !isLoading
&& (hasMoreRenderedRows || (hasMoreHierarchyRows && !hierarchy.isFetching) || (hasMoreIssues && !isLoadingMoreIssues));
+ const pagination = {
+ if (loadMoreIssuesError) (onRetryLoadMoreIssues ?? onLoadMoreIssues)?.();
+ else if (viewState.viewMode === "board") onLoadMoreIssues?.();
+ else loadMoreIssueRows();
+ }} autoLoad={false} />;
+
useEffect(() => {
if (!canLoadMoreIssues) return;
let animationFrameId: number | null = null;
@@ -2446,19 +2462,17 @@ export function IssuesList({
);
})}
- {(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues) && (
+ {(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues || Boolean(loadMoreIssuesError)) && (
-
- {isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)
- ? "Loading more tasks..."
- : remainingIssueRowCount > 0
- ? `Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`
- : "Scroll to load more tasks"}
-
+ {remainingIssueRowCount > 0 &&
+ {`Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`}
+
}
+ {pagination}
)}
>
))}
+ {viewState.viewMode === "board" && (hasMoreIssues || isLoadingMoreIssues || loadMoreIssuesError) ? pagination : null}
);
}
diff --git a/ui/src/components/TaskListPagination.tsx b/ui/src/components/TaskListPagination.tsx
new file mode 100644
index 00000000000..03e48eced32
--- /dev/null
+++ b/ui/src/components/TaskListPagination.tsx
@@ -0,0 +1,30 @@
+import { useEffect, useRef } from "react";
+import { describeError } from "@/api/errors";
+import { Button } from "./ui/button";
+
+export function TaskListPagination({ hasMore, isLoadingMore, error, loadMore, autoLoad = true }: {
+ hasMore: boolean;
+ isLoadingMore: boolean;
+ error: unknown;
+ loadMore: () => void;
+ autoLoad?: boolean;
+}) {
+ const sentinel = useRef(null);
+ useEffect(() => {
+ if (!autoLoad || !hasMore || isLoadingMore || error || !sentinel.current || typeof IntersectionObserver === "undefined") return;
+ const observer = new IntersectionObserver(entries => {
+ if (entries.some(entry => entry.isIntersecting)) loadMore();
+ });
+ observer.observe(sentinel.current);
+ return () => observer.disconnect();
+ }, [autoLoad, hasMore, isLoadingMore, error, loadMore]);
+
+ if (!hasMore && !isLoadingMore && !error) return null;
+ return
+ {error ?
Couldn’t load more tasks. {describeError(error).body}
: null}
+ {isLoadingMore ?
Loading more tasks…
: null}
+
+
;
+}
diff --git a/ui/src/hooks/useInboxMineIssues.ts b/ui/src/hooks/useInboxMineIssues.ts
new file mode 100644
index 00000000000..b2799d1808a
--- /dev/null
+++ b/ui/src/hooks/useInboxMineIssues.ts
@@ -0,0 +1,48 @@
+import { useCallback, useMemo } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { INBOX_MINE_ISSUE_STATUS_FILTER, type InboxMineSnapshot, type Issue } from "@paperclipai/shared";
+import { ApiError } from "@/api/client";
+import { isTransientError } from "@/api/errors";
+import { issuesApi } from "@/api/issues";
+import { queryKeys } from "@/lib/queryKeys";
+import { useIssueListPages } from "./useIssueListPages";
+
+export function useInboxMineIssues({ companyId, userId, enabled }: {
+ companyId: string | null;
+ userId: string | null;
+ enabled: boolean;
+}) {
+ const client = useQueryClient();
+ const contextKey = useMemo(() => [...queryKeys.issues.list(companyId!), "mine-context", userId], [companyId, userId]);
+ const queryKey = useMemo(() => [...queryKeys.issues.listMineByMe(companyId!), "index", "with-routine-executions", "live-descendant-summary", 100, userId], [companyId, userId]);
+ const { data: snapshot } = useQuery({ queryKey: contextKey, enabled: false });
+ const active = enabled && !!companyId && !!userId;
+ const query = useQuery({
+ queryKey,
+ queryFn: async ({ signal }) => {
+ const next = await issuesApi.inboxMine(companyId!, { signal });
+ if (next.userId !== userId) {
+ void client.invalidateQueries({ queryKey: queryKeys.auth.session });
+ throw new ApiError("Your account changed. Refresh the inbox.", 409, { error: "account_changed" });
+ }
+ client.setQueryData(contextKey, next);
+ return next.issues as Issue[];
+ },
+ enabled: active,
+ refetchOnMount: snapshot ? undefined : "always",
+ refetchOnWindowFocus: false,
+ staleTime: snapshot ? 30_000 : 0,
+ refetchInterval: () => {
+ const current = client.getQueryData(contextKey);
+ return [current?.failureError, current?.contextError].some(error =>
+ error && isTransientError(new ApiError(error.message, error.status, null))) ? 5_000 : false;
+ },
+ });
+ const fetchPage = useCallback(async (offset: number, signal: AbortSignal) => await issuesApi.listCompact(companyId!, {
+ touchedByUserId: "me", inboxArchivedByUserId: "me", status: INBOX_MINE_ISSUE_STATUS_FILTER,
+ projection: "index", sortField: "updated", sortDir: "desc", includeRoutineExecutions: true,
+ includeLiveDescendantSummary: true, limit: 100, offset,
+ }, { signal }) as Issue[], [companyId]);
+ const pages = useIssueListPages({ queryKey, query, fetchPage, enabled: active });
+ return { query, queryKey, snapshot, ...pages };
+}
diff --git a/ui/src/hooks/useInboxTouchedIssues.test.tsx b/ui/src/hooks/useInboxTouchedIssues.test.tsx
new file mode 100644
index 00000000000..90649af16ef
--- /dev/null
+++ b/ui/src/hooks/useInboxTouchedIssues.test.tsx
@@ -0,0 +1,252 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { Issue } from "@paperclipai/shared";
+import { TaskListPagination } from "@/components/TaskListPagination";
+import { getRecentTouchedIssues } from "@/lib/inbox";
+import { queryKeys } from "@/lib/queryKeys";
+import { removeIssueFromInboxCaches, restoreIssueToInboxCaches, snapshotInboxIssueCaches } from "@/lib/inboxArchiveCache";
+import { useInboxTouchedIssues } from "./useInboxTouchedIssues";
+import { useInboxMineIssues } from "./useInboxMineIssues";
+
+const api = vi.hoisted(() => ({ listCompact: vi.fn(), inboxMine: vi.fn(), publish: vi.fn() }));
+vi.mock("@/api/issues", () => ({ issuesApi: api }));
+vi.mock("./useSharedPolling", () => ({
+ useSharedPollingQuery: () => ({}),
+ usePublishSharedQueryData: (_shared: unknown, data: unknown) => api.publish(data),
+}));
+
+const intersections = new Set();
+let root: Root;
+let container: HTMLDivElement;
+let client: QueryClient;
+let current: ReturnType;
+let options: Parameters[0];
+let autoLoad: boolean;
+let mineMode: boolean;
+
+const issue = (index: number) => ({
+ id: `task-${index}`, title: `Task ${index}`, companyId: "company-1",
+ lastActivityAt: new Date(Date.UTC(2026, 10, 1) - index * 60_000),
+} as Issue);
+
+function Harness() {
+ const touched = useInboxTouchedIssues({ ...options, enabled: options.enabled && !mineMode });
+ const mine = useInboxMineIssues({ ...options, enabled: options.enabled && mineMode });
+ current = mineMode ? mine : touched;
+ const visible = getRecentTouchedIssues(current.issues);
+ return <>
+ {visible.map(task => {task.title})}
+
+ >;
+}
+
+const render = () => act(async () => root.render());
+const intersect = () => act(async () => {
+ for (const callback of [...intersections]) callback([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
+});
+const clickMore = () => act(async () => container.querySelector("button")?.click());
+const visibleIds = () => [...container.querySelectorAll('[data-testid="tasks"] span')].map(node => node.textContent);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ intersections.clear();
+ vi.stubGlobal("IntersectionObserver", class {
+ constructor(private callback: IntersectionObserverCallback) {}
+ observe() { intersections.add(this.callback); }
+ disconnect() { intersections.delete(this.callback); }
+ });
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ container = document.createElement("div");
+ root = createRoot(container);
+ options = { companyId: "company-1", userId: "user-1", hideArchived: false, unreadOnly: false, enabled: true };
+ autoLoad = true;
+ mineMode = false;
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ client.clear();
+ vi.unstubAllGlobals();
+});
+
+it("loads past 100 on scroll and by button, dedupes overlapping pages, and stops at the last page", async () => {
+ api.listCompact.mockImplementation(async (_company, filters) => {
+ const start = filters.offset === 0 ? 0 : filters.offset - 1;
+ return Array.from({ length: Math.min(100, 215 - start) }, (_, index) => issue(start + index));
+ });
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ expect(api.listCompact).toHaveBeenCalledTimes(1);
+ expect(container.textContent).toContain("Load more tasks");
+
+ await act(async () => {
+ const callbacks = [...intersections];
+ for (let index = 0; index < 2; index++) {
+ for (const callback of callbacks) callback([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
+ }
+ });
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(199));
+ expect(api.listCompact).toHaveBeenCalledTimes(2);
+ await clickMore();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(215));
+ expect(visibleIds()).toContain("Task 214");
+ expect(current.hasMore).toBe(false);
+ expect(container.querySelector("button")).toBeNull();
+ expect(api.listCompact.mock.calls.map(([, filters]) => filters.offset)).toEqual([0, 100, 200]);
+ expect(api.listCompact.mock.calls.every(([, filters, request]) => filters.limit === 100 && request.signal instanceof AbortSignal)).toBe(true);
+ expect(api.publish.mock.lastCall?.[0]).toHaveLength(100);
+});
+
+it("bounds merge work across five pages and skips collection work on unchanged rerenders", async () => {
+ const { createIssue } = await vi.importActual("../../storybook/fixtures/paperclipData");
+ let reads = 0;
+ let readLimit = 0;
+ const tasks = Array.from({ length: 500 }, (_, index) => {
+ const id = `task-${index}`;
+ return Object.defineProperty(createIssue({ id, companyId: "company-1" }), "id", {
+ enumerable: true,
+ get() {
+ if (++reads > readLimit) throw new Error("Touched task pages exceeded their collection work limit");
+ return id;
+ },
+ });
+ });
+ api.listCompact.mockImplementation(async (_company, filters) => tasks.slice(filters.offset, filters.offset + filters.limit));
+ function Probe({ tick }: { tick: number }) {
+ current = useInboxTouchedIssues(options);
+ return ;
+ }
+ const renderProbe = (tick: number) => act(async () => root.render());
+
+ for (let page = 1; page <= 5; page++) {
+ const size = page * 100;
+ reads = 0;
+ readLimit = size * 6;
+ if (page === 1) await renderProbe(0);
+ else await act(async () => current.loadMore());
+ await vi.waitFor(() => expect(current.issues).toHaveLength(size));
+ expect(reads).toBeGreaterThan(0);
+ expect(reads).toBeLessThanOrEqual(size * 6);
+
+ const merged = current.issues;
+ const readsAfterMerge = reads;
+ readLimit = readsAfterMerge;
+ for (let tick = 1; tick <= 10; tick++) await renderProbe(tick);
+ expect(current.issues).toBe(merged);
+ expect(reads).toBe(readsAfterMerge);
+ expect(container.querySelector("output")?.textContent).toBe(String(size));
+ }
+ expect(api.listCompact.mock.calls.map(([, filters]) => filters.offset)).toEqual([0, 100, 200, 300, 400]);
+});
+
+it("keeps loaded rows visible after a page failure and retries that page without an automatic loop", async () => {
+ let finishPage!: (rows: Issue[]) => void;
+ api.listCompact.mockResolvedValueOnce(Array.from({ length: 100 }, (_, index) => issue(index)))
+ .mockRejectedValueOnce(new Error("page failed"))
+ .mockImplementationOnce(() => new Promise(resolve => { finishPage = resolve; }));
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ await intersect();
+ await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Couldn’t load more tasks"));
+ expect(visibleIds()).toHaveLength(100);
+ expect(intersections.size).toBe(0);
+ expect(api.listCompact).toHaveBeenCalledTimes(2);
+ await clickMore();
+ await vi.waitFor(() => expect(container.querySelector("button")?.disabled).toBe(true));
+ expect(visibleIds()).toHaveLength(100);
+ await act(async () => finishPage([issue(100)]));
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(101));
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ expect(api.listCompact.mock.calls.map(([, filters]) => filters.offset)).toEqual([0, 100, 100]);
+});
+
+it("keeps each page compatible with archive rollback and live invalidation", async () => {
+ api.listCompact.mockImplementation(async (_company, filters) =>
+ Array.from({ length: filters.offset ? 5 : 100 }, (_, index) => issue(filters.offset + index)));
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ await clickMore();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(105));
+ const snapshot = snapshotInboxIssueCaches(client, "company-1").filter(([, data]) => data !== undefined);
+ expect(snapshot).toHaveLength(2);
+ expect(snapshot.every(([, data]) => Array.isArray(data))).toBe(true);
+ await act(async () => removeIssueFromInboxCaches(client, "company-1", "task-103"));
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(104));
+ await act(async () => restoreIssueToInboxCaches(client, snapshot, "task-103"));
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(105));
+ await act(async () => { await client.invalidateQueries({ queryKey: queryKeys.issues.listTouchedByMe("company-1") }); });
+ expect(api.listCompact.mock.calls.map(([, filters]) => filters.offset)).toEqual([0, 100, 0, 100]);
+ expect(visibleIds()).toHaveLength(105);
+});
+
+it("lets filtered views and browsers without IntersectionObserver load older tasks by button", async () => {
+ autoLoad = false;
+ api.listCompact.mockImplementation(async (_company, filters) =>
+ Array.from({ length: filters.offset ? 1 : 100 }, (_, index) => issue(filters.offset + index)));
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ expect(intersections.size).toBe(0);
+ vi.stubGlobal("IntersectionObserver", undefined);
+ autoLoad = true;
+ await render();
+ expect(container.textContent).toContain("Load more tasks");
+ await clickMore();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(101));
+});
+
+it("resets history for another account, company, or unread view", async () => {
+ api.listCompact.mockImplementation(async (companyId, filters) =>
+ Array.from({ length: 100 }, (_, index) => ({ ...issue(filters.offset + index), title: `${companyId} task ${filters.offset + index}` })));
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ await clickMore();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(200));
+ options = { ...options, userId: "user-2" };
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ options = { ...options, companyId: "company-2" };
+ await render();
+ await vi.waitFor(() => expect(visibleIds()[0]).toBe("company-2 task 0"));
+ expect(visibleIds()).toHaveLength(100);
+ expect(api.listCompact.mock.calls.slice(-2).map(([, filters]) => filters.offset)).toEqual([0, 0]);
+ options = { ...options, unreadOnly: true, hideArchived: true };
+ await render();
+ await vi.waitFor(() => expect(current.issues).toHaveLength(100));
+ expect(current.hasMore).toBe(true);
+ expect(api.listCompact.mock.lastCall?.[1]).toMatchObject({ unreadForUserId: "me", inboxArchivedByUserId: "me", offset: 0 });
+});
+
+it.each(["Recent", "Unread"])("paginates %s past 100 tasks", async view => {
+ options = { ...options, unreadOnly: view === "Unread", hideArchived: view === "Unread" };
+ api.listCompact.mockImplementation(async (_company, filters) =>
+ Array.from({ length: filters.offset ? 15 : 100 }, (_, index) => issue(filters.offset + index)));
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ await clickMore();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(115));
+ expect(current.hasMore).toBe(false);
+ expect(api.listCompact.mock.lastCall?.[1]).toMatchObject({ offset: 100, limit: 100,
+ unreadForUserId: view === "Unread" ? "me" : undefined });
+});
+
+it("paginates Mine while preserving its coherent first-page snapshot", async () => {
+ mineMode = true;
+ const snapshot = { userId: "user-1", issues: Array.from({ length: 100 }, (_, index) => issue(index)),
+ contextIssues: [issue(500)], failureRuns: [], failureIssueIds: [] };
+ api.inboxMine.mockResolvedValue(snapshot);
+ api.listCompact.mockResolvedValue(Array.from({ length: 15 }, (_, index) => issue(100 + index)));
+ await render();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(100));
+ expect(api.listCompact).not.toHaveBeenCalled();
+ await clickMore();
+ await vi.waitFor(() => expect(visibleIds()).toHaveLength(115));
+ expect(api.inboxMine).toHaveBeenCalledTimes(1);
+ expect(api.listCompact.mock.lastCall?.[1]).toMatchObject({ offset: 100, limit: 100,
+ touchedByUserId: "me", inboxArchivedByUserId: "me", projection: "index" });
+ expect(client.getQueryData([...queryKeys.issues.list("company-1"), "mine-context", "user-1"])).toEqual(snapshot);
+ expect(current.hasMore).toBe(false);
+});
diff --git a/ui/src/hooks/useInboxTouchedIssues.ts b/ui/src/hooks/useInboxTouchedIssues.ts
new file mode 100644
index 00000000000..1c3179b7f2f
--- /dev/null
+++ b/ui/src/hooks/useInboxTouchedIssues.ts
@@ -0,0 +1,53 @@
+import { useCallback, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { INBOX_MINE_ISSUE_STATUS_FILTER, type Issue } from "@paperclipai/shared";
+import { issuesApi } from "@/api/issues";
+import { queryKeys } from "@/lib/queryKeys";
+import { usePublishSharedQueryData, useSharedPollingQuery } from "./useSharedPolling";
+import { useIssueListPages } from "./useIssueListPages";
+
+const PAGE_SIZE = 100;
+
+export function useInboxTouchedIssues({ companyId, userId, hideArchived, enabled, unreadOnly = false }: {
+ companyId: string | null;
+ userId: string | null;
+ hideArchived: boolean;
+ enabled: boolean;
+ unreadOnly?: boolean;
+}) {
+ const key = useMemo(() => [
+ ...(hideArchived || unreadOnly ? queryKeys.issues.listUnreadTouchedByMe(companyId!) : queryKeys.issues.listTouchedByMe(companyId!)),
+ "index", "with-routine-executions", "live-descendant-summary", PAGE_SIZE, userId, unreadOnly,
+ ] as const, [companyId, userId, hideArchived, unreadOnly]);
+ const fetchPage = useCallback(async (offset: number, signal: AbortSignal) =>
+ await issuesApi.listCompact(companyId!, {
+ touchedByUserId: "me",
+ inboxArchivedByUserId: hideArchived ? "me" : undefined,
+ unreadForUserId: unreadOnly ? "me" : undefined,
+ status: INBOX_MINE_ISSUE_STATUS_FILTER,
+ projection: "index",
+ sortField: "updated",
+ sortDir: "desc",
+ includeRoutineExecutions: true,
+ includeLiveDescendantSummary: true,
+ limit: PAGE_SIZE,
+ offset,
+ }, { signal }) as Issue[], [companyId, hideArchived, unreadOnly]);
+ const query = useQuery({
+ queryKey: key,
+ queryFn: ({ signal }) => fetchPage(0, signal),
+ enabled,
+ refetchOnWindowFocus: false,
+ staleTime: 30_000,
+ });
+ const shared = useSharedPollingQuery({
+ companyId,
+ resourceKey: hideArchived ? "inbox:unread-touched-issues" : "inbox:touched-issues",
+ queryKey: key,
+ enabled,
+ });
+ usePublishSharedQueryData(shared, query.data, query.dataUpdatedAt);
+
+ const pages = useIssueListPages({ queryKey: key, query, fetchPage, enabled });
+ return { query, ...pages };
+}
diff --git a/ui/src/hooks/useIssueListPages.ts b/ui/src/hooks/useIssueListPages.ts
new file mode 100644
index 00000000000..051bb9eea90
--- /dev/null
+++ b/ui/src/hooks/useIssueListPages.ts
@@ -0,0 +1,58 @@
+import { useCallback, useMemo, useState } from "react";
+import { useQueries, useQueryClient, type QueryKey, type UseQueryResult } from "@tanstack/react-query";
+import type { Issue } from "@paperclipai/shared";
+
+const NO_ISSUES: Issue[] = [];
+
+function combineOlderPages(results: UseQueryResult[]) {
+ return {
+ pages: results.map(result => result.data ?? NO_ISSUES),
+ error: results.find(result => result.isError)?.error ?? null,
+ isFetching: results.some(result => result.isFetching),
+ };
+}
+
+export function useIssueListPages({ queryKey, query, fetchPage, enabled = true, pageSize = 100 }: {
+ queryKey: QueryKey;
+ query: Pick, "data" | "isSuccess" | "isFetching">;
+ fetchPage: (offset: number, signal: AbortSignal) => Promise;
+ enabled?: boolean;
+ pageSize?: number;
+}) {
+ const client = useQueryClient();
+ const serializedKey = JSON.stringify(queryKey);
+ const key = useMemo(() => JSON.parse(serializedKey) as QueryKey, [serializedKey]);
+ const scope = JSON.stringify([key, pageSize]);
+ const [paging, setPaging] = useState({ scope, count: 0 });
+ const count = paging.scope === scope ? paging.count : 0;
+ const older = useQueries({
+ queries: Array.from({ length: count }, (_, index) => ({
+ queryKey: [...key, "older", (index + 1) * pageSize],
+ queryFn: ({ signal }: { signal: AbortSignal }) => fetchPage((index + 1) * pageSize, signal),
+ enabled: enabled && query.isSuccess,
+ refetchOnWindowFocus: false,
+ staleTime: 30_000,
+ })),
+ combine: combineOlderPages,
+ });
+ const issues = useMemo(() => {
+ const byId = new Map();
+ for (const page of [query.data ?? NO_ISSUES, ...older.pages]) {
+ for (const issue of page) if (!byId.has(issue.id)) byId.set(issue.id, issue);
+ }
+ return [...byId.values()];
+ }, [query.data, older.pages]);
+ const lastPage = count ? older.pages.at(-1) : query.data;
+ const hasMore = enabled && (older.error !== null || lastPage?.length === pageSize);
+ const loadMore = useCallback(() => {
+ if (!hasMore || query.isFetching || older.isFetching) return;
+ if (older.error) {
+ void client.refetchQueries({ queryKey: [...key, "older"], type: "active", predicate: q => q.state.status === "error" });
+ return;
+ }
+ setPaging(current => current.scope === scope && current.count !== count
+ ? current : { scope, count: count + 1 });
+ }, [client, key, scope, count, hasMore, query.isFetching, older.isFetching, older.error]);
+
+ return { issues, hasMore, loadMore, isLoadingMore: older.isFetching, loadMoreError: older.error };
+}
diff --git a/ui/src/lib/inbox.test.ts b/ui/src/lib/inbox.test.ts
index cff6121b81e..7600d845e4a 100644
--- a/ui/src/lib/inbox.test.ts
+++ b/ui/src/lib/inbox.test.ts
@@ -36,7 +36,6 @@ import {
loadLastInboxTab,
matchesInboxIssueSearch,
normalizeInboxIssueColumns,
- RECENT_ISSUES_LIMIT,
resolveInboxNestingEnabled,
resolveIssueWorkspaceName,
resolveIssueWorkspaceGroup,
@@ -686,8 +685,8 @@ describe("inbox helpers", () => {
expect(shouldShowCompanyAlerts("all")).toBe(true);
});
- it("limits recent touched issues before unread badge counting", () => {
- const issues = Array.from({ length: RECENT_ISSUES_LIMIT + 5 }, (_, index) => {
+ it("keeps all loaded touched issues available for unread badge counting", () => {
+ const issues = Array.from({ length: 215 }, (_, index) => {
const issue = makeIssue(String(index + 1), index < 3);
issue.lastActivityAt = new Date(Date.UTC(2026, 2, 31, 0, 0, 0, 0) - index * 60_000);
return issue;
@@ -695,10 +694,23 @@ describe("inbox helpers", () => {
const recentIssues = getRecentTouchedIssues(issues);
- expect(recentIssues).toHaveLength(RECENT_ISSUES_LIMIT);
+ expect(recentIssues).toHaveLength(215);
expect(getUnreadTouchedIssues(recentIssues).map((issue) => issue.id)).toEqual(["1", "2", "3"]);
});
+ it("keeps every loaded page in all personal task views", () => {
+ const issues = Array.from({ length: 215 }, (_, index) => {
+ const issue = makeIssue(String(index), false);
+ issue.lastActivityAt = new Date(Date.UTC(2026, 2, 31) - index * 60_000);
+ return issue;
+ }).reverse();
+
+ const everything = getRecentTouchedIssues(issues);
+ expect(everything).toHaveLength(215);
+ expect(everything[0]?.id).toBe("0");
+ expect(everything.at(-1)?.id).toBe("214");
+ });
+
it("matches workspace names when inbox issue search includes workspace labels", () => {
const issue = makeIssue("workspace", false);
issue.projectId = "project-1";
diff --git a/ui/src/lib/inbox.ts b/ui/src/lib/inbox.ts
index 94d130948ce..cec42a16059 100644
--- a/ui/src/lib/inbox.ts
+++ b/ui/src/lib/inbox.ts
@@ -14,7 +14,6 @@ import {
} from "./issue-filters";
import { formatAssigneeUserLabel } from "./assignees";
-export const RECENT_ISSUES_LIMIT = 100;
export const ACTIONABLE_APPROVAL_STATUSES = new Set(["pending", "revision_requested"]);
export const DISMISSED_KEY = "paperclip:inbox:dismissed";
export const READ_ITEMS_KEY = "paperclip:inbox:read-items";
@@ -749,7 +748,7 @@ export function sortIssuesByMostRecentActivity(a: Issue, b: Issue): number {
}
export function getRecentTouchedIssues(issues: Issue[]): Issue[] {
- return [...issues].sort(sortIssuesByMostRecentActivity).slice(0, RECENT_ISSUES_LIMIT);
+ return [...issues].sort(sortIssuesByMostRecentActivity);
}
export function getUnreadTouchedIssues(issues: Issue[]): Issue[] {
diff --git a/ui/src/pages/CoordinatorTasks.tsx b/ui/src/pages/CoordinatorTasks.tsx
index b9fe6aa25a4..88fc90788bd 100644
--- a/ui/src/pages/CoordinatorTasks.tsx
+++ b/ui/src/pages/CoordinatorTasks.tsx
@@ -13,6 +13,7 @@ import { heartbeatsApi } from "@/api/heartbeats";
import { issuesApi } from "@/api/issues";
import { EmptyState } from "@/components/EmptyState";
import { KanbanBoard } from "@/components/KanbanBoard";
+import { TaskListPagination } from "@/components/TaskListPagination";
import { TaskList, type TaskListItem } from "@/components/TaskList";
import { TaskListToolbar } from "@/components/TaskListToolbar";
import { TruncatedTextMarqueeProvider } from "@/components/TruncatedText";
@@ -145,7 +146,11 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
queryFn: () => attentionApi.taskIndex(companyId!), enabled: !!companyId && !!userId && needsAttention });
// Resolve every pending task in bounded index batches, including tasks outside
// the first list page. Keep full task enrichment out of the collection read.
- const attentionIds = needsAttention ? attention.data?.taskIds ?? [] : [];
+ const attentionScope = JSON.stringify([companyId, userId, needsAttention, deferredQuery, participantAgentId, workspaceIds, originKind, includeBlockedBy]);
+ const [attentionPaging, setAttentionPaging] = useState({ scope: attentionScope, limit: 100 });
+ const attentionLimit = attentionPaging.scope === attentionScope ? attentionPaging.limit : 100;
+ const allAttentionIds = needsAttention ? attention.data?.taskIds ?? [] : [];
+ const attentionIds = allAttentionIds.slice(0, attentionLimit);
const attentionBatches = Array.from({ length: Math.ceil(attentionIds.length / 100) }, (_, index) => attentionIds.slice(index * 100, (index + 1) * 100));
const attentionTasks = useQueries({ queries: attentionBatches.map(ids => ({
queryKey: [...queryKeys.issues.list(companyId!), "coordinator-attention-index", userId, participantAgentId, deferredQuery, originKind, includeBlockedBy, ids],
@@ -264,11 +269,26 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
const update = useMutation({ mutationFn: ({ id, data }: { id: string; data: Record }) => data.status === "cancelled" ? cancelTask(id, data) : issuesApi.update(id, data),
onSuccess: () => { void client.invalidateQueries({ queryKey: queryKeys.issues.list(companyId!) }); void client.invalidateQueries({ queryKey: queryKeys.attention(companyId!) }); },
});
- const error = (needsAttention ? attention.error ?? attentionTasks.find(task => task.error)?.error : tasks.error)
+ const attentionMoreError = attentionTasks.slice(1).find(task => task.error)?.error;
+ const isLoadingMore = needsAttention ? attentionTasks.slice(1).some(task => task.isFetching) : tasks.isFetchingNextPage;
+ const loadMoreError = needsAttention ? attentionMoreError : tasks.isFetchNextPageError ? tasks.error : null;
+ const loadMore = () => {
+ if (!needsAttention) {
+ if (tasks.hasNextPage && !tasks.isFetching) void tasks.fetchNextPage({ cancelRefetch: false });
+ } else if (!attentionTasks.some(task => task.isFetching)) {
+ if (attentionMoreError) {
+ for (const task of attentionTasks) if (task.error) void task.refetch();
+ } else {
+ setAttentionPaging(current => current.scope === attentionScope && current.limit !== attentionLimit
+ ? current : { scope: attentionScope, limit: attentionLimit + 100 });
+ }
+ }
+ };
+ const error = (needsAttention ? attention.error ?? attentionTasks[0]?.error : tasks.isFetchNextPageError ? null : tasks.error)
?? (view === "unread" ? parentContext.error : null)
?? agents.error ?? projects.error ?? directory.error ?? labels.error ?? (update.error instanceof TaskCancellationDismissedError ? null : update.error)
?? (collection.filters.liveOnly ? liveRuns.error : null);
- const pending = (needsAttention ? attention.isPending || attentionTasks.some(task => task.isPending) : tasks.isPending)
+ const pending = (needsAttention ? attention.isPending || (records.length === 0 && attentionTasks.some(task => task.isPending)) : tasks.isPending)
|| (view === "unread" && parentIds.length > 0 && parentContext.isPending)
|| (collection.filters.liveOnly && liveRuns.isPending);
useWarmTaskDetailCode(!pending && !error && items.length > 0);
@@ -313,7 +333,9 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } =
getArchiveAction={getArchiveAction} issueLinkState={issueLinkState} collapsedIds={collection.collapsedIds} onCollapsedIdsChange={collection.setCollapsedIds} /> : empty}
{collection.layout === "board" ? collection.matchingItems.length
? enrichIssueRow(item.issue))} agents={agents.data} onUpdateIssue={(id, data) => update.mutate({ id, data })} /> : empty : null}
- {!needsAttention && tasks.hasNextPage ? {view === "unread" ? unreadIds.size : items.length} tasks loaded. Load more to include them in filters.
: null}
+
>}
;
}
diff --git a/ui/src/pages/DesignSandboxTasks.tsx b/ui/src/pages/DesignSandboxTasks.tsx
index eb7ba9c874e..dbe0eafdc60 100644
--- a/ui/src/pages/DesignSandboxTasks.tsx
+++ b/ui/src/pages/DesignSandboxTasks.tsx
@@ -8,6 +8,7 @@ import { useAccountIdentity } from "@/api/companies-query";
import { issuesApi } from "@/api/issues";
import { EmptyState } from "@/components/EmptyState";
import { KanbanBoard } from "@/components/KanbanBoard";
+import { TaskListPagination } from "@/components/TaskListPagination";
import { TaskList, type TaskListItem } from "@/components/TaskList";
import { TaskListToolbar } from "@/components/TaskListToolbar";
import { TruncatedTextMarqueeProvider } from "@/components/TruncatedText";
@@ -85,7 +86,7 @@ export function DesignSandboxTasks() {
mutationFn: ({ id, data }: { id: string; data: Record }) => issuesApi.update(id, data),
onSuccess: () => { void client.invalidateQueries({ queryKey: queryKeys.issues.list(companyId!) }); },
});
- const error = tasks.error ?? agents.error ?? projects.error ?? directory.error ?? labels.error ?? unread.error ?? update.error;
+ const error = (tasks.isFetchNextPageError ? null : tasks.error) ?? agents.error ?? projects.error ?? directory.error ?? labels.error ?? unread.error ?? update.error;
const empty = collection.companyItems.length === 0
? openNewIssue()} />
: ;
@@ -102,7 +103,9 @@ export function DesignSandboxTasks() {
{collection.narrowed ? {collection.matchingItems.length} matching tasks{collection.layout === "list" && collection.visibleItems.length > collection.matchingItems.length ? " · Parent tasks included for context" : ""}
: null}
{collection.layout === "board" ? collection.matchingItems.length ? item.issue)} agents={agents.data} onUpdateIssue={(id, data) => update.mutate({ id, data })} /> : empty : null}
- {tasks.hasNextPage ? Search, views and filters cover the {items.length} loaded tasks.
: null}
+ { if (!tasks.isFetching) void tasks.fetchNextPage({ cancelRefetch: false }); }}
+ autoLoad={!collection.query && collection.activeFilterCount === 0} />
>}
;
}
diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsx
index 17b2207a093..0ad400ac917 100644
--- a/ui/src/pages/Inbox.tsx
+++ b/ui/src/pages/Inbox.tsx
@@ -11,7 +11,7 @@ import { IssueRowDetailsNotice } from "../components/IssueRowDetailsNotice";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocation, useNavigate } from "@/lib/router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
-import { deriveOriginatingActor, INBOX_MINE_ISSUE_STATUS_FILTER, isHeartbeatRunVisibleInMine } from "@paperclipai/shared";
+import { deriveOriginatingActor, isHeartbeatRunVisibleInMine } from "@paperclipai/shared";
import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling";
import { approvalsApi } from "../api/approvals";
import { accessApi } from "../api/access";
@@ -103,6 +103,9 @@ import { BlockedInboxView } from "../components/BlockedInboxView";
import { SwipeToArchive } from "../components/SwipeToArchive";
import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
import { Inbox as LegacyInbox } from "./LegacyInbox";
+import { useInboxTouchedIssues } from "../hooks/useInboxTouchedIssues";
+import { useInboxMineIssues } from "../hooks/useInboxMineIssues";
+import { TaskListPagination } from "../components/TaskListPagination";
import { StatusIcon } from "../components/StatusIcon";
import { cn } from "../lib/utils";
@@ -138,7 +141,7 @@ import {
} from "lucide-react";
import { Input } from "@/components/ui/input";
import { PageTabBar } from "../components/PageTabBar";
-import type { Approval, HeartbeatRun, InboxMineSnapshot, Issue, JoinRequest } from "@paperclipai/shared";
+import type { Approval, HeartbeatRun, Issue, JoinRequest } from "@paperclipai/shared";
import {
ACTIONABLE_APPROVAL_STATUSES,
DEFAULT_INBOX_ISSUE_COLUMNS,
@@ -208,7 +211,6 @@ import {
import { taskStatusIconProps } from "@/lib/task-status-presentation";
const INBOX_HEARTBEAT_RUN_LIMIT = 200;
-const INBOX_ISSUE_LIST_LIMIT = 100;
const INBOX_HOT_PATH_STALE_MS = 30_000;
// Stable fallback so memos over unloaded or disabled issue reads do not rerun on every render.
const NO_ISSUES: Issue[] = [];
@@ -924,8 +926,8 @@ function StreamlinedInbox({
});
const currentUserId = session?.user.id ?? session?.session.userId ?? null;
const canArchiveTaskFromTab = canArchiveFromTab || (isTasksUnread && !!currentUserId);
- const mineContextQueryKey = [...queryKeys.issues.list(selectedCompanyId!), "mine-context", currentUserId] as const;
- const { data: mineSnapshot } = useQuery({ queryKey: mineContextQueryKey, enabled: false });
+ const minePages = useInboxMineIssues({ companyId: selectedCompanyId, userId: currentUserId, enabled: tab === "mine" });
+ const { snapshot: mineSnapshot } = minePages;
// On a returning visit the saved query cache restores Mine's snapshot and the
// approvals, join requests and dismissals it showed. Those stand in until the
// reads answer, so rows show without waiting on the network.
@@ -1067,67 +1069,21 @@ function StreamlinedInbox({
});
usePublishSharedQueryData(sharedDashboard, dashboard, dashboardUpdatedAt);
- const mineIssuesQuery = useQuery({
- queryKey: [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId] as const,
- queryFn: async ({ signal }) => {
- const snapshot = await issuesApi.inboxMine(selectedCompanyId!, { signal });
- if (snapshot.userId !== currentUserId) {
- void queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
- throw new ApiError("Your account changed. Refresh the inbox.", 409, { error: "account_changed" });
- }
- queryClient.setQueryData(mineContextQueryKey, snapshot);
- return snapshot.issues as Issue[];
- },
- enabled: !!selectedCompanyId && !!currentUserId && tab === "mine",
- refetchOnMount: mineSnapshot ? undefined : "always",
- refetchOnWindowFocus: false,
- staleTime: mineSnapshot ? INBOX_HOT_PATH_STALE_MS : 0,
- // A successful aggregate can still omit a failed source. React Query's
- // error retries do not run for that 200 response, so retry those sources.
- refetchInterval: () => {
- const snapshot = queryClient.getQueryData(mineContextQueryKey);
- return [snapshot?.failureError, snapshot?.contextError].some(error =>
- error && isTransientError(new ApiError(error.message, error.status, null))) ? 5_000 : false;
- },
- });
- const { data: mineIssuesRaw = NO_ISSUES, isLoading: isMineIssuesLoading, error: mineIssuesError } = mineIssuesQuery;
+ const { issues: mineIssuesRaw, query: mineIssuesQuery, queryKey: mineIssuesQueryKey } = minePages;
+ const { isLoading: isMineIssuesLoading, error: mineIssuesError } = mineIssuesQuery;
const mineIssuesView = useQueryView(mineIssuesQuery);
- const mineIssuesQueryKey = [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId] as const;
- // Mine owns one coherent response: broadcasting only its task array would
- // refresh that array while another tab retained stale parent/failure context.
- // Each tab uses the authenticated aggregate read; the server coalesces it.
- const touchedIssuesQueryKey = [
- ...(isTasksUnread ? queryKeys.issues.listUnreadTouchedByMe(selectedCompanyId!) : queryKeys.issues.listTouchedByMe(selectedCompanyId!)),
- "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId,
- ] as const;
- const touchedIssuesQuery = useQuery({
- queryKey: touchedIssuesQueryKey,
- queryFn: () =>
- issuesApi.listCompact(selectedCompanyId!, {
- touchedByUserId: "me",
- inboxArchivedByUserId: isTasksUnread ? "me" : undefined,
- status: INBOX_MINE_ISSUE_STATUS_FILTER,
- projection: "index",
- sortField: "updated",
- sortDir: "desc",
- includeRoutineExecutions: true,
- includeLiveDescendantSummary: true,
- limit: INBOX_ISSUE_LIST_LIMIT,
- }).then((rows) => rows as Issue[]),
- enabled: !!selectedCompanyId && (tab !== "mine" && tab !== "blocked" || normalizedSearchQuery.length > 0),
- refetchOnWindowFocus: false,
- staleTime: INBOX_HOT_PATH_STALE_MS,
- });
- const { data: touchedIssuesRaw = NO_ISSUES, isLoading: isTouchedIssuesLoading, error: touchedIssuesError, dataUpdatedAt: touchedIssuesUpdatedAt } = touchedIssuesQuery;
- const touchedIssuesView = useQueryView(touchedIssuesQuery);
- const sharedTouchedIssues = useSharedPollingQuery({
+ const touchedPages = useInboxTouchedIssues({
companyId: selectedCompanyId,
- resourceKey: isTasksUnread ? "inbox:unread-touched-issues" : "inbox:touched-issues",
- queryKey: touchedIssuesQueryKey,
+ userId: currentUserId,
+ hideArchived: isTasksUnread,
enabled: !!selectedCompanyId && (tab !== "mine" && tab !== "blocked" || normalizedSearchQuery.length > 0),
+ unreadOnly: tab === "unread",
});
- usePublishSharedQueryData(sharedTouchedIssues, touchedIssuesRaw, touchedIssuesUpdatedAt);
+ const taskPages = tab === "mine" ? minePages : touchedPages;
+ const { issues: touchedIssuesRaw } = touchedPages;
+ const { isLoading: isTouchedIssuesLoading, error: touchedIssuesError } = touchedPages.query;
+ const touchedIssuesView = useQueryView(touchedPages.query);
const { data: otherHeartbeatRuns, isLoading: isOtherRunsLoading, error: otherRunsError } = useQuery({
queryKey: [...queryKeys.heartbeats(selectedCompanyId!), "inbox-failures", INBOX_HEARTBEAT_RUN_LIMIT],
@@ -3660,6 +3616,12 @@ function StreamlinedInbox({
>
)}
+ {tab !== "blocked" && allLoaded && !listError && (tab !== "all" || showTouchedCategory) && (
+
+ )}
+
{allLoaded && !listError && showAlertsSection && (
<>
{showSeparatorBefore("alerts") && }
diff --git a/ui/src/pages/Issues.tsx b/ui/src/pages/Issues.tsx
index 45b36c7d12d..3ac8ffc0b6a 100644
--- a/ui/src/pages/Issues.tsx
+++ b/ui/src/pages/Issues.tsx
@@ -314,6 +314,7 @@ function OrganizationIssues({
includeAgentCreatedTasks,
originKind,
"infinite",
+ syncedSearch.trim(),
issuePageSize,
serverSortField,
serverSortDir,
@@ -324,6 +325,7 @@ function OrganizationIssues({
],
queryFn: ({ pageParam, signal }) => issuesApi.listCompact(selectedCompanyId!, {
projection: streamlinedUiEnabled ? "index" : undefined,
+ q: syncedSearch.trim() || undefined,
participantAgentId,
inboxArchive,
workspaceId: workspaceIdFilter,
@@ -346,13 +348,12 @@ function OrganizationIssues({
});
const { data: issuePages, isFetchingNextPage, hasNextPage, fetchNextPage } = issuesQuery;
- const issuesView = useQueryView(issuesQuery);
+ const issuesView = useQueryView({ ...issuesQuery, ...(issuesQuery.isFetchNextPageError ? { error: null, status: "success" as const } : {}) });
// The task list is loaded once its first page of rows has rendered.
usePageContentReady(!selectedCompanyId || (issuesView.kind !== "loading" && issuesView.kind !== "reconnecting"));
const issues = useMemo(() => mergeIssuePagesStable(issuePages?.pages ?? []) as Issue[], [issuePages]);
const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns, issues), [issues, liveRuns]);
- const hasMoreServerIssues = syncedSearch.trim().length === 0
- && hasNextPage === true;
+ const hasMoreServerIssues = hasNextPage === true;
const loadMoreServerIssues = useCallback(() => {
if (!hasNextPage || isFetchingNextPage || fetchNextPageInFlightRef.current) return;
fetchNextPageInFlightRef.current = true;
@@ -387,6 +388,7 @@ function OrganizationIssues({
issues={issues ?? []}
getArchiveAction={getArchiveAction}
preloadTaskChats
+ pagedIssuesProvided
isLoading={issuesView.kind === "loading" || issuesView.kind === "reconnecting"}
isLoadingMoreIssues={isFetchingNextPage}
agents={agents}
@@ -410,8 +412,10 @@ function OrganizationIssues({
onUpdatedBeforeChange={setUpdatedBefore}
updatedFilter={updatedFilter}
onUpdatedFilterChange={handleUpdatedFilterChange}
- hasMoreIssues={hasMoreServerIssues}
- onLoadMoreIssues={loadMoreServerIssues}
+ hasMoreIssues={hasMoreServerIssues && !issuesQuery.isFetchNextPageError}
+ onLoadMoreIssues={issuesQuery.isFetchNextPageError ? undefined : loadMoreServerIssues}
+ loadMoreIssuesError={issuesQuery.isFetchNextPageError ? issuesQuery.error : null}
+ onRetryLoadMoreIssues={loadMoreServerIssues}
onUpdateIssue={(id, data) => updateIssue.mutate({ id, data })}
searchFilters={participantAgentId || workspaceIdFilter || originKind || includeBlockedBy || inboxArchive || updatedBefore ? {
participantAgentId, workspaceId: workspaceIdFilter, originKind, inboxArchive, updatedBefore,
diff --git a/ui/src/pages/LegacyInbox.tsx b/ui/src/pages/LegacyInbox.tsx
index 2b72e0c7353..f9bf41a4cb3 100644
--- a/ui/src/pages/LegacyInbox.tsx
+++ b/ui/src/pages/LegacyInbox.tsx
@@ -14,6 +14,8 @@ import { ApiError } from "../api/client";
import { dashboardApi } from "../api/dashboard";
import { executionWorkspacesApi } from "../api/execution-workspaces";
import { issuesApi } from "../api/issues";
+import { useIssueListPages } from "../hooks/useIssueListPages";
+import { TaskListPagination } from "../components/TaskListPagination";
import { agentsApi } from "../api/agents";
import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
@@ -862,23 +864,19 @@ export function Inbox() {
const { data: issues, isLoading: isIssuesLoading, dataUpdatedAt: issuesUpdatedAt } = inboxIssuesQuery;
const inboxIssuesView = useQueryView(inboxIssuesQuery);
usePublishSharedQueryData(sharedInboxIssues, issues, issuesUpdatedAt);
+ const fetchMinePage = useCallback(async (offset: number, signal: AbortSignal) => await issuesApi.listCompact(selectedCompanyId!, {
+ touchedByUserId: "me", inboxArchivedByUserId: "me", status: INBOX_MINE_ISSUE_STATUS_FILTER,
+ includeRoutineExecutions: true, includeLiveDescendantSummary: true,
+ sortField: "updated", sortDir: "desc", limit: INBOX_ISSUE_LIST_LIMIT, offset,
+ }, { signal }) as Issue[], [selectedCompanyId]);
const mineIssuesQuery = useQuery({
queryKey: [...queryKeys.issues.listMineByMe(selectedCompanyId!), "compact", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const,
- queryFn: () =>
- issuesApi.listCompact(selectedCompanyId!, {
- touchedByUserId: "me",
- inboxArchivedByUserId: "me",
- status: INBOX_MINE_ISSUE_STATUS_FILTER,
- includeRoutineExecutions: true,
- includeLiveDescendantSummary: true,
- limit: INBOX_ISSUE_LIST_LIMIT,
- }).then((rows) => rows as Issue[]),
+ queryFn: ({ signal }) => fetchMinePage(0, signal),
enabled: !!selectedCompanyId,
refetchOnWindowFocus: false,
staleTime: INBOX_HOT_PATH_STALE_MS,
});
const {
- data: mineIssuesRaw = [],
isLoading: isMineIssuesLoading,
dataUpdatedAt: mineIssuesUpdatedAt,
} = mineIssuesQuery;
@@ -890,23 +888,25 @@ export function Inbox() {
queryKey: mineIssuesQueryKey,
enabled: !!selectedCompanyId,
});
- usePublishSharedQueryData(sharedMineIssues, mineIssuesRaw, mineIssuesUpdatedAt);
+ const minePages = useIssueListPages({ queryKey: mineIssuesQueryKey, query: mineIssuesQuery,
+ enabled: !!selectedCompanyId && tab === "mine", pageSize: INBOX_ISSUE_LIST_LIMIT,
+ fetchPage: fetchMinePage,
+ });
+ const { issues: mineIssuesRaw } = minePages;
+ usePublishSharedQueryData(sharedMineIssues, mineIssuesQuery.data, mineIssuesUpdatedAt);
+ const fetchTouchedPage = useCallback(async (offset: number, signal: AbortSignal) => await issuesApi.listCompact(selectedCompanyId!, {
+ touchedByUserId: "me", status: INBOX_MINE_ISSUE_STATUS_FILTER,
+ includeRoutineExecutions: true, includeLiveDescendantSummary: true,
+ sortField: "updated", sortDir: "desc", limit: INBOX_ISSUE_LIST_LIMIT, offset,
+ }, { signal }) as Issue[], [selectedCompanyId]);
const touchedIssuesQuery = useQuery({
queryKey: [...queryKeys.issues.listTouchedByMe(selectedCompanyId!), "compact", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const,
- queryFn: () =>
- issuesApi.listCompact(selectedCompanyId!, {
- touchedByUserId: "me",
- status: INBOX_MINE_ISSUE_STATUS_FILTER,
- includeRoutineExecutions: true,
- includeLiveDescendantSummary: true,
- limit: INBOX_ISSUE_LIST_LIMIT,
- }).then((rows) => rows as Issue[]),
+ queryFn: ({ signal }) => fetchTouchedPage(0, signal),
enabled: !!selectedCompanyId,
refetchOnWindowFocus: false,
staleTime: INBOX_HOT_PATH_STALE_MS,
});
const {
- data: touchedIssuesRaw = [],
isLoading: isTouchedIssuesLoading,
dataUpdatedAt: touchedIssuesUpdatedAt,
} = touchedIssuesQuery;
@@ -918,7 +918,13 @@ export function Inbox() {
queryKey: touchedIssuesQueryKey,
enabled: !!selectedCompanyId,
});
- usePublishSharedQueryData(sharedTouchedIssues, touchedIssuesRaw, touchedIssuesUpdatedAt);
+ const touchedPages = useIssueListPages({ queryKey: touchedIssuesQueryKey, query: touchedIssuesQuery,
+ enabled: !!selectedCompanyId && tab !== "mine" && tab !== "blocked", pageSize: INBOX_ISSUE_LIST_LIMIT,
+ fetchPage: fetchTouchedPage,
+ });
+ const { issues: touchedIssuesRaw } = touchedPages;
+ const taskPages = tab === "mine" ? minePages : touchedPages;
+ usePublishSharedQueryData(sharedTouchedIssues, touchedIssuesQuery.data, touchedIssuesUpdatedAt);
const heartbeatRunsQuery = useQuery({
queryKey: [...queryKeys.heartbeats(selectedCompanyId!), "limit", INBOX_HEARTBEAT_RUN_LIMIT],
@@ -3127,6 +3133,12 @@ export function Inbox() {
>
)}
+ {tab !== "blocked" && allLoaded && (tab !== "all" || showTouchedCategory) && (
+
+ )}
+
{showAlertsSection && (
<>
{showSeparatorBefore("alerts") && }
diff --git a/ui/src/pages/TaskListPagination.test.tsx b/ui/src/pages/TaskListPagination.test.tsx
new file mode 100644
index 00000000000..eb4f66a898b
--- /dev/null
+++ b/ui/src/pages/TaskListPagination.test.tsx
@@ -0,0 +1,230 @@
+// @vitest-environment jsdom
+import { act, useEffect, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { Issue } from "@paperclipai/shared";
+import { queryKeys } from "@/lib/queryKeys";
+import { Inbox } from "./Inbox";
+import { defaultIssueFilterState } from "@/lib/issue-filters";
+import { CoordinatorTasks } from "./CoordinatorTasks";
+import { Issues } from "./Issues";
+import { BlockedInboxView } from "@/components/BlockedInboxView";
+import { TaskListPagination } from "@/components/TaskListPagination";
+
+const api = vi.hoisted(() => ({ compact: vi.fn(), inboxMine: vi.fn(), list: vi.fn(), taskIndex: vi.fn(), agents: vi.fn(), projects: vi.fn(), directory: vi.fn(), labels: vi.fn() }));
+const route = vi.hoisted(() => ({ params: new URLSearchParams("view=all"), navigate: vi.fn(), setParams: vi.fn(), setBreadcrumbs: vi.fn(), autoScroll: false, streamlined: false, pathname: "/issues" }));
+vi.mock("@/api/issues", () => ({ issuesApi: { listCompact: api.compact, inboxMine: api.inboxMine, list: api.list, listLabels: api.labels } }));
+vi.mock("@/api/attention", () => ({ attentionApi: { taskIndex: api.taskIndex } }));
+vi.mock("@/api/agents", () => ({ agentsApi: { list: api.agents } }));
+vi.mock("@/api/projects", () => ({ projectsApi: { list: api.projects } }));
+vi.mock("@/api/access", () => ({ accessApi: { listUserDirectory: api.directory } }));
+vi.mock("@/context/ToastContext", () => ({ useToastActions: () => ({ pushToast: vi.fn() }) }));
+vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false }) }));
+vi.mock("@/hooks/useAccountBoundMutation", () => ({ useAccountBoundMutation: () => ({ mutate: vi.fn(), reset: vi.fn(), isPending: false, error: null }) }));
+vi.mock("@/hooks/usePreloadTaskChats", async importOriginal => ({ ...await importOriginal(), usePreloadTaskChats: () => {} }));
+vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company-1" }) }));
+vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: route.setBreadcrumbs }) }));
+vi.mock("@/context/DialogContext", () => ({ useDialogActions: () => ({ openNewIssue: () => {} }) }));
+vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ userId: "user-1", loaded: true }) }));
+vi.mock("@/hooks/useStreamlinedUiEnabled", () => ({ useStreamlinedUiEnabled: () => ({ enabled: route.streamlined }) }));
+vi.mock("@/hooks/useCombinedInboxTasksEnabled", () => ({ useCombinedInboxTasksEnabled: () => ({ enabled: false }) }));
+vi.mock("@/hooks/useShowAgentCreatedTasks", () => ({ useShowAgentCreatedTasks: () => false }));
+vi.mock("@/hooks/usePageContentReady", () => ({ usePageContentReady: () => {} }));
+vi.mock("@/context/DesignSandboxContext", () => ({ useDesignSandbox: () => false }));
+vi.mock("@/hooks/useWarmTaskDetailCode", () => ({ useWarmTaskDetailCode: () => {} }));
+vi.mock("@/hooks/useUpdateIssueMutation", () => ({ useUpdateIssueMutation: () => ({ mutate: vi.fn() }) }));
+vi.mock("@/hooks/useTaskArchiveAction", () => ({ useTaskArchiveAction: () => () => undefined }));
+vi.mock("@/hooks/useTaskCancellation", () => ({ useTaskCancellation: () => vi.fn(), TaskCancellationDismissedError: class extends Error {} }));
+vi.mock("@/hooks/useIssueRowDetails", () => ({ useIssueRowDetails: () => ({ enrichIssueRow: (issue: Issue) => issue }) }));
+vi.mock("@/hooks/useSharedPolling", () => ({ useSharedPollingQuery: () => ({ enabled: false }), usePublishSharedQueryData: () => {} }));
+vi.mock("@/lib/router", () => ({
+ useSearchParams: () => [route.params, route.setParams], useNavigate: () => route.navigate,
+ useLocation: () => ({ pathname: route.pathname, search: `?${route.params}`, hash: "" }),
+ Link: ({ children }: { children: ReactNode }) => {children},
+}));
+vi.mock("@/components/TaskList", async importOriginal => ({ ...await importOriginal(), TaskList: ({ items }: { items: { issue: Issue }[] }) => <>{items.map(({ issue }) => {issue.title})}> }));
+vi.mock("@/components/TaskListToolbar", () => ({ TaskListToolbar: () => null }));
+vi.mock("@/components/IssuesList", () => ({ IssuesList: ({ issues, pagedIssuesProvided, hasMoreIssues, isLoadingMoreIssues, onLoadMoreIssues, loadMoreIssuesError, onRetryLoadMoreIssues }: {
+ issues: Issue[]; pagedIssuesProvided: boolean; hasMoreIssues?: boolean; isLoadingMoreIssues?: boolean; onLoadMoreIssues?: () => void;
+ loadMoreIssuesError?: unknown; onRetryLoadMoreIssues?: () => void;
+}) => {
+ useEffect(() => {
+ if (route.autoScroll && hasMoreIssues && !isLoadingMoreIssues) onLoadMoreIssues?.();
+ }, [hasMoreIssues, isLoadingMoreIssues, onLoadMoreIssues]);
+ return {issues.map(issue => {issue.title})}
+ (onRetryLoadMoreIssues ?? onLoadMoreIssues)?.()} autoLoad={false} />
+
;
+} }));
+vi.mock("@/components/KanbanBoard", () => ({ KanbanBoard: () => null }));
+vi.mock("@/components/TruncatedText", () => ({ TruncatedTextMarqueeProvider: ({ children }: { children: ReactNode }) => children }));
+vi.mock("@/components/ui/flyout", () => ({ FlyoutAppearanceProvider: ({ children }: { children: ReactNode }) => children }));
+vi.mock("@/components/IssueRow", () => ({ IssueRow: ({ issue }: { issue: Issue }) => {issue.title} }));
+vi.mock("@/components/QueryView", () => ({ useQueryView: (query: { data?: unknown; error?: unknown; refetch: unknown }) => ({
+ kind: query.error ? "error" : query.data ? "ready" : "loading", error: query.error, retry: query.refetch,
+}) }));
+
+let client: QueryClient;
+let root: Root;
+let container: HTMLDivElement;
+let createIssue: typeof import("../../storybook/fixtures/paperclipData").createIssue;
+const rows = () => container.querySelectorAll("[data-task]");
+const more = () => [...container.querySelectorAll("button")].find(button => /Load more tasks|Retry loading tasks/.test(button.textContent ?? ""));
+const render = (children: ReactNode) => act(async () => root.render({children}));
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ vi.stubGlobal("IntersectionObserver", class { observe() {} disconnect() {} });
+ ({ createIssue } = await vi.importActual("../../storybook/fixtures/paperclipData"));
+ route.params = new URLSearchParams("view=all");
+ route.autoScroll = false;
+ route.streamlined = false;
+ route.pathname = "/issues";
+ api.agents.mockResolvedValue([]); api.projects.mockResolvedValue([]); api.directory.mockResolvedValue({ users: [] }); api.labels.mockResolvedValue([]);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ container = document.createElement("div");
+ root = createRoot(container);
+});
+afterEach(async () => { await act(async () => root.unmount()); client.clear(); vi.unstubAllGlobals(); });
+
+it.each(["all", "active", "backlog", "done", "archived"])("keeps the %s organization view paginated", async view => {
+ route.params = new URLSearchParams(`view=${view}`);
+ const status = view === "backlog" ? "backlog" : view === "done" || view === "archived" ? "done" : "todo";
+ const tasks = Array.from({ length: 203 }, (_, index) => createIssue({ id: `task-${index}`, companyId: "company-1", title: `Task ${index}`, status }));
+ api.compact.mockImplementation(async (_company, filters) => tasks.slice(filters.offset, filters.offset + filters.limit));
+ await render();
+ await vi.waitFor(() => expect(rows()).toHaveLength(200));
+ await act(async () => more()!.click());
+ await vi.waitFor(() => expect(rows()).toHaveLength(203));
+ expect(more()).toBeUndefined();
+ expect(api.compact.mock.calls.map(([, filters]) => filters.offset)).toEqual([0, 200]);
+});
+
+it("loads Needs attention in bounded ID pages without hiding readable rows", async () => {
+ route.params = new URLSearchParams("view=needs_attention");
+ const tasks = Array.from({ length: 215 }, (_, index) => createIssue({ id: `task-${index}`, companyId: "company-1", title: `Task ${index}` }));
+ const byId = new Map(tasks.map(task => [task.id, task]));
+ api.taskIndex.mockResolvedValue({ taskIds: [...byId.keys()] });
+ let finishPage!: (issues: Issue[]) => void;
+ let failLastPage = true;
+ let requestedIds = 0;
+ api.compact.mockImplementation(async (_company, filters) => {
+ requestedIds += filters.ids.length;
+ if (filters.ids.length > 100 || requestedIds > tasks.length + 15) throw new Error("Attention task paging exceeded its ID work limit");
+ if (filters.ids[0] === "task-100") return new Promise(resolve => { finishPage = resolve; });
+ if (filters.ids[0] === "task-200" && failLastPage) { failLastPage = false; throw new Error("last page failed"); }
+ return filters.ids.map((id: string) => byId.get(id));
+ });
+ await render();
+ await vi.waitFor(() => expect(rows()).toHaveLength(100));
+ expect(api.compact).toHaveBeenCalledTimes(1);
+ await act(async () => more()!.click());
+ expect(rows()).toHaveLength(100);
+ await act(async () => finishPage(tasks.slice(100, 200)));
+ await vi.waitFor(() => expect(rows()).toHaveLength(200));
+ await act(async () => more()!.click());
+ await vi.waitFor(() => expect(more()?.textContent).toBe("Retry loading tasks"));
+ expect(rows()).toHaveLength(200);
+ await act(async () => more()!.click());
+ await vi.waitFor(() => expect(rows()).toHaveLength(215));
+ expect(api.compact.mock.calls.map(([, filters]) => filters.ids.length)).toEqual([100, 100, 15, 15]);
+ expect(more()).toBeUndefined();
+});
+
+it.each(["", "Task 204"])("paginates Blocked while filtering by %j", async searchQuery => {
+ const tasks = Array.from({ length: 205 }, (_, index) => createIssue({ id: `task-${index}`, companyId: "company-1", title: `Task ${index}`,
+ blockedInboxAttention: { kind: "blocked", state: "needs_attention", reason: "blocked_chain_stalled", severity: "medium",
+ stoppedSinceAt: "2026-11-01T00:00:00Z", owner: { type: "agent", agentId: null, userId: null, label: "QA" },
+ action: { label: "Resolve task", detail: null }, sourceIssue: null, leafIssue: null, recoveryIssue: null,
+ approvalId: null, interactionId: null, sampleIssueIdentifier: null,
+ redaction: { externalDetailsRedacted: false, secretFieldsOmitted: true } },
+ }));
+ api.list.mockImplementation(async (_company, filters) => tasks.slice(filters.offset, filters.offset + filters.limit));
+ await render();
+ await vi.waitFor(() => expect(more()).toBeDefined());
+ expect(rows()).toHaveLength(searchQuery ? 0 : 200);
+ await act(async () => more()!.click());
+ await vi.waitFor(() => expect(rows()).toHaveLength(searchQuery ? 1 : 205));
+ expect(more()).toBeUndefined();
+ expect(api.list.mock.calls.map(([, filters]) => filters.offset)).toEqual([0, 200]);
+});
+
+it("keeps the classic Tasks view and server search paginated", async () => {
+ route.params = new URLSearchParams("view=all&q=comment-only-match");
+ const tasks = Array.from({ length: 105 }, (_, index) => createIssue({ id: `task-${index}`, companyId: "company-1", title: `Task ${index}` }));
+ api.compact.mockImplementation(async (_company, filters) => tasks.slice(filters.offset, filters.offset + filters.limit));
+ await render();
+ await vi.waitFor(() => expect(rows()).toHaveLength(100));
+ expect(container.querySelector('[data-paged="true"]')).not.toBeNull();
+ await act(async () => more()!.click());
+ await vi.waitFor(() => expect(rows()).toHaveLength(105));
+ expect(api.compact.mock.calls.map(([, filters]) => [filters.offset, filters.q])).toEqual([[0, "comment-only-match"], [100, "comment-only-match"]]);
+ expect(more()).toBeUndefined();
+});
+
+it.each([false, true])("waits for manual retry after automatic paging fails with streamlined=%s", async streamlined => {
+ route.streamlined = streamlined;
+ route.autoScroll = true;
+ const tasks = Array.from({ length: 105 }, (_, index) => createIssue({ id: `task-${index}`, companyId: "company-1", title: `Task ${index}` }));
+ let laterPageAttempts = 0;
+ api.compact.mockImplementation(async (_company, filters) => {
+ if (filters.offset === 100 && ++laterPageAttempts === 1) throw new Error("page failed");
+ return tasks.slice(filters.offset, filters.offset + filters.limit);
+ });
+ await render();
+ await vi.waitFor(() => expect(more()?.textContent).toBe("Retry loading tasks"));
+ expect(rows()).toHaveLength(100);
+ expect(api.compact).toHaveBeenCalledTimes(2);
+ await render();
+ expect(api.compact).toHaveBeenCalledTimes(2);
+ await act(async () => more()!.click());
+ await vi.waitFor(() => expect(rows()).toHaveLength(105));
+ expect(api.compact.mock.calls.map(([, filters]) => filters.offset)).toEqual([0, 100, 100]);
+ expect(more()).toBeUndefined();
+});
+
+
+it.each([
+ { streamlined: false, tab: "mine" }, { streamlined: true, tab: "mine" },
+ { streamlined: false, tab: "recent" }, { streamlined: true, tab: "recent" },
+ { streamlined: true, tab: "unread" },
+] as const)("loads later task pages through the real Inbox (%j)", async ({ streamlined, tab }) => {
+ route.streamlined = streamlined;
+ route.pathname = `/inbox/${tab}`;
+ const pageSize = streamlined ? 100 : 500;
+ const tasks = Array.from({ length: pageSize + 3 }, (_, index) => createIssue({
+ id: `task-${index}`, companyId: "company-1", title: `Task ${index}`, parentId: null,
+ }));
+ client.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } });
+ client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" }, session: { userId: "user-1" } });
+ client.setQueryData(queryKeys.instance.experimentalSettings, { enableIsolatedWorkspaces: false, enableExternalObjects: false });
+ for (const key of [queryKeys.agents.list("company-1"), queryKeys.projects.list("company-1", { includeArchived: true }),
+ queryKeys.issues.labels("company-1"), queryKeys.approvals.list("company-1"), queryKeys.access.joinRequests("company-1"),
+ queryKeys.inboxDismissals("company-1"), queryKeys.liveRuns("company-1"),
+ [...queryKeys.heartbeats("company-1"), streamlined ? "inbox-failures" : "limit", 200],
+ ]) client.setQueryData(key, []);
+ client.setQueryData(queryKeys.access.companyUserDirectory("company-1"), { users: [] });
+ client.setQueryData(queryKeys.dashboard("company-1"), { agents: { error: 0 }, costs: { monthBudgetCents: 0, monthUtilizationPercent: 0 } });
+ api.inboxMine.mockResolvedValue({ userId: "user-1", issues: tasks.slice(0, pageSize), contextIssues: [], failureRuns: [], failureIssueIds: [] });
+ api.compact.mockImplementation(async (_company, filters) => filters.touchedByUserId
+ ? tasks.slice(filters.offset ?? 0, (filters.offset ?? 0) + filters.limit) : []);
+ await render();
+ await vi.waitFor(() => expect(rows()).toHaveLength(pageSize));
+ await vi.waitFor(() => expect(more()).toBeDefined());
+ await act(async () => more()!.click());
+ await vi.waitFor(() => expect(rows()).toHaveLength(pageSize + 3));
+ expect(more()).toBeUndefined();
+ const laterPage = api.compact.mock.calls.find(([, filters]) => filters.offset === pageSize)?.[1];
+ expect(laterPage).toMatchObject({ touchedByUserId: "me", offset: pageSize, limit: pageSize });
+ expect(laterPage.inboxArchivedByUserId).toBe(tab === "mine" ? "me" : undefined);
+ expect(laterPage.unreadForUserId).toBe(tab === "unread" ? "me" : undefined);
+ if (!streamlined || tab !== "mine") {
+ const firstPage = api.compact.mock.calls.find(([, filters]) => filters.touchedByUserId && filters.inboxArchivedByUserId === laterPage.inboxArchivedByUserId && (filters.offset ?? 0) === 0)?.[1];
+ expect({ ...firstPage, offset: pageSize }).toEqual(laterPage);
+ }
+});