opencode-github-pr 0.0.0-stage → 0.1.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,193 @@
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 Repo,
15
+ } from "../domain/types"
16
+ import { currentBranch, detectRepo } from "../infra/git"
17
+ import { repositoryPRs, fetchOnePR } from "../infra/loader"
18
+ import { prListErrorKind, prListErrorMessage, parseRateLimitError } from "../domain/messages"
19
+ import { DEFAULT_MAX_PR_PAGES, DEFAULT_REQUEST_TIMEOUT_MS } from "./config"
20
+
21
+ export function useDashboard(
22
+ api: TuiPluginContext,
23
+ state: () => DashboardState,
24
+ setState: (fn: (s: DashboardState) => DashboardState) => void,
25
+ 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,
29
+ ): {
30
+ refresh: () => Promise<void>
31
+ refreshOne: (n: number) => Promise<void>
32
+ } {
33
+ // Resolve the working directory explicitly when the TUI exposes it, so
34
+ // repo detection doesn't depend on where opencode happens to launch.
35
+ // Falls back to process.cwd() for tests that chdir() into a temp repo.
36
+ const cwd = async (): Promise<string> => {
37
+ const route = api.ui.router.current()
38
+ if (route.type === "session") {
39
+ let session = api.data.session.get(route.sessionID)
40
+ if (!session) {
41
+ try {
42
+ session = await api.client.session.get({ sessionID: route.sessionID })
43
+ } catch {
44
+ // Fall back to the current TUI location if the session is unavailable.
45
+ }
46
+ }
47
+ const directory = session?.location.directory
48
+ if (directory) return directory
49
+ }
50
+ return api.location?.directory ?? api.data.location.default().directory ?? process.cwd()
51
+ }
52
+
53
+ let inFlight: Promise<void> | null = null
54
+ let inFlightIncludesClosed = false
55
+ let refreshToken = 0
56
+ let currentRefreshToken = 0
57
+
58
+ const refresh = async (): Promise<void> => {
59
+ const wantClosed = includeClosed()
60
+ 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())
64
+ return inFlight
65
+ }
66
+ const prev = state()
67
+ const token = ++refreshToken
68
+ const release = () => {
69
+ if (inFlight && currentRefreshToken === token) inFlight = null
70
+ }
71
+ const promise = (async () => {
72
+ const isStale = () => token !== refreshToken
73
+ try {
74
+ const directory = await cwd()
75
+ const repo = detectRepo(directory)
76
+ const isFirstLoad = prev.fetchedAt === null
77
+ const isDirChange =
78
+ !!prev.repo && !!repo && (prev.repo.owner !== repo.owner || prev.repo.repo !== repo.repo)
79
+ const showLoading = isFirstLoad || isDirChange || prev.status === DashboardStatus.Loading
80
+ if (showLoading && prev.status !== DashboardStatus.Loading) {
81
+ if (isStale()) return
82
+ setState((s) => ({ ...s, error: undefined, status: DashboardStatus.Loading }))
83
+ }
84
+ if (!repo) {
85
+ if (isStale()) return
86
+ setState((s) => ({
87
+ ...s,
88
+ status: DashboardStatus.NoRepo,
89
+ repo: null,
90
+ prs: [],
91
+ currentBranch: null,
92
+ viewerLogin: null,
93
+ closedLoaded: false,
94
+ truncated: { open: false, closed: false },
95
+ error: undefined,
96
+ errorKind: undefined,
97
+ fetchedAt: Date.now(),
98
+ }))
99
+ return
100
+ }
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
+ ]),
106
+ )
107
+ 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
+ })
135
+ } catch (e: unknown) {
136
+ if (isStale()) return
137
+ const rl = parseRateLimitError(e)
138
+ setState((s) => ({
139
+ ...s,
140
+ status: DashboardStatus.Error,
141
+ 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 },
145
+ error: rl.message ?? prListErrorMessage(e),
146
+ errorKind: rl.isRateLimit ? "rate-limit" : prListErrorKind(e),
147
+ fetchedAt: Date.now(),
148
+ }))
149
+ }
150
+ })()
151
+ currentRefreshToken = token
152
+ inFlight = promise
153
+ inFlightIncludesClosed = wantClosed
154
+ promise.finally(release)
155
+ return inFlight
156
+ }
157
+
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
169
+ ? {
170
+ ...updated,
171
+ checkStatuses: updated.checkStatuses ?? p.checkStatuses,
172
+ reviewThreads: updated.reviewThreads ?? p.reviewThreads,
173
+ }
174
+ : p),
175
+ fetchedAt: Date.now(),
176
+ }))
177
+ } catch {}
178
+ }
179
+
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
+ })
193
+ }
@@ -0,0 +1,38 @@
1
+ // Pure formatting helpers used by the TUI sidebar: title truncation and
2
+ // relative age rendering.
3
+
4
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" })
5
+
6
+ export function truncateTitle(title: string, maxWidth: number): string {
7
+ const budget = Math.max(1, Math.floor(maxWidth))
8
+ const normalized = title.replace(/\s+/gu, " ").trim()
9
+ if (Bun.stringWidth(normalized) <= budget) return normalized
10
+
11
+ const contentBudget = Math.max(0, budget - Bun.stringWidth("…"))
12
+ let prefix = ""
13
+ let truncated = ""
14
+ for (const { segment } of graphemes.segment(normalized)) {
15
+ const next = prefix + segment
16
+ if (Bun.stringWidth(next) > contentBudget) break
17
+ prefix = next
18
+ truncated = prefix
19
+ }
20
+
21
+ const wordBoundary = truncated.lastIndexOf(" ")
22
+ if (wordBoundary > 0) truncated = truncated.slice(0, wordBoundary).trimEnd()
23
+ return `${truncated}…`
24
+ }
25
+
26
+ export function formatAge(iso: string): string {
27
+ const t = Date.parse(iso)
28
+ if (Number.isNaN(t)) return ""
29
+ const diff = Date.now() - t
30
+ const m = Math.floor(diff / 60_000)
31
+ if (m < 1) return "now"
32
+ if (m < 60) return `${m}m`
33
+ const h = Math.floor(m / 60)
34
+ if (h < 24) return `${h}h`
35
+ const d = Math.floor(h / 24)
36
+ if (d < 30) return `${d}d`
37
+ return `${Math.floor(d / 30)}mo`
38
+ }
@@ -0,0 +1,33 @@
1
+ // Login display helpers and bot-account aliases used by the TUI sidebar.
2
+
3
+ export const BOT_ALIASES: Record<string, string> = {
4
+ "copilot-pull-request-reviewer": "copilot",
5
+ "copilot-swe-agent": "copilot",
6
+ "copilot": "copilot",
7
+ "dependabot": "dependabot",
8
+ "dependabot-preview": "dependabot",
9
+ "github-actions": "github-actions",
10
+ "renovate": "renovate",
11
+ "renovate-bot": "renovate",
12
+ "graphite-app": "graphite",
13
+ "graphite-ci": "graphite",
14
+ }
15
+
16
+ export function displayLogin(login: string): string {
17
+ const lower = login.toLowerCase()
18
+ if (BOT_ALIASES[lower]) return BOT_ALIASES[lower]
19
+ if (lower.endsWith("[bot]")) {
20
+ const base = lower.slice(0, -5)
21
+ return BOT_ALIASES[base] ?? base
22
+ }
23
+ if (lower.endsWith("-bot")) {
24
+ const base = lower.slice(0, -4)
25
+ return BOT_ALIASES[base] ?? base
26
+ }
27
+ return login
28
+ }
29
+
30
+ export function ellipsize(name: string, maxLen = 9): string {
31
+ if (name.length <= maxLen) return name
32
+ return name.slice(0, 4) + "…" + name.slice(-4)
33
+ }
@@ -0,0 +1,161 @@
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 the generic `failed(msg)` fallback
9
+ // ("Failed: <detail>"). The tool description provides context; the
10
+ // error string just conveys what went wrong.
11
+ // - Reusable domain states (no repo, no auth, rate limit, HTTP status
12
+ // categories) have dedicated entries here because they're shared
13
+ // across multiple actions.
14
+
15
+ export const errorMessages = {
16
+ // auth
17
+ noAuthToken:
18
+ "Not authenticated; set a GitHub token or run `gh auth login`.",
19
+
20
+ // repo / session context
21
+ noRepo: "Not a git repo",
22
+
23
+ // server-side tool errors
24
+ prListing: {
25
+ unauthorized: "Not authorised, check token is valid",
26
+ forbidden: "Forbidden, check token scope",
27
+ rateLimited: "Rate limited",
28
+ notFound: "Repo not found",
29
+ unprocessable: "Invalid query",
30
+ timeout: "Timed out",
31
+ network: (msg: string) => `Network error: ${msg}`,
32
+ server: "GitHub server error",
33
+ unknown: (msg: string) => msg,
34
+ },
35
+
36
+ // generic toast/tool failure fallback
37
+ failed: (msg: string) => `Failed: ${msg}`,
38
+ unknown: "unknown",
39
+
40
+ // dashboard view banners / empty states
41
+ noMatchingPRs: "No matching PRs",
42
+ }
43
+
44
+ function isRecord(value: unknown): value is Record<string, unknown> {
45
+ return typeof value === "object" && value !== null
46
+ }
47
+
48
+ // Classify errors from GitHub HTTP status, aborts/timeouts, network codes,
49
+ // and request messages when no status is available.
50
+ export function prListErrorKind(e: unknown): PRListErrorKind {
51
+ if (!e) return "unknown"
52
+ const details = isRecord(e) ? e : {}
53
+ const status = typeof details.status === "number" ? details.status : undefined
54
+ const name = typeof details.name === "string" ? details.name : undefined
55
+ const code = typeof details.code === "string" ? details.code : undefined
56
+ const message = e instanceof Error ? e.message : String(e)
57
+ const lower = message.toLowerCase()
58
+
59
+ if (/not authenticated|unauthor/i.test(lower)) return "authentication"
60
+ if (name === "AbortError") return "timeout"
61
+ if (
62
+ code &&
63
+ ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN"].includes(code)
64
+ ) {
65
+ return "network"
66
+ }
67
+
68
+ switch (status) {
69
+ case 401:
70
+ return "authentication"
71
+ case 403:
72
+ return /rate limit/i.test(lower) ? "rate-limit" : "forbidden"
73
+ case 404:
74
+ return "not-found"
75
+ case 408:
76
+ return "timeout"
77
+ case 422:
78
+ return "invalid-query"
79
+ }
80
+ if (status && status >= 500) return "server"
81
+
82
+ // GitHub request message fallback (no status, just text)
83
+ if (/rate limit/i.test(lower)) return "rate-limit"
84
+ if (/not found|\b404\b/.test(lower)) return "not-found"
85
+ if (/unauthor|\b401\b/.test(lower)) return "authentication"
86
+ if (/forbidden|\b403\b/.test(lower)) return "forbidden"
87
+ if (/network|econn|enotfound|etimedout|eai_again/.test(lower)) {
88
+ return "network"
89
+ }
90
+ if (/timeout|timed out/.test(lower)) return "timeout"
91
+
92
+ return "unknown"
93
+ }
94
+
95
+ // Map a thrown error to the existing user-facing detail string.
96
+ export function prListErrorMessage(e: unknown): string {
97
+ if (!e) return errorMessages.prListing.unknown("unknown")
98
+ const details = isRecord(e) ? e : {}
99
+ const message = e instanceof Error ? e.message : String(e)
100
+ const status = typeof details.status === "number" ? details.status : undefined
101
+ const code = typeof details.code === "string" ? details.code : undefined
102
+
103
+ switch (prListErrorKind(e)) {
104
+ case "authentication":
105
+ return status === 401 || /unauthor/i.test(message)
106
+ ? errorMessages.prListing.unauthorized
107
+ : errorMessages.noAuthToken
108
+ case "forbidden":
109
+ return errorMessages.prListing.forbidden
110
+ case "rate-limit":
111
+ return errorMessages.prListing.rateLimited
112
+ case "not-found":
113
+ return errorMessages.prListing.notFound
114
+ case "invalid-query":
115
+ return errorMessages.prListing.unprocessable
116
+ case "timeout":
117
+ return errorMessages.prListing.timeout
118
+ case "network":
119
+ return errorMessages.prListing.network(code ?? message)
120
+ case "server":
121
+ return errorMessages.prListing.server
122
+ case "unknown":
123
+ return errorMessages.prListing.unknown(message)
124
+ }
125
+ }
126
+
127
+ export type RateLimitInfo =
128
+ | { isRateLimit: true; message: string; resetAt: number }
129
+ | { isRateLimit: false; message: null; resetAt: null }
130
+
131
+ // Detects GitHub primary/secondary rate-limit errors and extracts the
132
+ // reset time from the x-ratelimit-reset header. Used by useDashboard to
133
+ // preserve the existing PR list when the error is a rate limit (the PRs
134
+ // are still valid; only the fetch failed).
135
+ export function parseRateLimitError(e: unknown): RateLimitInfo {
136
+ const details = isRecord(e) ? e : {}
137
+ const msg = typeof details.message === "string" ? details.message : ""
138
+ const status = typeof details.status === "number" ? details.status : undefined
139
+ const isRateLimit =
140
+ status === 429 ||
141
+ (status === 403 && /rate limit/i.test(msg)) ||
142
+ /rate limit (already exceeded|exceeded)/i.test(msg) ||
143
+ /api rate limit/i.test(msg)
144
+ if (!isRateLimit) return { isRateLimit: false, message: null, resetAt: null }
145
+
146
+ const response = isRecord(details.response) ? details.response : {}
147
+ const headers = isRecord(response.headers)
148
+ ? response.headers
149
+ : isRecord(details.headers)
150
+ ? details.headers
151
+ : {}
152
+ const rawReset = headers["x-ratelimit-reset"] ?? headers["X-RateLimit-Reset"]
153
+ const resetAt = rawReset ? parseInt(String(rawReset), 10) * 1000 : null
154
+ const resetText = resetAt ? new Date(resetAt).toLocaleTimeString() : "unknown time"
155
+
156
+ let detail = `GitHub API rate limit exceeded — resets at ${resetText}.`
157
+ if (/secondary rate limit/i.test(msg) || status === 429) {
158
+ detail = `GitHub secondary rate limit hit (too many requests) — try again at ${resetText}.`
159
+ }
160
+ return { isRateLimit: true, message: detail, resetAt: resetAt ?? 0 }
161
+ }
@@ -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,127 @@
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
+ // Row color: draft → grey, merge conflict → red, ready to merge → green,
10
+ // otherwise → "default" (white/text).
11
+ export function classifyRowState(pr: PR): "draft" | "blocked" | "ready" | "default" {
12
+ if (pr.isDraft) return "draft"
13
+ if (pr.mergeable === "CONFLICTING") return "blocked"
14
+ const ci = classifyCI(pr)
15
+ const r = reviewSummary(pr)
16
+ if (ci === "pass" && r.changes === 0) return "ready"
17
+ return "default"
18
+ }
19
+
20
+ export function classifyCI(pr: PR): "pass" | "fail" | "pending" | "none" {
21
+ const state = pr.statusCheckRollup?.state
22
+ if (state === "SUCCESS") return "pass"
23
+ if (state === "FAILURE" || state === "ERROR") return "fail"
24
+ if (state === "PENDING" || state === "EXPECTED") return "pending"
25
+ return "none"
26
+ }
27
+
28
+ function classifyCheckStatus(state: string): Exclude<StatusCategory, "none"> {
29
+ switch (state.toUpperCase()) {
30
+ case "SUCCESS":
31
+ return "pass"
32
+ case "FAILURE":
33
+ case "ERROR":
34
+ case "ACTION_REQUIRED":
35
+ case "CANCELLED":
36
+ case "STARTUP_FAILURE":
37
+ case "TIMED_OUT":
38
+ return "fail"
39
+ case "EXPECTED":
40
+ case "IN_PROGRESS":
41
+ case "PENDING":
42
+ case "QUEUED":
43
+ case "REQUESTED":
44
+ case "WAITING":
45
+ return "pending"
46
+ default:
47
+ return "neutral"
48
+ }
49
+ }
50
+
51
+ const statusOrder: StatusCategory[] = ["pass", "fail", "pending", "neutral", "none"]
52
+
53
+ function orderedGroups(counts: Map<StatusCategory, number>): StatusGroup[] {
54
+ return statusOrder
55
+ .filter((status) => (counts.get(status) ?? 0) > 0)
56
+ .map((status) => ({ status, count: counts.get(status)! }))
57
+ }
58
+
59
+ export function checkStatusGroups(pr: PR): StatusGroup[] {
60
+ const contexts = (pr.checkStatuses ?? []).filter(Boolean)
61
+ if (contexts.length === 0) {
62
+ const status = classifyCI(pr)
63
+ return [{ status, count: status === "none" ? 0 : 1 }]
64
+ }
65
+
66
+ const counts = new Map<StatusCategory, number>()
67
+ for (const context of contexts) {
68
+ const status = classifyCheckStatus(context)
69
+ counts.set(status, (counts.get(status) ?? 0) + 1)
70
+ }
71
+ return orderedGroups(counts)
72
+ }
73
+
74
+ export function reviewStatusGroups(pr: PR): StatusGroup[] {
75
+ const summary = reviewSummary(pr)
76
+ return orderedGroups(new Map<StatusCategory, number>([
77
+ ["pass", summary.approved],
78
+ ["fail", summary.changes],
79
+ ["pending", summary.pending],
80
+ ["neutral", summary.commented],
81
+ ]))
82
+ }
83
+
84
+ export function commentThreadCounts(pr: PR): { open: number; resolved: number } | null {
85
+ if (pr.reviewThreads === null) return null
86
+ return pr.reviewThreads.reduce(
87
+ (counts, thread) => {
88
+ if (thread.isResolved) counts.resolved++
89
+ else counts.open++
90
+ return counts
91
+ },
92
+ { open: 0, resolved: 0 },
93
+ )
94
+ }
95
+
96
+ export function reviewSummary(pr: PR): {
97
+ approved: number
98
+ changes: number
99
+ pending: number
100
+ commented: number
101
+ approvedLogins: string[]
102
+ changesLogins: string[]
103
+ pendingLogins: string[]
104
+ commentedLogins: string[]
105
+ } {
106
+ const approved = new Set<string>()
107
+ const changes = new Set<string>()
108
+ const commented = new Set<string>()
109
+ for (const r of pr.latestReviews ?? []) {
110
+ const login = r.author?.login
111
+ if (!login) continue
112
+ if (r.state === "APPROVED") approved.add(login)
113
+ else if (r.state === "CHANGES_REQUESTED") changes.add(login)
114
+ else if (r.state === "COMMENTED") commented.add(login)
115
+ }
116
+ const pendingLogins = (pr.reviewRequests ?? []).map((r) => r.login).filter(Boolean)
117
+ return {
118
+ approved: approved.size,
119
+ changes: changes.size,
120
+ pending: pendingLogins.length,
121
+ commented: commented.size,
122
+ approvedLogins: Array.from(approved),
123
+ changesLogins: Array.from(changes),
124
+ pendingLogins,
125
+ commentedLogins: Array.from(commented),
126
+ }
127
+ }
@@ -0,0 +1,77 @@
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
+ authorLogin: string
16
+ assigneeLogins: string[]
17
+ additions: number
18
+ deletions: number
19
+ baseRefName: string
20
+ mergeable: string
21
+ statusCheckRollup: { state: string } | null
22
+ checkStatuses: string[] | null
23
+ reviewThreads: Array<{ isResolved: boolean }> | null
24
+ reviewRequests: Array<{ login: string }> | null
25
+ latestReviews: Array<{ author: { login: string }; state: string }> | null
26
+ }
27
+
28
+ export type PRLinkTarget = "overview" | "mergeStatus" | "checks" | "files"
29
+
30
+ export type Repo = { owner: string; repo: string }
31
+
32
+ export type PRScope = "branch" | "author" | "assignee" | "all"
33
+ export type PRStatusFilter = "open" | "closed" | "all"
34
+
35
+ export enum DashboardStatus {
36
+ Loading = "loading",
37
+ Ok = "ok",
38
+ NoRepo = "no-repo",
39
+ Error = "error",
40
+ }
41
+
42
+ export type PRListErrorKind =
43
+ | "authentication"
44
+ | "forbidden"
45
+ | "rate-limit"
46
+ | "not-found"
47
+ | "invalid-query"
48
+ | "timeout"
49
+ | "network"
50
+ | "server"
51
+ | "unknown"
52
+
53
+ export type DashboardState = {
54
+ status: DashboardStatus
55
+ repo: Repo | null
56
+ prs: PR[]
57
+ currentBranch: string | null
58
+ viewerLogin: string | null
59
+ fetchedAt: number | null
60
+ // Closed and merged PRs load only once a status filter needs them.
61
+ closedLoaded: boolean
62
+ // Whether more PRs exist than the page limit loaded, per listing.
63
+ truncated: { open: boolean; closed: boolean }
64
+ error?: string
65
+ errorKind?: PRListErrorKind
66
+ }
67
+
68
+ // The public surface of useDashboard() — the signal/accessor pairs and
69
+ // actions exposed to the view layer and actions module. Defined here so
70
+ // the actions module can import it without depending on usePRData.
71
+ export interface DashboardContext {
72
+ state: () => DashboardState
73
+ refresh: () => Promise<void>
74
+ refreshOne: (n: number) => Promise<void>
75
+ selectedIdx: () => number
76
+ setSelectedIdx: (n: number) => void
77
+ }