Skip to content

fix(issues): replace cursor-based pagination with page-number Search API - #8680

Merged
AmethystLiang merged 4 commits into
stablyai:mainfrom
fsdwen:fsdwen/issue-8649-bug-issue-pagination
Jul 16, 2026
Merged

AmethystLiang merged 4 commits into
stablyai:mainfrom
fsdwen:fsdwen/issue-8649-bug-issue-pagination

Conversation

@fsdwen

@fsdwen fsdwen commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Issue #8649 reported two bugs in the Tasks issue list pagination:

  1. Pages 6-16 unreachable — clicking page 16 highlighted page 5; clicking pages 6-16 did nothing. The old cursor-based approach (updated:<CURSOR) broke with Search API relevance sorting — pages after the first few returned no items even though more issues existed.
  2. Issue numbers out of order — e.g. [Feature]: Jujutsu Workspaces #1082 appeared between Managed hook runtime and PTY spawn env handling drift across layers #1308 and [Feature]: Declarative layout rules — pin content types to specific groups/regions #1499 because client-side sort used updatedAt instead of issue number.

Root Cause

Pagination used two separate GitHub API strategies that disagreed on item ordering:

Load type API Sort
Initial page 0 REST (repos/:owner/:repo/issues) updated
Subsequent pages Search API + cursor (updated:<DATE) relevance (implicit)

Items returned in different orders across these two sources caused items to go missing or appear on wrong pages across page boundaries.

Solution

  1. Unified on Search API for all pages — initial load and pagination both use search/issues?q=...&page=N, eliminating the REST-vs-Search inconsistency
  2. Page-number pagination — replaced cursor-based (updated:<DATE) with page numbers (page=N), which Search API supports natively
  3. Client-side sort by issue number — switched from sortWorkItemsByUpdatedAt to sortWorkItemsByNumber, matching GitHub's default Issues view
  4. Parallelized page fetches — clicking page 16 now fetches all intermediate pages concurrently (~2s) instead of sequentially (~30s)

Code quality improvements

  • Removed dead legacy gh issue list / gh pr list code path (46 lines)
  • Extracted quoteForSearch() helper to eliminate 5x duplicated space-quoting logic
  • Shortened overlong comments to comply with AGENTS.md 1-2 line rule
  • Made page a required parameter in buildWorkItemListArgs after removing dead branch

Screenshots

image

Verification

Check Result
TypeScript typecheck (3 tsconfigs) Passed
github.test.ts (147 tests) Passed
orca-runtime.test.ts (660 tests) Passed
web-preload-api.test.ts (61 tests) Passed

Closes #8649

