fix(ui): paginate all task-list views (#23564)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Its task lists help people find and manage work across personal and
organization views.
> - Several personal views stop after 100 tasks, and Blocked stops after
200 tasks.
> - Other lists have page reads but lack a consistent way to load more
or retry a failed page.
> - This pull request makes pagination available across every task-list
view.
> - People can reach older tasks, keep filters active, and retry without
losing readable rows.

## Linked Issues or Issue Description

**What happened?**
Task lists have inconsistent pagination. Mine, Recent, and Unread stop
at the first task batch. Blocked stops at 200 tasks. Everything has the
same missing-page behavior before this PR. Some organization layouts and
searches replace paged rows with separate capped queries.

**Expected behavior**
Every task-list view can load its remaining tasks. A failed later page
keeps loaded tasks visible and offers a retry.

**Steps to reproduce**
1. Use a company and account with more tasks than a view's first batch.
2. Open Mine, Recent, Unread, Everything, or Blocked and scroll to the
bottom.
3. Try to reach older tasks. The affected views stop without a next-page
control.
4. Check organization status views, Archived, search, and board layouts
for consistent loading controls.

**Paperclip version or commit**
The affected code is present at base commit
`53bebb59f907571228dfb85a834a38536f934aa6`.

**Deployment mode**
Observed on hosted staging. Verified locally from source on macOS arm64.

GitHub searches found no duplicate open PR or directly matching issue.

## What Changed

- Apply one task pagination control to personal, organization, status,
archive, classic, and sandbox task lists.
- Make Recent, Unread, and Everything page through touched tasks. Remove
the shared 100-task display cutoff.
- Filter unread tasks on the server before paging.
- Keep Mine's coherent initial snapshot. Fetch older task pages through
the existing authorized list API.
- Add older pages to Blocked. Load Needs attention task details in
batches from its existing task index.
- Let the Tasks route supply paged search and board data to the shared
list components, so separate capped queries cannot replace loaded pages.
- Keep loaded rows visible during later-page loading and errors. Keep
the retry control available when the final attention page fails.
- Pause the classic and streamlined lists' automatic server-page reads
after a later-page error. Keep an explicit retry button available to
restart that page.
- Keep one paging and retry control inside each task-list component for
list and board layouts.
- Reuse the same request filters for the first and later Legacy Inbox
pages.
- Preserve the array cache contract for archive rollback, live updates,
and sharing the first page across tabs.
- Update product documentation and cover the additional views with
regression tests.

## Verification

- Revision: `9275d37c06dc14d00b6759ad71fb6402252db84b`, based on
`origin/master` at `53bebb59f907571228dfb85a834a38536f934aa6`.
- Environment: macOS arm64, Node v25.6.1, pnpm 9.15.4.
- From `ui/`, ran `pnpm exec vitest run
src/components/IssuesList.paging.test.tsx
src/pages/TaskListPagination.test.tsx src/pages/Issues.test.tsx
src/hooks/useInboxTouchedIssues.test.tsx src/lib/inbox.test.ts
src/lib/blockedInbox.test.ts src/lib/inboxArchiveCache.test.ts
src/lib/inboxOrderPin.test.ts src/hooks/useSharedPolling.test.ts
src/hooks/useSharedPollingSnapshot.test.tsx
src/hooks/useTaskListCollection.test.tsx`: all 133 tests passed across
11 files.
- Real IssuesList tests cover both UI modes. They verify that provided
board and search pages stay visible, capped column and search queries do
not run, and each layout has one paging and retry control. Only leaf row
and board rendering are stubbed.
- Real Inbox page tests load later Mine and Recent pages in both UI
modes. They also check Unread's server filter, first-page and later-page
filter agreement, and removal of the control after the last page.
- Page tests cover All tasks, Active, Backlog, Done, Archived, Needs
attention, Blocked, and classic Tasks with server search. Supporting UI
services and row rendering are isolated.
- Red-green regressions proved the old 100-task display cutoff and
automatic retries after a failed page. The fixed lists keep readable
rows and require an explicit retry after failure.
- The work-limit test uses 500 full task fixtures across five pages. A
deterministic counter throws above a linear task-ID read budget. Ten
unchanged rerenders per page perform no collection work.
- Tests also cover page overlap, duplicate observer events, last-page
detection, loading and retry, account and company changes, archive
rollback, live invalidation, and the fallback without
IntersectionObserver.
- Ran `pnpm --dir ui typecheck`: passed.
- Ran `node scripts/check-test-budget.mjs --base origin/master`: passed
for all four changed test files.
- Ran `git diff --check origin/master...HEAD`: passed.
- A prior `pnpm verify` attempt selected 2,319 files and started a broad
server run. It was stopped to avoid duplicating broad CI for this UI
change. That interrupted attempt is not a pass.
- Full local build and browser acceptance of the modified pages were not
run. [Greptile passed with 5/5 on this
revision](https://github.com/paperclipai/paperclip/pull/23564#issuecomment-7362362373).
Both inline review threads are resolved. [CI
typecheck](https://github.com/paperclipai/paperclip/actions/runs/47004999629/job/143907916923)
and
[build](https://github.com/paperclipai/paperclip/actions/runs/47004999629/job/143907916990)
passed. [Both required CI checks passed on this
revision](https://github.com/paperclipai/paperclip/actions/runs/47004999629):
`ci / e2e` and `ci / verify`. No CI checks remain pending or failed.
Confirmation that automated design review has cleared the prior hold is
still pending.

## Risks

- Task updates can move rows between offset pages. The merge removes
duplicate task IDs, and live refreshes update loaded pages.
- Search and task filters cover loaded rows in personal views. Use Load
more tasks to include older rows while filters are active.
- Mine keeps the existing snapshot and access behavior. The change adds
no database migration or public API contract.

## Model Used

OpenAI `gpt-6.1-sol` through the Codex harness, with xhigh reasoning
effort and tool use.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-12-02 17:28:12 -08:00
1 parent 2a8a0b8e18
commit 2b65b97cae
18 files changed
+983 -160

No files matched your search

+22 -25
View File
@@ -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<Set<string>>(() => 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 = <TaskListPagination hasMore={pages.hasMore} isLoadingMore={pages.isLoadingMore}
error={pages.loadMoreError} loadMore={pages.loadMore}
autoLoad={!searchQuery.trim() && countActiveIssueFilters(issueFilters, true) === 0} />;
const blockedView = useQueryView(blockedQuery);
const allRows = useMemo(() => buildBlockedInboxRows(blockedIssues), [blockedIssues]);
@@ -192,7 +187,7 @@ export function BlockedInboxView({
if (allRows.length === 0) {
return (
<Card
<div className="space-y-3"><Card
data-testid="blocked-inbox-empty"
className="items-center gap-3 border-border/70 bg-card/40 px-6 py-10 text-center"
>
@@ -205,7 +200,7 @@ export function BlockedInboxView({
Tasks that need a decision, recovery, or external action will appear here.
</p>
</div>
</Card>
</Card>{pagination}</div>
);
}
@@ -218,6 +213,7 @@ export function BlockedInboxView({
>
No stopped items match your search.
</Card>
{pagination}
</div>
);
}
@@ -278,6 +274,7 @@ export function BlockedInboxView({
})
)}
</div>
{pagination}
</div>
);
}
@@ -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 }) => <a>{children}</a> }));
vi.mock("./IssueRow", async importOriginal => ({ ...await importOriginal<typeof import("./IssueRow")>(),
IssueRow: ({ issue }: { issue: Issue }) => <span data-task-row>{issue.title}</span>,
}));
vi.mock("./KanbanBoard", async importOriginal => ({ ...await importOriginal<typeof import("./KanbanBoard")>(),
KanbanBoard: ({ issues }: { issues: Issue[] }) => <div data-board>{issues.map(issue => <span key={issue.id} data-task-row>{issue.title}</span>)}</div>,
}));
let client: QueryClient;
let container: HTMLDivElement;
let root: Root;
let tasks: Issue[];
let listProps: Partial<ComponentProps<typeof IssuesList>>;
const titles = () => [...container.querySelectorAll("[data-task-row]")].map(row => row.textContent);
const render = (issues: Issue[], initialSearch = "", searchWithinLoadedIssues = false) => act(async () => root.render(
<QueryClientProvider client={client}><IssuesList issues={issues} agents={[]} projects={[]} viewStateKey="provided-pages"
onUpdateIssue={() => {}} pagedIssuesProvided initialSearch={initialSearch} searchWithinLoadedIssues={searchWithinLoadedIssues} {...listProps} /></QueryClientProvider>,
));
beforeEach(async () => {
vi.clearAllMocks();
listProps = {};
localStorage.clear();
const { createIssue } = await vi.importActual<typeof import("../../storybook/fixtures/paperclipData")>("../../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();
});
+32 -18
View File
@@ -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<IssueListRequestFilters, "q" | "projectId" | "limit" | "includeRoutineExecutions" | "sortField" | "sortDir">;
searchWithinLoadedIssues?: boolean;
pagedIssuesProvided?: boolean;
baseCreateIssueDefaults?: Record<string, unknown>;
createIssueLabel?: string;
defaultSortField?: IssueSortField;
@@ -510,6 +512,8 @@ interface IssuesListProps {
mutedIssueIds?: Set<string>;
issueBadgeById?: Map<string, string>;
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<string, Issue>();
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 = <TaskListPagination
hasMore={hasMoreIssues || (viewState.viewMode === "list" && (hasMoreRenderedRows || hasMoreHierarchyRows))}
isLoadingMore={isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)} error={loadMoreIssuesError}
loadMore={() => {
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({
</Collapsible>
);
})}
{(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues) && (
{(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues || Boolean(loadMoreIssuesError)) && (
<div className="py-2" data-testid="issues-load-more-sentinel">
<p className="text-xs text-muted-foreground">
{isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)
? "Loading more tasks..."
: remainingIssueRowCount > 0
? `Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`
: "Scroll to load more tasks"}
</p>
{remainingIssueRowCount > 0 && <p className="text-xs text-muted-foreground">
{`Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`}
</p>}
{pagination}
</div>
)}
</div>
))}
{viewState.viewMode === "board" && (hasMoreIssues || isLoadingMoreIssues || loadMoreIssuesError) ? pagination : null}
</div>
);
}
+32 -18
View File
@@ -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<IssueListRequestFilters, "q" | "projectId" | "limit" | "includeRoutineExecutions" | "sortField" | "sortDir">;
searchWithinLoadedIssues?: boolean;
pagedIssuesProvided?: boolean;
baseCreateIssueDefaults?: Record<string, unknown>;
createIssueLabel?: string;
defaultSortField?: IssueSortField;
@@ -488,6 +490,8 @@ interface IssuesListProps {
mutedIssueIds?: Set<string>;
issueBadgeById?: Map<string, string>;
onLoadMoreIssues?: () => void;
loadMoreIssuesError?: unknown;
onRetryLoadMoreIssues?: () => void;
onSearchChange?: (search: string) => void;
onUpdateIssue: (id: string, data: Record<string, unknown>) => 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<string, Issue>();
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 = <TaskListPagination
hasMore={hasMoreIssues || (viewState.viewMode === "list" && (hasMoreRenderedRows || hasMoreHierarchyRows))}
isLoadingMore={isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)} error={loadMoreIssuesError}
loadMore={() => {
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({
</Collapsible>
);
})}
{(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues) && (
{(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues || Boolean(loadMoreIssuesError)) && (
<div className="py-2" data-testid="issues-load-more-sentinel">
<p className="text-xs text-muted-foreground">
{isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)
? "Loading more tasks..."
: remainingIssueRowCount > 0
? `Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`
: "Scroll to load more tasks"}
</p>
{remainingIssueRowCount > 0 && <p className="text-xs text-muted-foreground">
{`Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`}
</p>}
{pagination}
</div>
)}
</>
))}
{viewState.viewMode === "board" && (hasMoreIssues || isLoadingMoreIssues || loadMoreIssuesError) ? pagination : null}
</div>
);
}
+30
View File
@@ -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<HTMLDivElement>(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 <div ref={sentinel} className="flex flex-wrap items-center gap-3 py-2 text-sm text-muted-foreground">
{error ? <p role="alert">Couldn’t load more tasks. {describeError(error).body}</p> : null}
{isLoadingMore ? <p role="status">Loading more tasks…</p> : null}
<Button variant="outline" size="sm" disabled={isLoadingMore} onClick={loadMore}>
{isLoadingMore ? "Loading…" : error ? "Retry loading tasks" : "Load more tasks"}
</Button>
</div>;
}
+48
View File
@@ -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<InboxMineSnapshot>({ 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<InboxMineSnapshot>(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 };
}
+252
View File
@@ -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<IntersectionObserverCallback>();
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
let current: ReturnType<typeof useInboxTouchedIssues>;
let options: Parameters<typeof useInboxTouchedIssues>[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 <>
<div data-testid="tasks">{visible.map(task => <span key={task.id}>{task.title}</span>)}</div>
<TaskListPagination hasMore={current.hasMore} isLoadingMore={current.isLoadingMore}
error={current.loadMoreError} loadMore={current.loadMore} autoLoad={autoLoad} />
</>;
}
const render = () => act(async () => root.render(<QueryClientProvider client={client}><Harness /></QueryClientProvider>));
const intersect = () => act(async () => {
for (const callback of [...intersections]) callback([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
});
const clickMore = () => act(async () => container.querySelector<HTMLButtonElement>("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<typeof import("../../storybook/fixtures/paperclipData")>("../../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 <output data-tick={tick}>{current.issues.length}</output>;
}
const renderProbe = (tick: number) => act(async () => root.render(<QueryClientProvider client={client}><Probe tick={tick} /></QueryClientProvider>));
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<Issue[]>(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);
});
+53
View File
@@ -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<Issue[]>({
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 };
}
+58
View File
@@ -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<Issue[]>[]) {
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<UseQueryResult<Issue[]>, "data" | "isSuccess" | "isFetching">;
fetchPage: (offset: number, signal: AbortSignal) => Promise<Issue[]>;
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<string, Issue>();
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 };
}
+16 -4
View File
@@ -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";
+1 -2
View File
@@ -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[] {
+26 -4
View File
@@ -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<string, unknown> }) => 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}</div>
{collection.layout === "board" ? collection.matchingItems.length
? <KanbanBoard showOverflowFades issues={collection.matchingItems.map(item => enrichIssueRow(item.issue))} agents={agents.data} onUpdateIssue={(id, data) => update.mutate({ id, data })} /> : empty : null}
{!needsAttention && tasks.hasNextPage ? <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground"><span>{view === "unread" ? unreadIds.size : items.length} tasks loaded. Load more to include them in filters.</span><Button variant="outline" size="sm" disabled={tasks.isFetchingNextPage} onClick={() => void tasks.fetchNextPage()}>{tasks.isFetchingNextPage ? "Loading…" : "Load more tasks"}</Button></div> : null}
<TaskListPagination hasMore={needsAttention ? attentionLimit < allAttentionIds.length : tasks.hasNextPage}
isLoadingMore={isLoadingMore} error={loadMoreError} loadMore={loadMore}
autoLoad={!deferredQuery && collection.activeFilterCount === 0} />
</>}
</section></TruncatedTextMarqueeProvider></FlyoutAppearanceProvider>;
}
+5 -2
View File
@@ -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<string, unknown> }) => 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
? <EmptyState icon={ListChecks} message="No tasks in this organization" action="New Task" onAction={() => openNewIssue()} />
: <EmptyState icon={SearchX} message="No tasks match this view" action="Clear filters" hideActionIcon onAction={collection.clear} />;
@@ -102,7 +103,9 @@ export function DesignSandboxTasks() {
{collection.narrowed ? <p role="status" className="design-task-results">{collection.matchingItems.length} matching tasks{collection.layout === "list" && collection.visibleItems.length > collection.matchingItems.length ? " · Parent tasks included for context" : ""}</p> : null}
<div hidden={collection.layout !== "list"} className="design-task-list-panel"><TaskList key={companyId} items={collection.visibleItems} allItems={collection.companyItems} collapsedIds={collection.collapsedIds} onCollapsedIdsChange={collection.setCollapsedIds} emptyState={empty} /></div>
{collection.layout === "board" ? collection.matchingItems.length ? <KanbanBoard showOverflowFades issues={collection.matchingItems.map(item => item.issue)} agents={agents.data} onUpdateIssue={(id, data) => update.mutate({ id, data })} /> : empty : null}
{tasks.hasNextPage ? <div className="flex items-center gap-3 text-sm text-muted-foreground"><span>Search, views and filters cover the {items.length} loaded tasks.</span><Button variant="outline" size="sm" disabled={tasks.isFetchingNextPage} onClick={() => void tasks.fetchNextPage()}>{tasks.isFetchingNextPage ? "Loading…" : "Load more tasks"}</Button></div> : null}
<TaskListPagination hasMore={tasks.hasNextPage} isLoadingMore={tasks.isFetchingNextPage}
error={tasks.isFetchNextPageError ? tasks.error : null} loadMore={() => { if (!tasks.isFetching) void tasks.fetchNextPage({ cancelRefetch: false }); }}
autoLoad={!collection.query && collection.activeFilterCount === 0} />
</>}
</div></TruncatedTextMarqueeProvider>;
}
+23 -61
View File
@@ -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<InboxMineSnapshot>({ 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<InboxMineSnapshot>(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<Issue[]>({
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) && (
<TaskListPagination hasMore={taskPages.hasMore} isLoadingMore={taskPages.isLoadingMore}
error={taskPages.loadMoreError} loadMore={taskPages.loadMore}
autoLoad={!normalizedSearchQuery && activeIssueFilterCount === 0} />
)}
{allLoaded && !listError && showAlertsSection && (
<>
{showSeparatorBefore("alerts") && <Separator />}
+9 -5
View File
@@ -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,
+33 -21
View File
@@ -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) && (
<TaskListPagination hasMore={taskPages.hasMore} isLoadingMore={taskPages.isLoadingMore}
error={taskPages.loadMoreError} loadMore={taskPages.loadMore}
autoLoad={!searchQuery.trim() && countActiveIssueFilters(issueFilters, true) === 0} />
)}
{showAlertsSection && (
<>
{showSeparatorBefore("alerts") && <Separator />}
+230
View File
@@ -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<typeof import("@/hooks/usePreloadTaskChats")>(), 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 }) => <a>{children}</a>,
}));
vi.mock("@/components/TaskList", async importOriginal => ({ ...await importOriginal<typeof import("@/components/TaskList")>(), TaskList: ({ items }: { items: { issue: Issue }[] }) => <>{items.map(({ issue }) => <span data-task key={issue.id}>{issue.title}</span>)}</> }));
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 <div data-paged={pagedIssuesProvided}>{issues.map(issue => <span data-task key={issue.id}>{issue.title}</span>)}
<TaskListPagination hasMore={!!hasMoreIssues} isLoadingMore={!!isLoadingMoreIssues} error={loadMoreIssuesError}
loadMore={() => (onRetryLoadMoreIssues ?? onLoadMoreIssues)?.()} autoLoad={false} />
</div>;
} }));
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 }) => <span data-task>{issue.title}</span> }));
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(<QueryClientProvider client={client}>{children}</QueryClientProvider>));
beforeEach(async () => {
vi.clearAllMocks();
localStorage.clear();
vi.stubGlobal("IntersectionObserver", class { observe() {} disconnect() {} });
({ createIssue } = await vi.importActual<typeof import("../../storybook/fixtures/paperclipData")>("../../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(<CoordinatorTasks />);
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<Issue[]>(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(<CoordinatorTasks />);
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(<BlockedInboxView companyId="company-1" searchQuery={searchQuery} agentNameById={new Map()}
issueLinkState={undefined} groupBy="none" sortBy="most_recent" issueFilters={defaultIssueFilterState}
currentUserId="user-1" liveIssueIds={new Set()} subtreeLiveCounts={new Map()} workspaceFilterContext={{}}
showStatusColumn showIdentifierColumn showUpdatedColumn />);
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(<Issues />);
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(<Issues />);
await vi.waitFor(() => expect(more()?.textContent).toBe("Retry loading tasks"));
expect(rows()).toHaveLength(100);
expect(api.compact).toHaveBeenCalledTimes(2);
await render(<Issues />);
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(<Inbox />);
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);
}
});