opencode-github-pr 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ export function StatusMessage(props: {
4
+ icon: string
5
+ title: string
6
+ description?: string
7
+ titleColor: string
8
+ descriptionColor: string
9
+ }) {
10
+ const descriptionIndent = Bun.stringWidth(props.icon) + 1
11
+
12
+ return (
13
+ <box flexDirection="column" paddingTop={1} paddingRight={1} width="100%">
14
+ <text fg={props.titleColor} selectable={false}>{props.icon} {props.title}</text>
15
+ {props.description && (
16
+ <box paddingLeft={descriptionIndent} width="100%">
17
+ <text fg={props.descriptionColor} selectable={false}>{props.description}</text>
18
+ </box>
19
+ )}
20
+ </box>
21
+ )
22
+ }
@@ -1,14 +1,21 @@
1
1
  import type { PRScope, PRStatusFilter } from "../domain/types"
2
2
  import { DEFAULT_SKIN, type Skin } from "./theme"
3
+ import {
4
+ DEFAULT_RECENT_PRS_LIMIT,
5
+ DEFAULT_TUI_PAGES_PER_BATCH,
6
+ MAX_RECENT_PRS_LIMIT,
7
+ MIN_PAGES_PER_BATCH,
8
+ } from "../infra/loader"
3
9
 