Problem
=======
Issue pagination (stablyai#8649) had two bugs:
1. Pages 6-16 were unreachable — clicking page 16 highlighted page 5;
   clicking 6/7 did nothing. The old cursor-based approach
   (updated:<CURSOR) broke with Search API's relevance sorting —
   pages after the first few returned no items even though more
   issues existed.
2. Issue numbers appeared out of order on loaded pages (e.g. stablyai#1082
   between stablyai#1308 and stablyai#1499), because client-side sort used
   updatedAt instead of issue number.

Root Cause
==========
The pagination used two separate GitHub API strategies:
- Initial page 0 load: REST endpoints (repos/:owner/:repo/issues,
  repos/:owner/:repo/pulls) sorted by updatedAt
- Subsequent pages: Search API with cursor (updated:<DATE)

These two sources returned items in different orders, causing items
to go missing or appear on wrong pages across page boundaries.

Solution
========
1. Unified on GitHub Search API for all pages — initial load and
   pagination both use search/issues?q=...&page=N, eliminating the
   REST-vs-Search inconsistency.
2. Changed from cursor-based (update:<DATE) to page-number-based
   pagination (page=N), which the Search API supports natively.
3. Switched client-side sort from updatedAt to issue number
   (sortWorkItemsByNumber), matching GitHub's default Issues view.
4. Parallelized page fetches in handleLoadNextPage — clicking page
   16 now fetches all intermediate pages concurrently (~2s) instead
   of sequentially (~30s).
5. Cleaned up dead legacy gh issue list / gh pr list code path,
   extracted quoteForSearch helper, shortened overlong comments.

Files changed: 11 files, +140/-127 lines

Closes stablyai#8649
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Work-item retrieval now uses GitHub Search API page-based pagination instead of REST cursor pagination. The page parameter is propagated through the client, IPC, runtime RPC, preload bridge, and renderer store. Recent and queried results are ordered by work-item number, and issue searches filter PR-shaped results. Task loading fetches requested pages in parallel and stops aggregation after an empty page. Shared sorting and related tests were updated.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description covers the change well, but it doesn't follow the required template: missing Summary, Testing checklist, AI Review Report, Security Audit, and Notes sections. Add the required template sections: Summary, Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address #8649 by making all pages reachable, aligning the highlighted page with the selection, and sorting issues by number.
Out of Scope Changes check ✅ Passed The extra refactors, helper extraction, and tests all support the pagination fix and do not appear unrelated to the issue.
Title check ✅ Passed The title is concise and accurately summarizes the main change from cursor-based pagination to page-number Search API pagination.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/main/github/client.ts (2)

1094-1213: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

listRecentWorkItems ignores page, breaking pagination for the query-less view.

listRecentWorkItems use Search API so page 0 and pagination pages both use the same source, eliminating the REST-vs-Search inconsistency that caused issues to appear in different orders or go missing across page boundaries. but every one of its 4 Search API URLs hardcodes &page=1 (e.g. search/issues?q=${encodeURIComponent(repo:${issueOwnerRepo.owner}/${issueOwnerRepo.repo} is:issue is:open)}&sort=created&order=desc&per_page=${limit}&page=1), and the function has no page parameter at all.

listWorkItems never forwards its own page argument into this branch: await listRecentWorkItems( repoPath, issueOwnerRepo, prOwnerRepo, limit, connectionId, noCache, localGitOptions ) — only the listQueriedWorkItems branch receives page.

Since the renderer's fetchWorkItemsNextPage passes query: query || undefined (empty string becomes undefined), any "next page" click while the applied Tasks search resolves to an empty/no-filter query (e.g. the default "Recent" view) always re-requests Search API page 1 and never advances — reproducing exactly the pagination bug #8649 was meant to fix, for this specific view.

🐛 Proposed fix: thread `page` through `listRecentWorkItems`
 async function listRecentWorkItems(
   repoPath: string,
   issueOwnerRepo: OwnerRepo | null,
   prOwnerRepo: OwnerRepo | null,
   limit: number,
+  page: number = 1,
   connectionId?: string | null,
   noCache?: boolean,
   localGitOptions: LocalGitExecOptions = {}
 ): Promise<PartialWorkItemsResult> {
   ...
-              `search/issues?q=${encodeURIComponent(`repo:${issueOwnerRepo.owner}/${issueOwnerRepo.repo} is:issue is:open`)}&sort=created&order=desc&per_page=${limit}&page=1`,
+              `search/issues?q=${encodeURIComponent(`repo:${issueOwnerRepo.owner}/${issueOwnerRepo.repo} is:issue is:open`)}&sort=created&order=desc&per_page=${limit}&page=${page}`,
   // ...repeat for the other 3 hardcoded `&page=1` URLs...
 }

And in listWorkItems:

     const partial = !trimmedQuery
       ? await listRecentWorkItems(
           repoPath,
           issueOwnerRepo,
           prOwnerRepo,
           limit,
+          page ?? 1,
           connectionId,
           noCache,
           localGitOptions
         )

Also applies to: 1356-1409


1271-1354: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Issue search results aren't filtered for PR-shaped rows, unlike listRecentWorkItems.

listQueriedWorkItems's issue fetch maps results directly: return { items: (JSON.parse(stdout) as Record<string, unknown>[]).map(mapIssueWorkItem) }, with no filter for PR-shaped rows. But this same query goes through buildWorkItemListArgs({ kind: 'issue', ... }), which scopes with is:issue against the identical search/issues endpoint that listRecentWorkItems explicitly guards against: the GitHub search/issues endpoint may still return PRs with a pull_request marker even when queried with is:issue. Filter them out here to keep the issue and PR buckets clean. The same quirk applies here but isn't guarded, so a PR can leak into the "issues" bucket whenever a user runs a filtered/searched Tasks query.

🐛 Proposed fix: apply the same PR-shape filter
     try {
       const { stdout } = issueOwnerRepo
         ? await ghExecFileAsync(args, ghOptions)
         : await ghCwdResolvedExec(repoContext, args, ghOptions)
       return {
-        items: (JSON.parse(stdout) as Record<string, unknown>[]).map(mapIssueWorkItem)
+        items: (JSON.parse(stdout) as Record<string, unknown>[])
+          .filter((item) => !('pull_request' in item))
+          .map(mapIssueWorkItem)
       }
src/renderer/src/components/TaskPage.tsx (1)

6252-6306: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Off-by-one in the page-number loop breaks "load next page" for the most common case.

startPage = pages.length + 1 is a 1-indexed Search API page number, but target (targetPage ?? pages.length) is the 0-indexed UI page — the same indexing used directly against pages.length/setCurrentPage by the caller. The loop for (let p = startPage; p <= target; p++) therefore always computes exactly one fewer page than required (needed range is [pages.length+1, ..., target+1]).

Concretely: when the user clicks straight to the next unseen page (target === pages.length, i.e. the everyday "next page" click), startPage > target and pageNumbers is empty — the click fetches nothing and silently does nothing. For any larger jump, the fetch lands exactly one page short of the requested target. This breaks the PR's own acceptance criteria that every displayed page be reachable.

🐛 Proposed fix: align the loop bound with the 0-indexed target
         const startPage = pages.length + 1
+        const endPage = target + 1
         const pageNumbers: number[] = []
-        for (let p = startPage; p <= target; p++) {
+        for (let p = startPage; p <= endPage; p++) {
           pageNumbers.push(p)
         }
🧹 Nitpick comments (1)
src/renderer/src/components/TaskPage.tsx (1)

3823-3824: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reimplements sortWorkItemsByNumber inline instead of using the shared helper.

Both spots duplicate [...list].sort((a, b) => b.number - a.number) rather than importing sortWorkItemsByNumber from shared/work-items, which the sibling store slice (store/slices/github.ts) already uses for the exact same merge-and-sort step. The shared helper exists specifically to keep this sort consistent across callers (per its own "Why" comment about cross-caller consistency).

♻️ Proposed refactor: use the shared helper
-    const page0 = [...merged].sort((a, b) => b.number - a.number).slice(0, CROSS_REPO_DISPLAY_LIMIT)
+    const page0 = sortWorkItemsByNumber(merged).slice(0, CROSS_REPO_DISPLAY_LIMIT)
     const page0 =
       preMerged.length > 0
-        ? [...preMerged].sort((a, b) => b.number - a.number).slice(0, CROSS_REPO_DISPLAY_LIMIT)
+        ? sortWorkItemsByNumber(preMerged).slice(0, CROSS_REPO_DISPLAY_LIMIT)
         : []

(Import sortWorkItemsByNumber alongside the existing PER_REPO_FETCH_LIMIT/CROSS_REPO_DISPLAY_LIMIT import from shared/work-items.)

Also applies to: 6407-6410


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 59f081ed-764f-4d74-8122-d3fc646cc4c6

📥 Commits

Reviewing files that changed from the base of the PR and between e53a0a0 and b8773fa.

📒 Files selected for processing (11)
  • src/main/github/client.ts
  • src/main/ipc/github.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/github.ts
  • src/preload/index.ts
  • src/renderer/src/components/TaskPage.tsx
  • src/renderer/src/store/slices/github.test.ts
  • src/renderer/src/store/slices/github.ts
  • src/renderer/src/web/web-preload-api.test.ts
  • src/shared/work-items.ts

@fsdwen

fsdwen commented Jul 14, 2026

Copy link
Copy Markdown
Contributor Author

Design note: comparison with #8658

There is an overlapping PR #8658 (by moseoh + OrcaWin) fixing the same issue #8649 with a different approach. This note explains why #8680 takes a more aggressive approach.

#8658's approach (minimal fix)

  • Keeps cursor-based pagination, adds sort:updated-desc to every --search qualifier so the gh CLI and Search API both return items in the order the cursor expects
  • Changes updated:< to updated:<=' (inclusive) to avoid skipping boundary items
  • Extracts page accumulation into a pure helper with dedup logic (+506/-40 lines, 5 files)

What #8680 additionally considers

1. Unified API source, not just sorted output. The root cause was two API sources (REST for page 0, Search + cursor for pages 1+) disagreeing on ordering. #8658 pins the sort to updated-desc on both paths but still draws from two different backends with different result sets, index latency, and cutoff behavior. #8680 unifies all pages on the Search API, eliminating the inconsistency at the architecture level.

2. Page-number pagination enables parallel fetch. Cursor pagination is inherently sequential — page N needs the last item of page N-1 to form the cursor. Jumping to page 16 requires 15 serial requests (~30s). With page=N, all intermediate pages can be fetched in parallel via Promise.all (~2s). This directly addresses the core usability complaint in #8649 (high page numbers unreachable).

3. Sort by issue number matches user expectation. The reporter explicitly requested "sorted consistently by number (newest first, matching GitHub's default Issues view)." #8680 switches the cross-repo merge sort from sortWorkItemsByUpdatedAt to sortWorkItemsByNumber.

4. No boundary-dedup overhead. #8658's updated:<=' fix requires deduplicating re-fetched boundary rows via accumulateWorkItemPages + workItemIdentity, plus one extra fetch per page boundary. Page-number pagination avoids this entirely — each page=N returns distinct items.

5. Dead code removal. #8658 retains the gh issue list / gh pr list CLI code path (used only for page 0). #8680 removes it entirely after migrating all load paths to Search API.

Where #8658 has an edge

Familiarity. Keeping updatedAt ordering means no behavioral change for users accustomed to "most recently updated" sort. #8680's switch to issue-number sort is a product-level choice that maintainers may prefer to evaluate separately.

See the conversation on #8658 for discussion.

@fsdwen

fsdwen commented Jul 14, 2026

Copy link
Copy Markdown
Contributor Author

@OrcaWin Could you take a look at this PR? It addresses #8649 with a page-number approach (vs the cursor-based fix in #8658). The design rationale vs #8658 is outlined above — happy to consolidate if you prefer a single direction. Thanks!

@AmethystLiang

Copy link
Copy Markdown
Contributor

reviewing now

@AmethystLiang
AmethystLiang requested review from AmethystLiang and removed request for brennanb2025 July 16, 2026 00:28
@AmethystLiang

Copy link
Copy Markdown
Contributor

Addressed all review feedback and pushed the fixes in b52109d.\n\n- Synced the branch with current main and resolved the client/TaskPage conflicts.\n- Threaded numbered pages through the query-less Recent path and fixed the UI/API 0-based to 1-based conversion.\n- High-page clicks now fetch only the requested provider page, avoiding bursts of intermediate Search API requests.\n- Kept issues on numbered Search API pages while retaining rich gh pr list rows for PR metadata; later PR pages are sliced from a stable created-desc result set.\n- Filtered PR-shaped rows from issue searches, escaped quoted search values safely, and constrained runtime page inputs to positive integers.\n- Divided the display budget before cross-repo fetches so merged results are not truncated and lost; page counts now follow the largest per-repo result set, with sparse unfetched pages represented explicitly.\n- Updated the preload, IPC, runtime, store, and renderer contracts plus regression coverage.\n\nVerification:\n- pnpm run typecheck\n- pnpm run lint\n- Focused pagination/API suite: 1,006 tests passed\n- Full unit suite: 2,870 files passed, 30,430 tests passed (7 files / 47 tests skipped)\n\nGitHub now reports the PR as MERGEABLE; CI status checks have not populated yet.

@AmethystLiang
AmethystLiang merged commit 78d2b95 into stablyai:main Jul 16, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…API (stablyai#8680)

* fix(issues): replace cursor-based pagination with page-number Search API

Problem
=======
Issue pagination (stablyai#8649) had two bugs:
1. Pages 6-16 were unreachable — clicking page 16 highlighted page 5;
   clicking 6/7 did nothing. The old cursor-based approach
   (updated:<CURSOR) broke with Search API's relevance sorting —
   pages after the first few returned no items even though more
   issues existed.
2. Issue numbers appeared out of order on loaded pages (e.g. stablyai#1082
   between stablyai#1308 and stablyai#1499), because client-side sort used
   updatedAt instead of issue number.

Root Cause
==========
The pagination used two separate GitHub API strategies:
- Initial page 0 load: REST endpoints (repos/:owner/:repo/issues,
  repos/:owner/:repo/pulls) sorted by updatedAt
- Subsequent pages: Search API with cursor (updated:<DATE)

These two sources returned items in different orders, causing items
to go missing or appear on wrong pages across page boundaries.

Solution
========
1. Unified on GitHub Search API for all pages — initial load and
   pagination both use search/issues?q=...&page=N, eliminating the
   REST-vs-Search inconsistency.
2. Changed from cursor-based (update:<DATE) to page-number-based
   pagination (page=N), which the Search API supports natively.
3. Switched client-side sort from updatedAt to issue number
   (sortWorkItemsByNumber), matching GitHub's default Issues view.
4. Parallelized page fetches in handleLoadNextPage — clicking page
   16 now fetches all intermediate pages concurrently (~2s) instead
   of sequentially (~30s).
5. Cleaned up dead legacy gh issue list / gh pr list code path,
   extracted quoteForSearch helper, shortened overlong comments.

Files changed: 11 files, +140/-127 lines

Closes stablyai#8649

* chore: remove unrelated merge formatting

---------

Co-authored-by: Jinjing <[email protected]>
AmoabaKelvin added a commit that referenced this pull request Oct 18, 2026
Hosts stopped reading the `before` cursor in #8680, so every "next page"
returned page 1 again. A page that lands after the repo, filter or
provider changed no longer replaces the new list.
AmoabaKelvin added a commit that referenced this pull request Oct 18, 2026
Hosts stopped reading the `before` cursor in #8680, so every "next page"
returned page 1 again. A page that lands after the repo, filter or
provider changed no longer replaces the new list.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Issue pagination shows wrong pages after clicking page numbers

3 participants