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,183 @@
1
+ import type { PRListErrorKind } from "./types"
2
+
3
+ // Centralized user-facing error messages for the PR dashboard plugins.
4
+ //
5
+ // Message convention:
6
+ // - Success messages are verb-specific and live in the tool/action
7
+ // that produces them (e.g. "Requested review from @alice on PR #42").
8
+ // - Tool/action failures use an error string appropriate to the action.
9
+ // - Reusable domain states (no repo, no auth, rate limit, HTTP status
10
+ // categories) have dedicated entries here because they're shared
11
+ // across multiple actions.
12
+
13
+ export const errorMessages = {
14
+ // auth
15
+ noAuthToken:
16
+ "Not authenticated; set a GitHub token or run `gh auth login`.",
17
+
18
+ // repo / session context
19
+ noRepo: "Not a git repo",
20
+
21
+ // server-side tool errors
22
+ prListing: {
23
+ unauthorized: "Not authorised, check token is valid",
24
+ forbidden: "Forbidden, check token scope",
25
+ rateLimited: "Rate limited",
26
+ notFound: "Repo not found",
27
+ unprocessable: "Invalid query",
28
+ timeout: "Timed out",
29
+ network: (msg: string) => `Network error: ${msg}`,
30
+ server: "GitHub server error",
31
+ unknown: (msg: string) => msg,
32
+ },
33
+
34
+ unknown: "unknown",
35
+
36
+ // dashboard view banners / empty states
37
+ noMatchingPRs: "No matching PRs",
38
+ }
39
+
40
+ function isRecord(value: unknown): value is Record<string, unknown> {
41
+ return typeof value === "object" && value !== null
42
+ }
43
+
44
+ // Classify errors from GitHub HTTP status, aborts/timeouts, network codes,
45
+ // and request messages when no status is available.
46
+ export function prListErrorKind(e: unknown): PRListErrorKind {
47
+ if (!e) return "unknown"
48
+ const details = isRecord(e) ? e : {}
49
+ const graphqlErrors = Array.isArray(details.errors) ? details.errors : []
50
+ const graphqlTypes = graphqlErrors.filter(isRecord).map((error) => error.type)
51
+ if (graphqlTypes.includes("NOT_FOUND")) return "not-found"
52
+ if (graphqlTypes.includes("FORBIDDEN")) return "forbidden"
53
+ if (graphqlTypes.includes("RATE_LIMITED")) return "rate-limit"
54
+ const status = typeof details.status === "number" ? details.status : undefined
55
+ const name = typeof details.name === "string" ? details.name : undefined
56
+ const code = typeof details.code === "string" ? details.code : undefined
57
+ const message = e instanceof Error ? e.message : String(e)
58
+ const lower = message.toLowerCase()
59
+
60
+ if (/not authenticated|unauthor/i.test(lower)) return "authentication"
61
+ if (name === "AbortError") return "timeout"
62
+ if (
63
+ code &&
64
+ ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN"].includes(code)
65
+ ) {
66
+ return "network"
67
+ }
68
+
69
+ switch (status) {
70
+ case 401:
71
+ return "authentication"
72
+ case 403:
73
+ return /rate limit/i.test(lower) ? "rate-limit" : "forbidden"
74
+ case 404:
75
+ return "not-found"
76
+ case 408:
77
+ return "timeout"
78
+ case 422:
79
+ return "invalid-query"
80
+ }
81
+ if (status && status >= 500) return "server"
82
+
83
+ // GitHub request message fallback (no status, just text)
84
+ if (/rate limit/i.test(lower)) return "rate-limit"
85
+ if (/not found|\b404\b/.test(lower)) return "not-found"
86
+ if (/unauthor|\b401\b/.test(lower)) return "authentication"
87
+ if (/forbidden|\b403\b/.test(lower)) return "forbidden"
88
+ if (/network|econn|enotfound|etimedout|eai_again/.test(lower)) {
89
+ return "network"
90
+ }
91
+ if (/timeout|timed out/.test(lower)) return "timeout"
92
+
93
+ return "unknown"
94
+ }
95
+
96
+ // Map a thrown error to the existing user-facing detail string.
97
+ export function prListErrorMessage(e: unknown): string {
98
+ if (!e) return errorMessages.prListing.unknown("unknown")
99
+ const details = isRecord(e) ? e : {}
100
+ const message = e instanceof Error ? e.message : String(e)
101
+ const status = typeof details.status === "number" ? details.status : undefined
102
+ const code = typeof details.code === "string" ? details.code : undefined
103
+
104
+ switch (prListErrorKind(e)) {
105
+ case "authentication":
106
+ return status === 401 || /unauthor/i.test(message)
107
+ ? errorMessages.prListing.unauthorized
108
+ : errorMessages.noAuthToken
109
+ case "forbidden":
110
+ return errorMessages.prListing.forbidden
111
+ case "rate-limit":
112
+ return errorMessages.prListing.rateLimited
113
+ case "not-found":
114
+ return errorMessages.prListing.notFound
115
+ case "invalid-query":
116
+ return errorMessages.prListing.unprocessable
117
+ case "timeout":
118
+ return errorMessages.prListing.timeout
119
+ case "network":
120
+ return errorMessages.prListing.network(code ?? message)
121
+ case "server":
122
+ return errorMessages.prListing.server
123
+ case "unknown":
124
+ return errorMessages.prListing.unknown(message)
125
+ }
126
+ }
127
+
128
+ export type RateLimitInfo =
129
+ | { isRateLimit: true; message: string; resetAt: number; isSecondary: boolean }
130
+ | { isRateLimit: false; message: null; resetAt: null; isSecondary: false }
131
+
132
+ // Detects GitHub primary/secondary rate-limit errors and extracts the
133
+ // reset time from x-ratelimit-reset or retry-after. Used by useDashboard to
134
+ // preserve the existing PR list when the error is a rate limit (the PRs
135
+ // are still valid; only the fetch failed).
136
+ export function parseRateLimitError(e: unknown): RateLimitInfo {
137
+ const details = isRecord(e) ? e : {}
138
+ const msg = typeof details.message === "string" ? details.message : ""
139
+ const graphqlErrors = Array.isArray(details.errors) ? details.errors : []
140
+ const hasGraphQLRateLimit = graphqlErrors.some((error) =>
141
+ isRecord(error) && error.type === "RATE_LIMITED"
142
+ )
143
+ const status = typeof details.status === "number" ? details.status : undefined
144
+ const isRateLimit =
145
+ status === 429 ||
146
+ (status === 403 && /rate limit/i.test(msg)) ||
147
+ hasGraphQLRateLimit ||
148
+ /rate limit (already exceeded|exceeded)/i.test(msg) ||
149
+ /api rate limit/i.test(msg)
150
+ if (!isRateLimit) return { isRateLimit: false, message: null, resetAt: null, isSecondary: false }
151
+
152
+ const response = isRecord(details.response) ? details.response : {}
153
+ const headers = isRecord(response.headers)
154
+ ? response.headers
155
+ : isRecord(details.headers)
156
+ ? details.headers
157
+ : {}
158
+ const rawDate = headers.date ?? headers.Date
159
+ const serverNow = rawDate === undefined ? null : Date.parse(String(rawDate))
160
+ const now = Date.now()
161
+ const clockOffset = serverNow !== null && Number.isFinite(serverNow) ? serverNow - now : 0
162
+ const rawRetryAfter = headers["retry-after"] ?? headers["Retry-After"]
163
+ const retryAfter = rawRetryAfter === undefined
164
+ ? null
165
+ : /^\d+(?:\.\d+)?$/.test(String(rawRetryAfter))
166
+ ? (serverNow !== null && Number.isFinite(serverNow) ? serverNow : now) +
167
+ Number(rawRetryAfter) * 1000 - clockOffset
168
+ : Number.isNaN(Date.parse(String(rawRetryAfter)))
169
+ ? null
170
+ : Date.parse(String(rawRetryAfter)) - clockOffset
171
+ const rawReset = headers["x-ratelimit-reset"] ?? headers["X-RateLimit-Reset"]
172
+ const primaryReset = rawReset ? parseInt(String(rawReset), 10) * 1000 - clockOffset : null
173
+ const isSecondary =
174
+ /secondary rate limit/i.test(msg) || status === 429 || retryAfter !== null
175
+ const resetAt = isSecondary ? retryAfter ?? primaryReset : primaryReset
176
+ const resetText = resetAt ? new Date(resetAt).toLocaleTimeString() : "unknown time"
177
+
178
+ let detail = `GitHub API rate limit exceeded — resets at ${resetText}.`
179
+ if (isSecondary) {
180
+ detail = `GitHub secondary rate limit hit (too many requests) — try again at ${resetText}.`
181
+ }
182
+ return { isRateLimit: true, message: detail, resetAt: resetAt ?? 0, isSecondary }
183
+ }
@@ -0,0 +1,40 @@
1
+ import type { PR, PRScope, PRStatusFilter } from "./types"
2
+
3
+ export const PR_SCOPES: PRScope[] = ["branch", "author", "assignee", "all"]
4
+ export const PR_STATUS_FILTERS: PRStatusFilter[] = ["open", "closed", "all"]
5
+
6
+ export function nextPRScope(scope: PRScope): PRScope {
7
+ return PR_SCOPES[(PR_SCOPES.indexOf(scope) + 1) % PR_SCOPES.length]
8
+ }
9
+
10
+ export function nextPRStatusFilter(status: PRStatusFilter): PRStatusFilter {
11
+ return PR_STATUS_FILTERS[(PR_STATUS_FILTERS.indexOf(status) + 1) % PR_STATUS_FILTERS.length]
12
+ }
13
+
14
+ export function filterPRs(
15
+ prs: PR[],
16
+ scope: PRScope,
17
+ status: PRStatusFilter,
18
+ currentBranch: string | null,
19
+ viewerLogin: string | null,
20
+ ): PR[] {
21
+ const login = viewerLogin?.toLowerCase()
22
+ return prs.filter((pr) => {
23
+ const matchesScope = (() => {
24
+ switch (scope) {
25
+ case "branch":
26
+ return currentBranch !== null && pr.headRefName === currentBranch
27
+ case "author":
28
+ return login !== undefined && pr.authorLogin.toLowerCase() === login
29
+ case "assignee":
30
+ return login !== undefined && pr.assigneeLogins.some((assignee) => assignee.toLowerCase() === login)
31
+ case "all":
32
+ return true
33
+ }
34
+ })()
35
+ const matchesStatus =
36
+ status === "all" ||
37
+ (status === "open" ? !pr.isClosed : pr.isClosed)
38
+ return matchesScope && matchesStatus
39
+ })
40
+ }
@@ -0,0 +1,12 @@
1
+ import type { PRLinkTarget } from "./types"
2
+
3
+ export function prTargetUrl(prUrl: string, target: PRLinkTarget = "overview"): string {
4
+ const base = prUrl.replace(/\/+$/, "")
5
+ if (target === "overview") return base
6
+ if (target === "mergeStatus") {
7
+ const url = new URL(base)
8
+ url.searchParams.set("panel", "mergeStatus")
9
+ return url.toString()
10
+ }
11
+ return `${base}/${target}`
12
+ }
@@ -0,0 +1,128 @@
1
+ // PR status evaluation: CI classification and review rollup.
2
+ // Pure functions over the PR type. Age formatting lives in ./format.
3
+
4
+ import type { PR } from "./types"
5
+
6
+ export type StatusCategory = "pass" | "fail" | "pending" | "neutral" | "none"
7
+ export type StatusGroup = { status: StatusCategory; count: number }
8
+
9
+ export function mergeReadiness(pr: PR): StatusCategory {
10
+ if (pr.reviewDecision === "CHANGES_REQUESTED") return "fail"
11
+ if (pr.mergeStateStatus === "DIRTY") return "fail"
12
+ if (pr.reviewDecision === "REVIEW_REQUIRED") return "pending"
13
+ if (pr.mergeStateStatus === "CLEAN" || pr.mergeStateStatus === "HAS_HOOKS") {
14
+ if (pr.reviewDecision === null || pr.reviewDecision === "APPROVED") return "pass"
15
+ return "neutral"
16
+ }
17
+ if (["BLOCKED", "BEHIND", "UNSTABLE"].includes(pr.mergeStateStatus)) return "pending"
18
+ return "none"
19
+ }
20
+
21
+ export function classifyCI(pr: PR): "pass" | "fail" | "pending" | "none" {
22
+ const state = pr.statusCheckRollup?.state
23
+ if (state === "SUCCESS") return "pass"
24
+ if (state === "FAILURE" || state === "ERROR") return "fail"
25
+ if (state === "PENDING" || state === "EXPECTED") return "pending"
26
+ return "none"
27
+ }
28
+
29
+ function classifyCheckStatus(state: string): Exclude<StatusCategory, "none"> {
30
+ switch (state.toUpperCase()) {
31
+ case "SUCCESS":
32
+ return "pass"
33
+ case "FAILURE":
34
+ case "ERROR":
35
+ case "ACTION_REQUIRED":
36
+ case "CANCELLED":
37
+ case "STARTUP_FAILURE":
38
+ case "TIMED_OUT":
39
+ return "fail"
40
+ case "EXPECTED":
41
+ case "IN_PROGRESS":
42
+ case "PENDING":
43
+ case "QUEUED":
44
+ case "REQUESTED":
45
+ case "WAITING":
46
+ return "pending"
47
+ default:
48
+ return "neutral"
49
+ }
50
+ }
51
+
52
+ const statusOrder: StatusCategory[] = ["pass", "fail", "pending", "neutral", "none"]
53
+
54
+ function orderedGroups(counts: Map<StatusCategory, number>): StatusGroup[] {
55
+ return statusOrder
56
+ .filter((status) => (counts.get(status) ?? 0) > 0)
57
+ .map((status) => ({ status, count: counts.get(status)! }))
58
+ }
59
+
60
+ export function checkStatusGroups(pr: PR): StatusGroup[] {
61
+ const contexts = (pr.checkStatuses ?? []).filter(Boolean)
62
+ if (contexts.length === 0) {
63
+ const status = classifyCI(pr)
64
+ return [{ status, count: status === "none" ? 0 : 1 }]
65
+ }
66
+
67
+ const counts = new Map<StatusCategory, number>()
68
+ for (const context of contexts) {
69
+ const status = classifyCheckStatus(context)
70
+ counts.set(status, (counts.get(status) ?? 0) + 1)
71
+ }
72
+ return orderedGroups(counts)
73
+ }
74
+
75
+ export function reviewStatusGroups(pr: PR): StatusGroup[] {
76
+ const summary = reviewSummary(pr)
77
+ return orderedGroups(new Map<StatusCategory, number>([
78
+ ["pass", summary.approved],
79
+ ["fail", summary.changes],
80
+ ["pending", summary.pending],
81
+ ["neutral", summary.commented],
82
+ ]))
83
+ }
84
+
85
+ export function commentThreadCounts(pr: PR): { open: number; resolved: number; truncated: boolean } | null {
86
+ if (pr.reviewThreads === null) return null
87
+ return pr.reviewThreads.reduce(
88
+ (counts, thread) => {
89
+ if (thread.isResolved) counts.resolved++
90
+ else counts.open++
91
+ return counts
92
+ },
93
+ { open: 0, resolved: 0, truncated: pr.reviewThreadsTruncated === true },
94
+ )
95
+ }
96
+
97
+ export function reviewSummary(pr: PR): {
98
+ approved: number
99
+ changes: number
100
+ pending: number
101
+ commented: number
102
+ } {
103
+ const pendingUsers = new Set<string>()
104
+ const pendingTeams = new Set<string>()
105
+ for (const request of pr.reviewRequests ?? []) {
106
+ if (request.type === "team") {
107
+ if (request.slug) pendingTeams.add(request.slug.toLowerCase())
108
+ } else if (request.login) {
109
+ pendingUsers.add(request.login.toLowerCase())
110
+ }
111
+ }
112
+ const approved = new Set<string>()
113
+ const changes = new Set<string>()
114
+ const commented = new Set<string>()
115
+ for (const r of pr.latestReviews ?? []) {
116
+ const login = r.author?.login
117
+ if (!login || pendingUsers.has(login.toLowerCase())) continue
118
+ if (r.state === "APPROVED") approved.add(login)
119
+ else if (r.state === "CHANGES_REQUESTED") changes.add(login)
120
+ else if (r.state === "COMMENTED") commented.add(login)
121
+ }
122
+ return {
123
+ approved: approved.size,
124
+ changes: changes.size,
125
+ pending: pendingUsers.size + pendingTeams.size,
126
+ commented: commented.size,
127
+ }
128
+ }
@@ -0,0 +1,94 @@
1
+ // Shared domain types for the PR dashboard plugins.
2
+ //
3
+ // Both the server and TUI pull PR data via Octokit, so they share a single
4
+ // PR shape (PR). Repo is non-null here; callers that may not have a repo
5
+ // use `Repo | null` explicitly.
6
+
7
+ export type PR = {
8
+ number: number
9
+ title: string
10
+ url: string
11
+ isDraft: boolean
12
+ isMerged: boolean
13
+ isClosed: boolean
14
+ headRefName: string
15
+ headRepositoryOwnerLogin?: string
16
+ authorLogin: string
17
+ assigneeLogins: string[]
18
+ additions: number
19
+ deletions: number
20
+ baseRefName: string
21
+ mergeable: string
22
+ mergeStateStatus: string
23
+ reviewDecision: string | null
24
+ statusCheckRollup: { state: string } | null
25
+ checkStatuses: string[] | null
26
+ reviewThreads: Array<{ isResolved: boolean }> | null
27
+ reviewThreadsTruncated?: boolean
28
+ reviewRequests: Array<
29
+ | { type: "user"; login: string }
30
+ | { type: "team"; slug: string }
31
+ > | null
32
+ latestReviews: Array<{ author: { login: string }; state: string }> | null
33
+ }
34
+
35
+ export type PRLinkTarget = "overview" | "mergeStatus" | "checks" | "files"
36
+
37
+ export type Repo = { owner: string; repo: string }
38
+
39
+ export type PRScope = "branch" | "author" | "assignee" | "all"
40
+ export type PRStatusFilter = "open" | "closed" | "all"
41
+
42
+ export enum DashboardStatus {
43
+ Loading = "loading",
44
+ Ok = "ok",
45
+ NoRepo = "no-repo",
46
+ Error = "error",
47
+ }
48
+
49
+ export type PRListErrorKind =
50
+ | "authentication"
51
+ | "forbidden"
52
+ | "rate-limit"
53
+ | "not-found"
54
+ | "invalid-query"
55
+ | "timeout"
56
+ | "network"
57
+ | "server"
58
+ | "unknown"
59
+
60
+ export type DashboardState = {
61
+ status: DashboardStatus
62
+ repo: Repo | null
63
+ prs: PR[]
64
+ currentBranch: string | null
65
+ viewerLogin: string | null
66
+ fetchedAt: number | null
67
+ // The active status listing is fetched from GitHub in cursor-based batches.
68
+ pagination: {
69
+ listing: PRStatusFilter
70
+ scope: PRScope
71
+ scopeValue: string | null
72
+ cursor: string | null
73
+ hasMore: boolean
74
+ totalCount: number | null
75
+ pagesLoaded: number
76
+ searchResultsFetched: number
77
+ supplementalPRCount: number
78
+ loading: boolean
79
+ limitReached: boolean
80
+ }
81
+ error?: string
82
+ errorKind?: PRListErrorKind
83
+ }
84
+
85
+ // The public surface of useDashboard() — the signal/accessor pairs and
86
+ // actions exposed to the view layer and actions module. Defined here so
87
+ // the actions module can import it without depending on usePRData.
88
+ export interface DashboardContext {
89
+ state: () => DashboardState
90
+ refresh: () => Promise<void>
91
+ loadMore: () => Promise<void>
92
+ selectedIdx: () => number
93
+ setSelectedIdx: (n: number) => void
94
+ }