opencode-github-pr 0.0.0-stage → 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
+ }
@@ -0,0 +1,25 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import open from "open"
3
+ import type { Context as TuiPluginContext } from "@opencode/plugin/tui/context"
4
+ import { prTargetUrl } from "../domain/pr-links"
5
+ import type { DashboardContext, PRLinkTarget } from "../domain/types"
6
+
7
+ export interface PrActions {
8
+ openPR: (n: number, target?: PRLinkTarget) => Promise<void>
9
+ }
10
+
11
+ // Build callbacks used by the sidebar and keymap using the V2 local TUI API.
12
+ export function createActions(api: TuiPluginContext, ctx: DashboardContext): PrActions {
13
+ const openPR = async (n: number, target: PRLinkTarget = "overview") => {
14
+ const pr = ctx.state().prs.find((p) => p.number === n)
15
+ if (!pr) return
16
+ try {
17
+ await open(prTargetUrl(pr.url, target))
18
+ api.ui.toast.show({ variant: "info", message: `Opening #${n} in browser…`, duration: 1500 })
19
+ } catch {
20
+ api.ui.toast.show({ variant: "error", message: `Couldn't open #${n} in browser`, duration: 2500 })
21
+ }
22
+ }
23
+
24
+ return { openPR }
25
+ }
@@ -0,0 +1,165 @@
1
+ import type { PRScope, PRStatusFilter } from "../domain/types"
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"
9
+
10
+ export const DEFAULT_ICONS = {
11
+ openPR: "",
12
+ closedPR: "",
13
+ draftPR: "",
14
+ mergedPR: "",
15
+ review: "",
16
+ openComment: "󰅺",
17
+ check: "●",
18
+ scope: "",
19
+ loading: "󰔟",
20
+ info: "",
21
+ error: "",
22
+ previousPage: "",
23
+ nextPage: "",
24
+ }
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
+
44
+ export type DashboardIcons = Record<keyof typeof DEFAULT_ICONS, string>
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
+
60
+ export type DashboardOptions = {
61
+ enabled: boolean
62
+ pageSize: number
63
+ pagesPerBatch: number
64
+ refreshIntervalMs: number
65
+ requestTimeoutMs: number
66
+ recentPRsLimit: number
67
+ defaultScope: PRScope
68
+ defaultStatusFilter: PRStatusFilter
69
+ iconStyle: IconStyle
70
+ showSingleStatusCount: boolean
71
+ spacing: DashboardSpacing
72
+ colors: Partial<Skin>
73
+ icons: DashboardIcons
74
+ }
75
+
76
+ type DashboardOptionsInput = {
77
+ enabled?: unknown
78
+ pageSize?: unknown
79
+ pagesPerBatch?: unknown
80
+ refreshIntervalMs?: unknown
81
+ requestTimeoutMs?: unknown
82
+ recentPRsLimit?: unknown
83
+ defaultScope?: unknown
84
+ defaultStatusFilter?: unknown
85
+ iconStyle?: unknown
86
+ showSingleStatusCount?: unknown
87
+ spacing?: unknown
88
+ colors?: unknown
89
+ icons?: unknown
90
+ }
91
+
92
+ const scopes: PRScope[] = ["branch", "author", "assignee", "all"]
93
+ const statusFilters: PRStatusFilter[] = ["open", "closed", "all"]
94
+
95
+ export const DEFAULT_PAGE_SIZE = 5
96
+ export const DEFAULT_PAGES_PER_BATCH = DEFAULT_TUI_PAGES_PER_BATCH
97
+ export const DEFAULT_REFRESH_INTERVAL_MS = 60_000
98
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
99
+
100
+ function positiveNumber(value: unknown, fallback: number): number {
101
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.max(1, Math.floor(value)) : fallback
102
+ }
103
+
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> {
129
+ if (!input || typeof input !== "object" || Array.isArray(input)) return {}
130
+ const result: Partial<T> = {}
131
+ for (const key of Object.keys(defaults) as Array<keyof T>) {
132
+ const value = (input as Record<string, unknown>)[key as string]
133
+ if (typeof value === "string" && (value.trim() || (allowEmpty && value === ""))) {
134
+ result[key] = value as T[keyof T]
135
+ }
136
+ }
137
+ return result
138
+ }
139
+
140
+ function mergeStrings<T extends Record<string, string>>(defaults: T, input: unknown, allowEmpty = false): T {
141
+ return { ...defaults, ...stringOverrides(defaults, input, allowEmpty) }
142
+ }
143
+
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
+
148
+ return {
149
+ enabled: input.enabled !== false,
150
+ pageSize: positiveNumber(input.pageSize, DEFAULT_PAGE_SIZE),
151
+ pagesPerBatch: Math.max(MIN_PAGES_PER_BATCH, positiveNumber(input.pagesPerBatch, DEFAULT_PAGES_PER_BATCH)),
152
+ refreshIntervalMs: positiveNumber(input.refreshIntervalMs, DEFAULT_REFRESH_INTERVAL_MS),
153
+ requestTimeoutMs: positiveNumber(input.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS),
154
+ recentPRsLimit: nonNegativeInteger(input.recentPRsLimit, DEFAULT_RECENT_PRS_LIMIT, MAX_RECENT_PRS_LIMIT),
155
+ defaultScope: scopes.includes(input.defaultScope as PRScope) ? (input.defaultScope as PRScope) : "author",
156
+ defaultStatusFilter: statusFilters.includes(input.defaultStatusFilter as PRStatusFilter)
157
+ ? (input.defaultStatusFilter as PRStatusFilter)
158
+ : "open",
159
+ iconStyle,
160
+ showSingleStatusCount: input.showSingleStatusCount === true,
161
+ spacing: spacingOverrides(input.spacing),
162
+ colors: stringOverrides(DEFAULT_SKIN, input.colors),
163
+ icons: mergeStrings(defaultIcons, input.icons, true),
164
+ }
165
+ }
@@ -0,0 +1,53 @@
1
+ // Convert OpenCode V2 semantic theme tokens into the palette used by the PR
2
+ // dashboard components.
3
+
4
+ import type { ResolvedTheme } from "@opencode/theme/tui"
5
+
6
+ export const DEFAULT_SKIN = {
7
+ panelAlt: "#1d1d1d",
8
+ text: "#e5e5e5",
9
+ muted: "#888888",
10
+ accent: "#5f87ff",
11
+ success: "#5fbf5f",
12
+ warning: "#d8a657",
13
+ error: "#d86565",
14
+ draft: "#888888",
15
+ merged: "#a371f7",
16
+ }
17
+
18
+ export type Skin = {
19
+ panelAlt: string
20
+ text: string
21
+ muted: string
22
+ accent: string
23
+ success: string
24
+ warning: string
25
+ error: string
26
+ draft: string
27
+ merged: string
28
+ }
29
+
30
+ export function toHex(c: { toInts(): [number, number, number, number] }): string {
31
+ const [r, g, b] = c.toInts()
32
+ return (
33
+ "#" +
34
+ [r, g, b]
35
+ .map((n) => Math.max(0, Math.min(255, n)).toString(16).padStart(2, "0"))
36
+ .join("")
37
+ )
38
+ }
39
+
40
+ export function skin(t: ResolvedTheme, overrides: Partial<Skin> = {}): Skin {
41
+ return {
42
+ panelAlt: toHex(t.background.raised.base),
43
+ text: toHex(t.text.base),
44
+ muted: toHex(t.text.muted),
45
+ accent: toHex(t.text.action.primary.base),
46
+ success: toHex(t.text.feedback.success.base),
47
+ warning: toHex(t.text.feedback.warning.base),
48
+ error: toHex(t.text.feedback.error.base),
49
+ draft: toHex(t.text.muted),
50
+ merged: toHex(t.text.feedback.info.base),
51
+ ...overrides,
52
+ }
53
+ }
@@ -0,0 +1,364 @@
1
+ // Data-fetching logic for the PR dashboard.
2
+ //
3
+ // Reactive signals (createSignal, onCleanup, etc.) must NOT be imported
4
+ // here. This is a .ts file, and Bun's @opentui/solid plugin only rewrites
5
+ // solid-js imports to the reactive build for .tsx/.jsx files. Importing
6
+ // createSignal in a .ts file silently gets the SSR (non-reactive) build,
7
+ // which causes state updates to never propagate to the view.
8
+ //
9
+ // All signals are created in the entry .tsx file and passed in.
10
+ import type { Context as TuiPluginContext } from "@opencode/plugin/tui/context"
11
+ import {
12
+ DashboardStatus,
13
+ type DashboardState,
14
+ type PRScope,
15
+ type PRStatusFilter,
16
+ } from "../domain/types"
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"
23
+ import { prListErrorKind, prListErrorMessage, parseRateLimitError } from "../domain/messages"
24
+ import { DEFAULT_PAGES_PER_BATCH, DEFAULT_PAGE_SIZE, DEFAULT_REQUEST_TIMEOUT_MS } from "./config"
25
+
26
+ export function useDashboard(
27
+ api: TuiPluginContext,
28
+ state: () => DashboardState,
29
+ setState: (fn: (s: DashboardState) => DashboardState) => void,
30
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
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,
36
+ ): {
37
+ refresh: () => Promise<void>
38
+ loadMore: () => Promise<void>
39
+ } {
40
+ // Resolve the working directory explicitly when the TUI exposes it, so
41
+ // repo detection doesn't depend on where opencode happens to launch.
42
+ // Falls back to process.cwd() for tests that chdir() into a temp repo.
43
+ const cwd = async (): Promise<string> => {
44
+ const route = api.ui.router.current()
45
+ if (route.type === "session") {
46
+ let session = api.data.session.get(route.sessionID)
47
+ if (!session) {
48
+ try {
49
+ session = await api.client.session.get({ sessionID: route.sessionID })
50
+ } catch {
51
+ // Fall back to the current TUI location if the session is unavailable.
52
+ }
53
+ }
54
+ const directory = session?.location.directory
55
+ if (directory) return directory
56
+ }
57
+ return api.location?.directory ?? api.data.location.default().directory ?? process.cwd()
58
+ }
59
+
60
+ let inFlight: Promise<void> | null = null
61
+ let inFlightFilterKey: string | null = null
62
+ const loadMoreInFlight = new Map<string, Promise<void>>()
63
+ let refreshToken = 0
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)
87
+
88
+ const refresh = async (): Promise<void> => {
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}`
112
+ if (inFlight) {
113
+ if (filterKey !== inFlightFilterKey) return inFlight.then((): Promise<void> => refresh())
114
+ return inFlight
115
+ }
116
+ const prev = state()
117
+ const token = ++refreshToken
118
+ const release = () => {
119
+ if (inFlight && currentRefreshToken === token) inFlight = null
120
+ }
121
+ const promise = (async () => {
122
+ const isStale = () => token !== refreshToken
123
+ let scopeValue: string | null = null
124
+ try {
125
+ const directory = await cwd()
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
134
+ const isFirstLoad = prev.fetchedAt === null
135
+ const isDirChange =
136
+ !!prev.repo && !!repo && (prev.repo.owner !== repo.owner || prev.repo.repo !== repo.repo)
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
144
+ if (showLoading && prev.status !== DashboardStatus.Loading) {
145
+ if (isStale()) return
146
+ setState((s) => ({ ...s, error: undefined, status: DashboardStatus.Loading }))
147
+ }
148
+ if (!repo) {
149
+ if (isStale()) return
150
+ setState((s) => ({
151
+ ...s,
152
+ status: DashboardStatus.NoRepo,
153
+ repo: null,
154
+ prs: [],
155
+ currentBranch: null,
156
+ viewerLogin: null,
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
+ },
170
+ error: undefined,
171
+ errorKind: undefined,
172
+ fetchedAt: Date.now(),
173
+ }))
174
+ return
175
+ }
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,
187
+ )
188
+ if (isStale()) return
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
+ }))
213
+ } catch (e: unknown) {
214
+ if (isStale()) return
215
+ const rl = recordRateLimit(e)
216
+ setState((s) => ({
217
+ ...s,
218
+ status: DashboardStatus.Error,
219
+ repo: s.repo,
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
+ },
244
+ error: rl.message ?? prListErrorMessage(e),
245
+ errorKind: rl.isRateLimit ? "rate-limit" : prListErrorKind(e),
246
+ fetchedAt: Date.now(),
247
+ }))
248
+ }
249
+ })()
250
+ currentRefreshToken = token
251
+ inFlight = promise
252
+ inFlightFilterKey = filterKey
253
+ promise.finally(release)
254
+ return inFlight
255
+ }
256
+
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
344
+ ? {
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(),
351
+ }
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
+ }
361
+ }
362
+
363
+ return { refresh, loadMore }
364
+ }
@@ -0,0 +1,27 @@
1
+ // Pure formatting helpers used by the TUI sidebar.
2
+
3
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" })
4
+
5
+ export function truncateTitle(title: string, maxWidth: number): string {
6
+ const budget = Math.max(1, Math.floor(maxWidth))
7
+ const normalized = title.replace(/\s+/gu, " ").trim()
8
+ if (Bun.stringWidth(normalized) <= budget) return normalized
9
+
10
+ const contentBudget = Math.max(0, budget - Bun.stringWidth("…"))
11
+ let wholeWords = ""
12
+ for (const word of normalized.split(" ")) {
13
+ const next = wholeWords ? `${wholeWords} ${word}` : word
14
+ if (Bun.stringWidth(next) > contentBudget) break
15
+ wholeWords = next
16
+ }
17
+ if (wholeWords) return `${wholeWords}…`
18
+
19
+ // If even the first word is too long, fall back to a grapheme-safe cut.
20
+ let prefix = ""
21
+ for (const { segment } of graphemes.segment(normalized)) {
22
+ const next = prefix + segment
23
+ if (Bun.stringWidth(next) > contentBudget) break
24
+ prefix = next
25
+ }
26
+ return `${prefix}…`
27
+ }