4
10
  export const DEFAULT_ICONS = {
5
11
  openPR: "",
12
+ closedPR: "",
13
+ draftPR: "",
6
14
  mergedPR: "",
7
15
  review: "",
8
16
  openComment: "󰅺",
9
17
  check: "●",
10
18
  scope: "",
11
- status: "",
12
19
  loading: "󰔟",
13
20
  info: "",
14
21
  error: "",
@@ -16,16 +23,52 @@ export const DEFAULT_ICONS = {
16
23
  nextPage: "",
17
24
  }
18
25
 
26
+ export const UNICODE_ICONS = {
27
+ openPR: "•",
28
+ closedPR: "•",
29
+ draftPR: "•",
30
+ mergedPR: "•",
31
+ review: "✓",
32
+ openComment: "■",
33
+ check: "●",
34
+ scope: "",
35
+ loading: "…",
36
+ info: "ℹ",
37
+ error: "⚠",
38
+ previousPage: "◀",
39
+ nextPage: "▶",
40
+ }
41
+
42
+ export type IconStyle = "nerd" | "unicode"
43
+
19
44
  export type DashboardIcons = Record<keyof typeof DEFAULT_ICONS, string>
20
45
 
46
+ export type DashboardSpacing = {
47
+ iconToCount: number
48
+ sameTypeGroups: number
49
+ differentTypeGroups: number
50
+ }
51
+
52
+ export const DEFAULT_SPACING: DashboardSpacing = {
53
+ iconToCount: 0,
54
+ sameTypeGroups: 0,
55
+ differentTypeGroups: 1,
56
+ }
57
+
58
+ const MAX_SPACING_GAP = 4
59
+
21
60
  export type DashboardOptions = {
22
61
  enabled: boolean
23
62
  pageSize: number
24
- maxPRPages: number
63
+ pagesPerBatch: number
25
64
  refreshIntervalMs: number
26
65
  requestTimeoutMs: number
66
+ recentPRsLimit: number
27
67
  defaultScope: PRScope
28
68
  defaultStatusFilter: PRStatusFilter
69
+ iconStyle: IconStyle
70
+ showSingleStatusCount: boolean
71
+ spacing: DashboardSpacing
29
72
  colors: Partial<Skin>
30
73
  icons: DashboardIcons
31
74
  }
@@ -33,11 +76,15 @@ export type DashboardOptions = {
33
76
  type DashboardOptionsInput = {
34
77
  enabled?: unknown
35
78
  pageSize?: unknown
36
- maxPRPages?: unknown
79
+ pagesPerBatch?: unknown
37
80
  refreshIntervalMs?: unknown
38
81
  requestTimeoutMs?: unknown
82
+ recentPRsLimit?: unknown
39
83
  defaultScope?: unknown
40
84
  defaultStatusFilter?: unknown
85
+ iconStyle?: unknown
86
+ showSingleStatusCount?: unknown
87
+ spacing?: unknown
41
88
  colors?: unknown
42
89
  icons?: unknown
43
90
  }
@@ -46,7 +93,7 @@ const scopes: PRScope[] = ["branch", "author", "assignee", "all"]
46
93
  const statusFilters: PRStatusFilter[] = ["open", "closed", "all"]
47
94
 
48
95
  export const DEFAULT_PAGE_SIZE = 5
49
- export const DEFAULT_MAX_PR_PAGES = 1
96
+ export const DEFAULT_PAGES_PER_BATCH = DEFAULT_TUI_PAGES_PER_BATCH
50
97
  export const DEFAULT_REFRESH_INTERVAL_MS = 60_000
51
98
  export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
52
99
 
@@ -54,32 +101,65 @@ function positiveNumber(value: unknown, fallback: number): number {
54
101
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.max(1, Math.floor(value)) : fallback
55
102
  }
56
103
 
57
- function stringOverrides<T extends Record<string, string>>(defaults: T, input: unknown): Partial<T> {
104
+ function nonNegativeInteger(value: unknown, fallback: number, max: number): number {
105
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
106
+ ? Math.min(max, Math.floor(value))
107
+ : fallback
108
+ }
109
+
110
+ function spacingOverrides(input: unknown): DashboardSpacing {
111
+ if (!input || typeof input !== "object" || Array.isArray(input)) return { ...DEFAULT_SPACING }
112
+ const values = input as Record<string, unknown>
113
+ return {
114
+ iconToCount: nonNegativeInteger(values.iconToCount, DEFAULT_SPACING.iconToCount, MAX_SPACING_GAP),
115
+ sameTypeGroups: nonNegativeInteger(values.sameTypeGroups, DEFAULT_SPACING.sameTypeGroups, MAX_SPACING_GAP),
116
+ differentTypeGroups: nonNegativeInteger(
117
+ values.differentTypeGroups,
118
+ DEFAULT_SPACING.differentTypeGroups,
119
+ MAX_SPACING_GAP,
120
+ ),
121
+ }
122
+ }
123
+
124
+ function stringOverrides<T extends Record<string, string>>(
125
+ defaults: T,
126
+ input: unknown,
127
+ allowEmpty = false,
128
+ ): Partial<T> {
58
129
  if (!input || typeof input !== "object" || Array.isArray(input)) return {}
59
130
  const result: Partial<T> = {}
60
131
  for (const key of Object.keys(defaults) as Array<keyof T>) {
61
132
  const value = (input as Record<string, unknown>)[key as string]
62
- if (typeof value === "string" && value.trim()) result[key] = value as T[keyof T]
133
+ if (typeof value === "string" && (value.trim() || (allowEmpty && value === ""))) {
134
+ result[key] = value as T[keyof T]
135
+ }
63
136
  }
64
137
  return result
65
138
  }
66
139
 
67
- function mergeStrings<T extends Record<string, string>>(defaults: T, input: unknown): T {
68
- return { ...defaults, ...stringOverrides(defaults, input) }
140
+ function mergeStrings<T extends Record<string, string>>(defaults: T, input: unknown, allowEmpty = false): T {
141
+ return { ...defaults, ...stringOverrides(defaults, input, allowEmpty) }
69
142
  }
70
143
 
71
144
  export function dashboardOptions(input: DashboardOptionsInput = {}): DashboardOptions {
145
+ const iconStyle: IconStyle = input.iconStyle === "unicode" ? "unicode" : "nerd"
146
+ const defaultIcons = iconStyle === "unicode" ? UNICODE_ICONS : DEFAULT_ICONS
147
+
72
148
  return {
73
149
  enabled: input.enabled !== false,
74
150
  pageSize: positiveNumber(input.pageSize, DEFAULT_PAGE_SIZE),
75
- maxPRPages: positiveNumber(input.maxPRPages, DEFAULT_MAX_PR_PAGES),
151
+ pagesPerBatch: Math.max(MIN_PAGES_PER_BATCH, positiveNumber(input.pagesPerBatch, DEFAULT_PAGES_PER_BATCH)),
76
152
  refreshIntervalMs: positiveNumber(input.refreshIntervalMs, DEFAULT_REFRESH_INTERVAL_MS),
77
153
  requestTimeoutMs: positiveNumber(input.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS),
154
+ recentPRsLimit: nonNegativeInteger(input.recentPRsLimit, DEFAULT_RECENT_PRS_LIMIT, MAX_RECENT_PRS_LIMIT),
78
155
  defaultScope: scopes.includes(input.defaultScope as PRScope) ? (input.defaultScope as PRScope) : "author",
79
156
  defaultStatusFilter: statusFilters.includes(input.defaultStatusFilter as PRStatusFilter)
80
157
  ? (input.defaultStatusFilter as PRStatusFilter)
81
158
  : "open",
159
+ iconStyle,
160
+ showSingleStatusCount: input.showSingleStatusCount === true,
161
+ spacing: spacingOverrides(input.spacing),
82
162
  colors: stringOverrides(DEFAULT_SKIN, input.colors),
83
- icons: mergeStrings(DEFAULT_ICONS, input.icons),
163
+ icons: mergeStrings(defaultIcons, input.icons, true),
84
164
  }
85
165
  }
@@ -4,10 +4,7 @@
4
4
  import type { ResolvedTheme } from "@opencode/theme/tui"
5
5
 
6
6
  export const DEFAULT_SKIN = {
7
- panel: "#161616",
8
7
  panelAlt: "#1d1d1d",
9
- border: "#3a3a3a",
10
- borderActive: "#5f87ff",
11
8
  text: "#e5e5e5",
12
9
  muted: "#888888",
13
10
  accent: "#5f87ff",
@@ -19,10 +16,7 @@ export const DEFAULT_SKIN = {
19
16
  }
20
17
 
21
18
  export type Skin = {
22
- panel: string
23
19
  panelAlt: string
24
- border: string
25
- borderActive: string
26
20
  text: string
27
21
  muted: string
28
22
  accent: string
@@ -45,10 +39,7 @@ export function toHex(c: { toInts(): [number, number, number, number] }): string
45
39
 
46
40
  export function skin(t: ResolvedTheme, overrides: Partial<Skin> = {}): Skin {
47
41
  return {
48
- panel: toHex(t.background.base),
49
42
  panelAlt: toHex(t.background.raised.base),
50
- border: toHex(t.border.base),
51
- borderActive: toHex(t.text.action.primary.base),
52
43
  text: toHex(t.text.base),
53
44
  muted: toHex(t.text.muted),
54
45
  accent: toHex(t.text.action.primary.base),
@@ -56,7 +47,7 @@ export function skin(t: ResolvedTheme, overrides: Partial<Skin> = {}): Skin {
56
47
  warning: toHex(t.text.feedback.warning.base),
57
48
  error: toHex(t.text.feedback.error.base),
58
49
  draft: toHex(t.text.muted),
59
- merged: toHex(t.text.action.primary.base),
50
+ merged: toHex(t.text.feedback.info.base),
60
51
  ...overrides,
61
52
  }
62
53
  }
@@ -11,24 +11,31 @@ import type { Context as TuiPluginContext } from "@opencode/plugin/tui/context"
11
11
  import {
12
12
  DashboardStatus,
13
13
  type DashboardState,
14
- type Repo,
14
+ type PRScope,
15
+ type PRStatusFilter,
15
16
  } from "../domain/types"
16
- import { currentBranch, detectRepo } from "../infra/git"
17
- import { repositoryPRs, fetchOnePR } from "../infra/loader"
17
+ import { currentBranch, detectPushRemoteOwner, detectRepo } from "../infra/git"
18
+ import {
19
+ DEFAULT_RECENT_PRS_LIMIT,
20
+ repositoryPRs,
21
+ MIN_PAGES_PER_BATCH,
22
+ } from "../infra/loader"
18
23
  import { prListErrorKind, prListErrorMessage, parseRateLimitError } from "../domain/messages"
19
- import { DEFAULT_MAX_PR_PAGES, DEFAULT_REQUEST_TIMEOUT_MS } from "./config"
24
+ import { DEFAULT_PAGES_PER_BATCH, DEFAULT_PAGE_SIZE, DEFAULT_REQUEST_TIMEOUT_MS } from "./config"
20
25
 
21
26
  export function useDashboard(
22
27
  api: TuiPluginContext,
23
28
  state: () => DashboardState,
24
29
  setState: (fn: (s: DashboardState) => DashboardState) => void,
25
30
  requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
26
- maxPRPages = DEFAULT_MAX_PR_PAGES,
27
- // Whether the status filter shows closed PRs, so they need loading.
28
- includeClosed: () => boolean = () => false,
31
+ pagesPerBatch = DEFAULT_PAGES_PER_BATCH,
32
+ statusFilter: () => PRStatusFilter = () => "open",
33
+ scopeFilter: () => PRScope = () => "all",
34
+ pageSize = DEFAULT_PAGE_SIZE,
35
+ recentPRsLimit = DEFAULT_RECENT_PRS_LIMIT,
29
36
  ): {
30
37
  refresh: () => Promise<void>
31
- refreshOne: (n: number) => Promise<void>
38
+ loadMore: () => Promise<void>
32
39
  } {
33
40
  // Resolve the working directory explicitly when the TUI exposes it, so
34
41
  // repo detection doesn't depend on where opencode happens to launch.
@@ -51,16 +58,59 @@ export function useDashboard(
51
58
  }
52
59
 
53
60
  let inFlight: Promise<void> | null = null
54
- let inFlightIncludesClosed = false
61
+ let inFlightFilterKey: string | null = null
62
+ const loadMoreInFlight = new Map<string, Promise<void>>()
55
63
  let refreshToken = 0
56
64
  let currentRefreshToken = 0
65
+ let rateLimitResetAt: number | null = null
66
+ let rateLimitMessage: string | null = null
67
+ const rateLimitActive = (): boolean => {
68
+ if (rateLimitResetAt === null) return false
69
+ if (Date.now() >= rateLimitResetAt) {
70
+ rateLimitResetAt = null
71
+ rateLimitMessage = null
72
+ return false
73
+ }
74
+ return true
75
+ }
76
+ const recordRateLimit = (error: unknown) => {
77
+ const rateLimit = parseRateLimitError(error)
78
+ if (rateLimit.isRateLimit) {
79
+ rateLimitMessage = rateLimit.message
80
+ if (rateLimit.resetAt + 2_000 > Date.now()) {
81
+ rateLimitResetAt = rateLimit.resetAt + 2_000
82
+ }
83
+ }
84
+ return rateLimit
85
+ }
86
+ const pageBatchSize = pageSize * Math.max(MIN_PAGES_PER_BATCH, pagesPerBatch)
57
87
 
58
88
  const refresh = async (): Promise<void> => {
59
- const wantClosed = includeClosed()
89
+ const listing = statusFilter()
90
+ const scope = scopeFilter()
91
+ if (rateLimitActive()) {
92
+ const scopeValue = scope === "branch" ? state().currentBranch : null
93
+ setState((s) => ({
94
+ ...s,
95
+ status: DashboardStatus.Error,
96
+ pagination: {
97
+ ...s.pagination,
98
+ listing,
99
+ scope,
100
+ scopeValue,
101
+ cursor: null,
102
+ hasMore: false,
103
+ totalCount: null,
104
+ loading: false,
105
+ },
106
+ error: rateLimitMessage ?? s.error,
107
+ errorKind: "rate-limit",
108
+ }))
109
+ return
110
+ }
111
+ const filterKey = `${listing}:${scope}`
60
112
  if (inFlight) {
61
- // A refresh that skipped closed PRs can't serve a filter that needs
62
- // them; run another once it lands.
63
- if (wantClosed && !inFlightIncludesClosed) return inFlight.then((): Promise<void> => refresh())
113
+ if (filterKey !== inFlightFilterKey) return inFlight.then((): Promise<void> => refresh())
64
114
  return inFlight
65
115
  }
66
116
  const prev = state()
@@ -70,13 +120,27 @@ export function useDashboard(
70
120
  }
71
121
  const promise = (async () => {
72
122
  const isStale = () => token !== refreshToken
123
+ let scopeValue: string | null = null
73
124
  try {
74
125
  const directory = await cwd()
75
- const repo = detectRepo(directory)
126
+ const [repo, branchPushOwner] = await Promise.all([
127
+ detectRepo(directory),
128
+ scope === "branch"
129
+ ? detectPushRemoteOwner(directory, currentBranch(directory))
130
+ : Promise.resolve(null),
131
+ ])
132
+ const branch = currentBranch(directory)
133
+ scopeValue = scope === "branch" ? branch : null
76
134
  const isFirstLoad = prev.fetchedAt === null
77
135
  const isDirChange =
78
136
  !!prev.repo && !!repo && (prev.repo.owner !== repo.owner || prev.repo.repo !== repo.repo)
79
- const showLoading = isFirstLoad || isDirChange || prev.status === DashboardStatus.Loading
137
+ const showLoading =
138
+ isFirstLoad ||
139
+ isDirChange ||
140
+ prev.status === DashboardStatus.Loading ||
141
+ prev.pagination.listing !== listing ||
142
+ prev.pagination.scope !== scope ||
143
+ prev.pagination.scopeValue !== scopeValue
80
144
  if (showLoading && prev.status !== DashboardStatus.Loading) {
81
145
  if (isStale()) return
82
146
  setState((s) => ({ ...s, error: undefined, status: DashboardStatus.Loading }))
@@ -90,58 +154,93 @@ export function useDashboard(
90
154
  prs: [],
91
155
  currentBranch: null,
92
156
  viewerLogin: null,
93
- closedLoaded: false,
94
- truncated: { open: false, closed: false },
157
+ pagination: {
158
+ listing,
159
+ scope,
160
+ scopeValue,
161
+ cursor: null,
162
+ hasMore: false,
163
+ totalCount: 0,
164
+ pagesLoaded: 0,
165
+ searchResultsFetched: 0,
166
+ supplementalPRCount: 0,
167
+ loading: false,
168
+ limitReached: false,
169
+ },
95
170
  error: undefined,
96
171
  errorKind: undefined,
97
172
  fetchedAt: Date.now(),
98
173
  }))
99
174
  return
100
175
  }
101
- const [open, closed] = await timeoutRace(requestTimeoutMs, () =>
102
- Promise.all([
103
- repositoryPRs(repo, maxPRPages, requestTimeoutMs, "open"),
104
- wantClosed ? repositoryPRs(repo, maxPRPages, requestTimeoutMs, "closed") : Promise.resolve(null),
105
- ]),
176
+ const result = await repositoryPRs(
177
+ repo,
178
+ pageBatchSize,
179
+ requestTimeoutMs,
180
+ listing,
181
+ null,
182
+ scope,
183
+ scopeValue,
184
+ 0,
185
+ recentPRsLimit,
186
+ branchPushOwner,
106
187
  )
107
188
  if (isStale()) return
108
- setState((s) => {
109
- // Keep closed PRs from an earlier load of the same repository, so
110
- // switching back to a closed view is instant.
111
- const sameRepo = s.repo?.owner === repo.owner && s.repo?.repo === repo.repo
112
- const keptClosed = sameRepo && s.closedLoaded
113
- const openNumbers = new Set(open.prs.map((pr) => pr.number))
114
- // A kept PR that has since been reopened is in the open list.
115
- const closedPRs = closed ? closed.prs : keptClosed
116
- ? s.prs.filter((pr) => pr.isClosed && !openNumbers.has(pr.number))
117
- : []
118
- return {
119
- ...s,
120
- status: DashboardStatus.Ok,
121
- repo,
122
- prs: [...open.prs, ...closedPRs],
123
- currentBranch: currentBranch(directory),
124
- viewerLogin: open.viewerLogin ?? closed?.viewerLogin ?? null,
125
- closedLoaded: closed !== null || keptClosed,
126
- truncated: {
127
- open: open.listingTruncated,
128
- closed: closed ? closed.listingTruncated : keptClosed && s.truncated.closed,
129
- },
130
- error: undefined,
131
- errorKind: undefined,
132
- fetchedAt: Date.now(),
133
- }
134
- })
189
+ setState((s) => ({
190
+ ...s,
191
+ status: DashboardStatus.Ok,
192
+ repo,
193
+ prs: result.prs,
194
+ currentBranch: branch,
195
+ viewerLogin: result.viewerLogin ?? s.viewerLogin,
196
+ pagination: {
197
+ listing,
198
+ scope,
199
+ scopeValue,
200
+ cursor: result.endCursor,
201
+ hasMore: result.hasMore,
202
+ totalCount: result.totalCount,
203
+ pagesLoaded: result.fetchedPages,
204
+ searchResultsFetched: result.searchResultsFetched,
205
+ supplementalPRCount: result.supplementalPRCount,
206
+ loading: false,
207
+ limitReached: result.limitReached,
208
+ },
209
+ error: undefined,
210
+ errorKind: undefined,
211
+ fetchedAt: Date.now(),
212
+ }))
135
213
  } catch (e: unknown) {
136
214
  if (isStale()) return
137
- const rl = parseRateLimitError(e)
215
+ const rl = recordRateLimit(e)
138
216
  setState((s) => ({
139
217
  ...s,
140
218
  status: DashboardStatus.Error,
141
219
  repo: s.repo,
142
- prs: rl.isRateLimit ? s.prs : [],
143
- closedLoaded: rl.isRateLimit ? s.closedLoaded : false,
144
- truncated: rl.isRateLimit ? s.truncated : { open: false, closed: false },
220
+ prs: rl.isRateLimit &&
221
+ s.pagination.listing === listing &&
222
+ s.pagination.scope === scope &&
223
+ s.pagination.scopeValue === scopeValue
224
+ ? s.prs
225
+ : [],
226
+ pagination: rl.isRateLimit &&
227
+ s.pagination.listing === listing &&
228
+ s.pagination.scope === scope &&
229
+ s.pagination.scopeValue === scopeValue
230
+ ? { ...s.pagination, loading: false }
231
+ : {
232
+ listing,
233
+ scope,
234
+ scopeValue,
235
+ cursor: null,
236
+ hasMore: false,
237
+ totalCount: null,
238
+ pagesLoaded: 0,
239
+ searchResultsFetched: 0,
240
+ supplementalPRCount: 0,
241
+ loading: false,
242
+ limitReached: false,
243
+ },
145
244
  error: rl.message ?? prListErrorMessage(e),
146
245
  errorKind: rl.isRateLimit ? "rate-limit" : prListErrorKind(e),
147
246
  fetchedAt: Date.now(),
@@ -150,44 +249,116 @@ export function useDashboard(
150
249
  })()
151
250
  currentRefreshToken = token
152
251
  inFlight = promise
153
- inFlightIncludesClosed = wantClosed
252
+ inFlightFilterKey = filterKey
154
253
  promise.finally(release)
155
254
  return inFlight
156
255
  }
157
256
 
158
- const refreshOne = async (n: number) => {
159
- const prs = state().prs
160
- const idx = prs.findIndex((p) => p.number === n)
161
- if (idx < 0) return
162
- const repo = state().repo
163
- if (!repo) return
164
- try {
165
- const updated = await fetchOnePR(repo, n)
166
- setState((s) => ({
167
- ...s,
168
- prs: s.prs.map((p) => p.number === n
257
+ const loadMore = async (): Promise<void> => {
258
+ if (rateLimitActive()) return
259
+ const before = state()
260
+ const listing = statusFilter()
261
+ const scope = scopeFilter()
262
+ const repo = before.repo
263
+ const cursor = before.pagination.cursor
264
+ if (
265
+ !repo ||
266
+ before.pagination.listing !== listing ||
267
+ before.pagination.scope !== scope ||
268
+ before.pagination.scopeValue !== (scope === "branch" ? before.currentBranch : null) ||
269
+ !before.pagination.hasMore ||
270
+ !cursor
271
+ ) return
272
+ const scopeValue = before.pagination.scopeValue
273
+ const requestKey = `${repo.owner}/${repo.repo}:${listing}:${scope}:${scopeValue ?? ""}:${cursor}`
274
+ const existingRequest = loadMoreInFlight.get(requestKey)
275
+ if (existingRequest) return existingRequest
276
+
277
+ setState((s) => s.pagination.listing === listing && s.pagination.cursor === cursor
278
+ ? { ...s, pagination: { ...s.pagination, loading: true } }
279
+ : s)
280
+
281
+ const promise = (async () => {
282
+ try {
283
+ const branchPushOwner = scope === "branch"
284
+ ? await detectPushRemoteOwner(await cwd(), before.currentBranch)
285
+ : null
286
+ const result = await repositoryPRs(
287
+ repo,
288
+ pageBatchSize,
289
+ requestTimeoutMs,
290
+ listing,
291
+ cursor,
292
+ scope,
293
+ scopeValue,
294
+ before.pagination.searchResultsFetched,
295
+ recentPRsLimit,
296
+ branchPushOwner,
297
+ )
298
+ setState((s) => {
299
+ const sameRepo = s.repo?.owner === repo.owner && s.repo.repo === repo.repo
300
+ if (
301
+ !sameRepo ||
302
+ s.pagination.listing !== listing ||
303
+ s.pagination.scope !== scope ||
304
+ s.pagination.scopeValue !== scopeValue ||
305
+ s.pagination.cursor !== cursor
306
+ ) return s
307
+ const knownNumbers = new Set(s.prs.map((pr) => pr.number))
308
+ return {
309
+ ...s,
310
+ status: DashboardStatus.Ok,
311
+ prs: [...s.prs, ...result.prs.filter((pr) => !knownNumbers.has(pr.number))],
312
+ pagination: {
313
+ listing,
314
+ scope,
315
+ scopeValue,
316
+ cursor: result.endCursor,
317
+ hasMore: result.hasMore,
318
+ totalCount: s.pagination.supplementalPRCount > 0
319
+ ? s.pagination.totalCount
320
+ : scope === "branch"
321
+ ? s.pagination.totalCount === null
322
+ ? null
323
+ : Math.max(0, s.pagination.totalCount - result.filteredPRCount)
324
+ : result.totalCount ?? s.pagination.totalCount,
325
+ pagesLoaded: s.pagination.pagesLoaded + result.fetchedPages,
326
+ searchResultsFetched: s.pagination.searchResultsFetched + result.searchResultsFetched,
327
+ supplementalPRCount: s.pagination.supplementalPRCount,
328
+ loading: false,
329
+ limitReached: result.limitReached,
330
+ },
331
+ viewerLogin: result.viewerLogin ?? s.viewerLogin,
332
+ fetchedAt: Date.now(),
333
+ error: undefined,
334
+ errorKind: undefined,
335
+ }
336
+ })
337
+ } catch (e: unknown) {
338
+ const rl = recordRateLimit(e)
339
+ setState((s) =>
340
+ s.pagination.listing === listing &&
341
+ s.pagination.scope === scope &&
342
+ s.pagination.scopeValue === scopeValue &&
343
+ s.pagination.cursor === cursor
169
344
  ? {
170
- ...updated,
171
- checkStatuses: updated.checkStatuses ?? p.checkStatuses,
172
- reviewThreads: updated.reviewThreads ?? p.reviewThreads,
345
+ ...s,
346
+ status: DashboardStatus.Error,
347
+ pagination: { ...s.pagination, loading: false },
348
+ error: rl.message ?? prListErrorMessage(e),
349
+ errorKind: rl.isRateLimit ? "rate-limit" : prListErrorKind(e),
350
+ fetchedAt: Date.now(),
173
351
  }
174
- : p),
175
- fetchedAt: Date.now(),
176
- }))
177
- } catch {}
352
+ : s)
353
+ }
354
+ })()
355
+ loadMoreInFlight.set(requestKey, promise)
356
+ try {
357
+ await promise
358
+ } finally {
359
+ if (loadMoreInFlight.get(requestKey) === promise) loadMoreInFlight.delete(requestKey)
360
+ }
178
361
  }
179
362
 
180
- return { refresh, refreshOne }
181
- }
182
-
183
- function timeoutRace<T>(ms: number, fn: () => Promise<T>): Promise<T> {
184
- return new Promise<T>((resolve, reject) => {
185
- const timer = setTimeout(() => {
186
- reject(new Error(`Operation timed out after ${ms / 1000}s`))
187
- }, ms)
188
- fn().then(
189
- (val) => { clearTimeout(timer); resolve(val) },
190
- (err) => { clearTimeout(timer); reject(err) },
191
- )
192
- })
363
+ return { refresh, loadMore }
193
364
  }