mirror of
https://github.com/stablyai/orca.git
synced 2026-10-20 00:03:45 +00:00
* fix(github): load PR diffs for Enterprise remotes * fix(github): encode PR content paths by segment * Fix PR review actions failing on GitHub Enterprise remotes - Threads GitHub host identity (not just owner/repo) through the client, work-item-details, issues, and RPC layers so gh commands target the correct Enterprise server instead of silently falling back to github.com - Adds a shared github-api-repository helper to resolve/host-qualify repo identity consistently across REST, GraphQL, and CLI shorthand calls - Scopes the gh rate-limit breaker and singleton rate-limit snapshot by host/runtime so a github.com block or probe can't affect GHES or WSL - Coalesces concurrent host-auth probes and paginates PR file fetching beyond 100 results - Propagates `host` through renderer PR caches, checks-panel keys, and preload IPC types so Enterprise and github.com data never collide * Route gh host qualification through runner options instead of argv sniff Move GHES/GH_HOST resolution from parsing --hostname/--repo out of gh argv to an explicit options.host passed through ghExecFileAsync, since SSH-backed repos spawn gh with no cwd and argv sniffing couldn't reliably detect the target host. The runner now injects --hostname and qualifies --repo/-R at spawn time from options.host, and rate-limit scoping/guards use the same explicit host instead of inferring it. Also adds a shared githubRepoIdentityKey helper to keep cache/store keys consistent with the new host-aware repository identity. * Fix gh CLI GHES host pinning and rate-limit scope leaks - Pin `--host` on every gh call site so a process-level GH_HOST can't silently redirect requests, and qualify `-R`/`-R=` repo shorthand alongside the existing `--repo=` handling. - Check the target scope for an active rate-limit block before each WSL/native or host fallback retry, not just on the initial attempt, so a blocked scope can't be hit again through a fallback path. - Compute idempotency once per call instead of re-deriving it after fallback reassigns args. * Fix GitHub Enterprise host identity loss across PR/work-item paths - Thread `host` through mobile PR RPC params, IPC work-item lookups, and RPC schemas so GHES identity survives the renderer/mobile/main boundary instead of silently falling back to a same-named github.com repo. - Qualify `--repo`/`-R` args for github.com too (not just GHES), since gh resolves bare shorthand against a process-level GH_HOST that can redirect pinned github.com commands. - Cache `getOriginGitHubApiRepository` to avoid a per-call uncached `git remote get-url` round trip on connection-backed repos. - Add a local-fork fallback in `getWorkItemDetails` so PRs living on a base repo (not visible via the origin slug) still resolve via cwd. - Centralize the github.com-vs-GHES host predicate in `isDefaultGitHubHost` so cache keys, quota scoping, and identity checks can't drift out of sync. * Make repository identity host-aware across all GitHub surfaces Generalize the auth-gated enterprise resolver to any remote and build a cached hosted-identity family (origin/issue/candidates/source) on top of it, then migrate every github.com-only consumer: Tasks listing/counting, branch-to-PR discovery, push targets, fork upstream, issue operations, Projects, web links, avatars, and PR-link facts. Scope the rate-limit breaker probe per runtime:host and classify WSL UNC cwds correctly. Co-authored-by: Orca <help@stably.ai> * Fix expected slug to include host field in GitHub PR link test Updates the smart-source paste-intent test fixture to match the repository slug shape that now carries a `host` field, keeping GHES host identity intact through the paste-intent parsing path. * Surface per-host gh auth state for GitHub Enterprise diagnoseGhAuth accepts the host a surface needs credentials for, scopes the account/scope diagnosis to that host, and reports whether gh has any login there; GhAuthErrorHelp renders host-qualified login/refresh commands so an unauthenticated GHES host stops masquerading as a github.com scope problem. Also fixes the mobile paste-intent expectation for host-carrying parsed links. Co-authored-by: Orca <help@stably.ai> * Bound GHES identity caches and preserve non-default ports in host identity Cap the origin-repo and host-auth caches like ownerRepoCache; keep ports from remote/link URLs so GHES on a non-default port is a distinct identity; make positional github.com slugs explicit against GH_HOST; compare work-item sources by host-aware identity key; bail cwd-less branch lookups when no repository candidate resolved; thread host through the renderer work-item slug lookup. Co-authored-by: Orca <help@stably.ai> * Thread GitHub host through issue detail requests Incorporates ghes-issue-host-support (ed6bb96ef): one hosted issue repository identity is resolved before the details fan-out so comments, timeline, participants, and mention lookups cannot drift across hosts, with SSH guards so unresolved issue/PR repositories never fall through to gh's default host. Co-authored-by: Orca <help@stably.ai> * Scope remaining GitHub rate-limit accounting * Resolve typed PR lookups across hosted repository candidates getWorkItem's PR path probes upstream-then-origin hosted candidates instead of origin alone, so fork checkouts resolve the base repo's PR with the right host; issue detail resolution reuses the up-front hosted identity and keeps the SSH unresolved-host guards. Co-authored-by: Orca <help@stably.ai> * Refactor GitHub repository execution setup * Carry host on smart-submit link intents Co-authored-by: Orca <help@stably.ai> * Carry the project host on GitHub item dialog origins Co-authored-by: Orca <help@stably.ai> * Keep GHES web ports but drop SSH transport ports in host identity Supersedes PR #9118 on this branch: http(s) remote ports identify the Enterprise web/API endpoint and are preserved, while ssh/git transport ports (including ssh.github.com:443) never leak into gh's host identity. Replaces the ssh.github.com:443 special case with the structural protocol split and ports the PR's parsing test suite. Co-authored-by: Orca <help@stably.ai> * Support GitHub Enterprise diffs and mutations with host-scoped caches Parse GitHub host identity from work-item URLs and carry it through PR/issue mutations, labels, and assignments. Bound rate-limit and scope-probe caches (1024 and 512 entries) to prevent unbounded growth when interacting with multiple GHES instances. Normalize repository identity keys to include host so github.com and GHES slugs don't collide in cache and equality checks. * Support GitHub Enterprise diffs and mutations with host-scoped caches - Carry host identity through PR mutations and reads so fork PRs on different GHES instances don't collide in cache or state tracking. - Validate host authentication before routing requests to unconfigured Enterprise servers; ambient credentials must never reach untrusted hosts. - Scope rate-limit guards and spend tracking per host so GHES quota stays independent from github.com quota. - Respect explicit --hostname arguments in gh CLI calls ahead of GH_HOST or ambient defaults, so breaker state follows the actual request target. - Detect implicit WSL runtimes from UNC paths for consistent host auth and execution-options scoping across mobile and desktop clients. * Support GitHub Enterprise work-item diffs with host-scoped execution Enterprise PRs must use their selected host consistently across diff, comments, and file-content loads. Validate repository slugs before authenticated execution to prevent path-injection via renderer overrides. Scope project browsing cache and rate-limit tracking by host to prevent cross-host pollution. Use parsed URLs as authoritative over ambient hosts for project resolution. * Support GitHub Enterprise work-item diffs with host-scoped execution Preserve host identity on PR/issue work items throughout the mutation and diff pipeline so Enterprise instances (including ported endpoints like github.acme.test:8443) can execute mutations without ambiguity. Rate-limit gh commands by the pre-qualified --repo host, cache auth state per ported host, and surface Enterprise hosts in project metadata and error messages. * fix(review): drop dead rateLimitGuard/noteRateLimitSpend re-export Both callers (project-view.ts, mutations.ts) moved to the host-scoped repositoryRateLimitGuard/noteRepositoryRateLimitSpend; the bucket-only re-export in internals.ts had zero importers left. Co-authored-by: Orca <help@stably.ai> * fix(ci): split Enterprise host work-item tests under max-lines Move GHES/SSH host-routing cases out of work-item-details.test.ts so the suite stays within the 800-line test max-lines budget. * test(github): align mocks with host-scoped repository resolution - Route origin repository resolution through getOwnerRepoForRemote, not getOwnerRepo, to match production path - Pin github.com host on origin results so host-less fixtures pass host gate in resolveGitHubApiRepository - Add generation-based invalidation to prevent stale slug-cache writes from in-flight resolutions - Fix ref-sync race in ProjectPicker: use useLayoutEffect so committed tree owns browse cache key - Defer handledCrossRepoUrlRef assignment in SmartWorkspaceNameField until resolution succeeds - Update Enterprise host routing: found work items must not silently fall back to default host when unresolved - Normalize GHES avatar URLs: accept explicit port 443 as canonical form, not a fallback trigger --------- Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Co-authored-by: Orca <help@stably.ai>
615 lines
19 KiB
TypeScript
615 lines
19 KiB
TypeScript
/* eslint-disable max-lines -- Why: co-locating issue list/create/update/
|
|
comment operations keeps the shared acquire/release + error-classification
|
|
pattern obvious. Each function is short; the file is long because the
|
|
surface is broad. */
|
|
import type {
|
|
ClassifiedError,
|
|
GitHubAssignableUser,
|
|
GitHubCreateIssueFields,
|
|
GitHubCreateIssueResult,
|
|
GitHubCommentResult,
|
|
GitHubIssueUpdate,
|
|
IssueInfo,
|
|
IssueSourcePreference,
|
|
PRComment
|
|
} from '../../shared/types'
|
|
import { mapIssueInfo } from './mappers'
|
|
import type { LocalGitExecOptions, OwnerRepo } from './gh-utils'
|
|
import {
|
|
getIssueGitHubApiRepository,
|
|
resolveGitHubRepoExecution,
|
|
resolveIssueGitHubApiRepositorySource
|
|
} from './github-api-repository'
|
|
// prettier-ignore
|
|
import { ghExecFileAsync, acquire, release, classifyGhError, classifyListIssuesError, extractExecError } from './gh-utils'
|
|
|
|
// Why: distinguishes a successful-empty listing from a failed fetch. The
|
|
// previous `catch { return [] }` conflated a 403 on a private upstream with an
|
|
// empty backlog. Callers decide how to surface `error`.
|
|
//
|
|
// Why no `fellBack` here: the fell-back signal for the renderer toast rides on
|
|
// `ListWorkItemsResult.issueSourceFellBack` (the Tasks list's envelope). The
|
|
// only consumer of `listIssues` — the `gh:listIssues` IPC handler — unwraps
|
|
// to `.items` and has no UI hook to surface a fallback toast. Adding a dead
|
|
// `fellBack` field here invited drift between the JSDoc promise and reality.
|
|
export type IssueListResult = {
|
|
items: IssueInfo[]
|
|
error?: ClassifiedError
|
|
}
|
|
|
|
function githubIssueErrorMessage(error: unknown): string {
|
|
const { stderr, stdout } = extractExecError(error)
|
|
return stderr.trim() || stdout.trim()
|
|
}
|
|
|
|
/**
|
|
* Get a single issue by number.
|
|
* Uses gh api --cache so 304 Not Modified responses don't count against the rate limit.
|
|
*
|
|
* Why this path doesn't take a preference: linked-issue lookups persist a
|
|
* number to a worktree at creation time. Routing detail lookups through the
|
|
* live per-repo preference would silently flip an existing link to a
|
|
* different repo after the user toggled the selector — the opposite of what
|
|
* #1186 / the parent design doc guard against. List and create paths honor
|
|
* preference; number-resolution stays on the heuristic.
|
|
*/
|
|
export async function getIssue(
|
|
repoPath: string,
|
|
issueNumber: number,
|
|
connectionId?: string | null,
|
|
localGitOptions: LocalGitExecOptions = {}
|
|
): Promise<IssueInfo | null> {
|
|
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
|
repoPath,
|
|
() => getIssueGitHubApiRepository(repoPath, connectionId, localGitOptions),
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
// Why: a connection-backed request has no local cwd, so the non-GitHub
|
|
// fallback below would let gh target its default repository. Refuse instead.
|
|
if (connectionId && !ownerRepo) {
|
|
return null
|
|
}
|
|
await acquire()
|
|
try {
|
|
if (ownerRepo) {
|
|
const { stdout } = await ghExecFileAsync(
|
|
[
|
|
'api',
|
|
'--cache',
|
|
'300s',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}`
|
|
],
|
|
ghOptions
|
|
)
|
|
const data = JSON.parse(stdout)
|
|
return mapIssueInfo(data)
|
|
}
|
|
// Fallback for non-GitHub remotes
|
|
const { stdout } = await ghExecFileAsync(
|
|
['issue', 'view', String(issueNumber), '--json', 'number,title,state,url,labels'],
|
|
ghOptions
|
|
)
|
|
const data = JSON.parse(stdout)
|
|
return mapIssueInfo(data)
|
|
} catch {
|
|
return null
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* List issues for a repo.
|
|
* Uses gh api --cache so 304 Not Modified responses don't count against the rate limit.
|
|
*
|
|
* Why: returns a structured result so a 403 (e.g. fork contributor without
|
|
* read access to a private upstream) surfaces as an error the UI can render
|
|
* instead of collapsing to "No issues". The empty-list-on-error behavior this
|
|
* replaces was explicitly flagged as a merge-blocker in the parent design doc
|
|
* (§3) — silently hiding failures re-creates the same silent-source-switch
|
|
* class of wrongness #1186 warned against, one level deeper.
|
|
*/
|
|
export async function listIssues(
|
|
repoPath: string,
|
|
limit = 20,
|
|
preference?: IssueSourcePreference,
|
|
connectionId?: string | null,
|
|
localGitOptions: LocalGitExecOptions = {}
|
|
): Promise<IssueListResult> {
|
|
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
|
repoPath,
|
|
async () =>
|
|
(
|
|
await resolveIssueGitHubApiRepositorySource(
|
|
repoPath,
|
|
preference,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
).source,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
// Why: a connection-backed request has no local cwd, so the non-GitHub
|
|
// fallback below would let gh list its default repository. Refuse instead.
|
|
if (connectionId && !ownerRepo) {
|
|
return {
|
|
items: [],
|
|
error: {
|
|
type: 'not_found',
|
|
message: 'Could not resolve GitHub owner/repo for this repository'
|
|
}
|
|
}
|
|
}
|
|
await acquire()
|
|
try {
|
|
if (ownerRepo) {
|
|
const { stdout } = await ghExecFileAsync(
|
|
[
|
|
'api',
|
|
'--cache',
|
|
'120s',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues?per_page=${limit}&state=open&sort=updated&direction=desc`
|
|
],
|
|
ghOptions
|
|
)
|
|
const data = JSON.parse(stdout) as Record<string, unknown>[]
|
|
// Why: the GitHub REST `/repos/{owner}/{repo}/issues` endpoint returns
|
|
// pull requests alongside issues (PRs carry a `pull_request` key).
|
|
// Strip them here so `listIssues` only returns true issues, matching the
|
|
// filter applied in `listRecentWorkItems` (src/main/github/client.ts).
|
|
return {
|
|
items: data
|
|
.filter((d) => !('pull_request' in d))
|
|
.map((d) => mapIssueInfo(d as Parameters<typeof mapIssueInfo>[0]))
|
|
}
|
|
}
|
|
// Fallback for non-GitHub remotes
|
|
const { stdout } = await ghExecFileAsync(
|
|
['issue', 'list', '--json', 'number,title,state,url,labels', '--limit', String(limit)],
|
|
ghOptions
|
|
)
|
|
const data = JSON.parse(stdout) as unknown[]
|
|
return {
|
|
items: data.map((d) => mapIssueInfo(d as Parameters<typeof mapIssueInfo>[0]))
|
|
}
|
|
} catch (err) {
|
|
const stderr = err instanceof Error ? err.message : String(err)
|
|
return {
|
|
items: [],
|
|
error: classifyListIssuesError(stderr)
|
|
}
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create a new GitHub issue. Uses `gh api` with explicit owner/repo so the
|
|
* call does not depend on the current working directory having a remote that
|
|
* matches the repo the user picked in the tasks page.
|
|
*/
|
|
export async function createIssue(
|
|
repoPath: string,
|
|
title: string,
|
|
body: string,
|
|
preference?: IssueSourcePreference,
|
|
connectionId?: string | null,
|
|
fields?: GitHubCreateIssueFields,
|
|
localGitOptions: LocalGitExecOptions = {}
|
|
): Promise<GitHubCreateIssueResult> {
|
|
const trimmedTitle = title.trim()
|
|
if (!trimmedTitle) {
|
|
return { ok: false, error: 'Title is required' }
|
|
}
|
|
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
|
repoPath,
|
|
async () =>
|
|
(
|
|
await resolveIssueGitHubApiRepositorySource(
|
|
repoPath,
|
|
preference,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
).source,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
if (!ownerRepo) {
|
|
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
|
|
}
|
|
await acquire()
|
|
try {
|
|
const createArgs = (issueBody: string) => {
|
|
const args = [
|
|
'api',
|
|
'-X',
|
|
'POST',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues`,
|
|
'--raw-field',
|
|
`title=${trimmedTitle}`,
|
|
'--raw-field',
|
|
`body=${issueBody}`
|
|
]
|
|
for (const label of fields?.labels ?? []) {
|
|
args.push('--raw-field', `labels[]=${label}`)
|
|
}
|
|
for (const assignee of fields?.assignees ?? []) {
|
|
args.push('--raw-field', `assignees[]=${assignee}`)
|
|
}
|
|
return args
|
|
}
|
|
|
|
const parseIssue = (stdout: string) =>
|
|
JSON.parse(stdout) as { number?: number; html_url?: string; url?: string }
|
|
|
|
let data: { number?: number; html_url?: string; url?: string }
|
|
try {
|
|
const { stdout } = await ghExecFileAsync(createArgs(body), ghOptions)
|
|
data = parseIssue(stdout)
|
|
} catch (err) {
|
|
const message = githubIssueErrorMessage(err)
|
|
if (!/body is too long \(maximum is \d+ characters\)/i.test(message)) {
|
|
return { ok: false, error: message }
|
|
}
|
|
|
|
// Why: GitHub rejects oversized bodies on create but accepts the same body
|
|
// on update, so establish the issue before attaching its body.
|
|
const { stdout } = await ghExecFileAsync(createArgs(''), ghOptions)
|
|
data = parseIssue(stdout)
|
|
if (typeof data.number !== 'number') {
|
|
return { ok: false, error: 'Unexpected response from GitHub' }
|
|
}
|
|
|
|
try {
|
|
await ghExecFileAsync(
|
|
[
|
|
'api',
|
|
'-X',
|
|
'PATCH',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${data.number}`,
|
|
'--raw-field',
|
|
`body=${body}`
|
|
],
|
|
ghOptions
|
|
)
|
|
} catch (patchErr) {
|
|
const patchMessage = githubIssueErrorMessage(patchErr)
|
|
const identity = data.html_url ?? data.url ?? `#${data.number}`
|
|
return {
|
|
ok: true,
|
|
number: data.number,
|
|
url: String(data.html_url ?? data.url ?? ''),
|
|
bodySaveWarning: `Issue ${identity} was created, but saving its body failed: ${patchMessage}`
|
|
}
|
|
}
|
|
}
|
|
|
|
if (typeof data.number !== 'number') {
|
|
return { ok: false, error: 'Unexpected response from GitHub' }
|
|
}
|
|
return {
|
|
ok: true,
|
|
number: data.number,
|
|
url: String(data.html_url ?? data.url ?? '')
|
|
}
|
|
} catch (err) {
|
|
return { ok: false, error: githubIssueErrorMessage(err) }
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update an existing GitHub issue. Fans out to separate gh commands for
|
|
* state changes vs field edits since `gh issue edit` does not support state.
|
|
*
|
|
* Why this path doesn't take a preference (mirrors `getIssue`): mutations
|
|
* target an issue number already bound to a worktree / linked elsewhere in
|
|
* the UI. Routing an update through the live per-repo preference would let
|
|
* a user open upstream#N, toggle the selector to origin, save, and silently
|
|
* write to origin#N — a different issue (or 404). That is the exact
|
|
* silent-source-switch class of wrongness #1186 / the parent design doc
|
|
* guard against. List and create paths honor preference; mutations stay on
|
|
* the heuristic `getIssueOwnerRepo`.
|
|
*/
|
|
export async function updateIssue(
|
|
repoPath: string,
|
|
issueNumber: number,
|
|
updates: GitHubIssueUpdate,
|
|
connectionId?: string | null,
|
|
localGitOptions: LocalGitExecOptions = {}
|
|
): Promise<{ ok: true } | { ok: false; error: string }> {
|
|
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
|
repoPath,
|
|
() => getIssueGitHubApiRepository(repoPath, connectionId, localGitOptions),
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
if (!ownerRepo) {
|
|
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
|
|
}
|
|
|
|
const repo = `${ownerRepo.owner}/${ownerRepo.repo}`
|
|
const errors: string[] = []
|
|
|
|
// State change requires a separate command
|
|
if (updates.state) {
|
|
await acquire()
|
|
try {
|
|
if (updates.state === 'closed') {
|
|
const closeArgs = ['issue', 'close', String(issueNumber), '--repo', repo]
|
|
if (updates.stateReason === 'completed') {
|
|
closeArgs.push('--reason', 'completed')
|
|
} else if (updates.stateReason === 'not_planned') {
|
|
closeArgs.push('--reason', 'not planned')
|
|
} else if (updates.stateReason === 'duplicate' && updates.duplicateOf) {
|
|
closeArgs.push('--duplicate-of', String(updates.duplicateOf))
|
|
}
|
|
await ghExecFileAsync(closeArgs, ghOptions)
|
|
} else {
|
|
await ghExecFileAsync(['issue', 'reopen', String(issueNumber), '--repo', repo], ghOptions)
|
|
}
|
|
} catch (err) {
|
|
const stderr = err instanceof Error ? err.message : String(err)
|
|
// Treat "already closed/open" as a no-op
|
|
if (!stderr.toLowerCase().includes('already')) {
|
|
errors.push(classifyGhError(stderr).message)
|
|
}
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
if (updates.body !== undefined) {
|
|
await acquire()
|
|
try {
|
|
await ghExecFileAsync(
|
|
[
|
|
'api',
|
|
'-X',
|
|
'PATCH',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}`,
|
|
'--raw-field',
|
|
`body=${updates.body}`
|
|
],
|
|
ghOptions
|
|
)
|
|
} catch (err) {
|
|
const stderr = err instanceof Error ? err.message : String(err)
|
|
errors.push(classifyGhError(stderr).message)
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
// Field edits (labels, assignees, title) via gh issue edit
|
|
const editArgs: string[] = ['issue', 'edit', String(issueNumber), '--repo', repo]
|
|
let hasEditArgs = false
|
|
|
|
if (updates.title) {
|
|
editArgs.push('--title', updates.title)
|
|
hasEditArgs = true
|
|
}
|
|
for (const label of updates.addLabels ?? []) {
|
|
editArgs.push('--add-label', label)
|
|
hasEditArgs = true
|
|
}
|
|
for (const label of updates.removeLabels ?? []) {
|
|
editArgs.push('--remove-label', label)
|
|
hasEditArgs = true
|
|
}
|
|
for (const assignee of updates.addAssignees ?? []) {
|
|
editArgs.push('--add-assignee', assignee)
|
|
hasEditArgs = true
|
|
}
|
|
for (const assignee of updates.removeAssignees ?? []) {
|
|
editArgs.push('--remove-assignee', assignee)
|
|
hasEditArgs = true
|
|
}
|
|
|
|
if (hasEditArgs) {
|
|
await acquire()
|
|
try {
|
|
await ghExecFileAsync(editArgs, ghOptions)
|
|
} catch (err) {
|
|
const stderr = err instanceof Error ? err.message : String(err)
|
|
errors.push(classifyGhError(stderr).message)
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
if (errors.length > 0) {
|
|
return { ok: false, error: errors.join('; ') }
|
|
}
|
|
return { ok: true }
|
|
}
|
|
|
|
/**
|
|
* Add a comment to an existing GitHub issue.
|
|
*
|
|
* Why this path doesn't take a preference (mirrors `getIssue` / `updateIssue`):
|
|
* a comment is posted against an issue number already bound to a worktree or
|
|
* surfaced from a prior read. Routing through the live per-repo preference
|
|
* would let a user read upstream#N, toggle the selector to origin, and have
|
|
* their reply silently post on origin#N — a different issue entirely. That
|
|
* is the same silent-source-switch class of wrongness #1186 / the parent
|
|
* design doc guard against. List and create paths honor preference;
|
|
* mutations stay on the heuristic `getIssueOwnerRepo`.
|
|
*/
|
|
export async function addIssueComment(
|
|
repoPath: string,
|
|
issueNumber: number,
|
|
body: string,
|
|
connectionId?: string | null,
|
|
ownerRepoOverride?: OwnerRepo | null,
|
|
localGitOptions: LocalGitExecOptions = {}
|
|
): Promise<GitHubCommentResult> {
|
|
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
|
repoPath,
|
|
ownerRepoOverride ??
|
|
(() => getIssueGitHubApiRepository(repoPath, connectionId, localGitOptions)),
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
if (!ownerRepo) {
|
|
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
|
|
}
|
|
await acquire()
|
|
try {
|
|
const { stdout } = await ghExecFileAsync(
|
|
[
|
|
'api',
|
|
'-X',
|
|
'POST',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}/comments`,
|
|
'--raw-field',
|
|
`body=${body}`
|
|
],
|
|
ghOptions
|
|
)
|
|
const data = JSON.parse(stdout) as {
|
|
id?: number
|
|
user: { login: string; avatar_url: string; type?: string } | null
|
|
body?: string
|
|
created_at?: string
|
|
html_url?: string
|
|
}
|
|
if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) {
|
|
return { ok: false, error: 'Unexpected response from GitHub' }
|
|
}
|
|
const comment: PRComment = {
|
|
id: data.id,
|
|
author: data.user?.login ?? 'You',
|
|
authorAvatarUrl: data.user?.avatar_url ?? '',
|
|
body: data.body ?? body,
|
|
createdAt: data.created_at ?? new Date().toISOString(),
|
|
url: data.html_url ?? '',
|
|
isBot: data.user?.type === 'Bot'
|
|
}
|
|
return { ok: true, comment }
|
|
} catch (err) {
|
|
const stderr = err instanceof Error ? err.message : String(err)
|
|
return { ok: false, error: classifyGhError(stderr).message }
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
export async function listLabels(
|
|
repoPath: string,
|
|
preference?: IssueSourcePreference,
|
|
connectionId?: string | null,
|
|
localGitOptions: LocalGitExecOptions = {}
|
|
): Promise<string[]> {
|
|
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
|
repoPath,
|
|
async () =>
|
|
(
|
|
await resolveIssueGitHubApiRepositorySource(
|
|
repoPath,
|
|
preference,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
).source,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
if (!ownerRepo) {
|
|
return []
|
|
}
|
|
await acquire()
|
|
try {
|
|
const { stdout } = await ghExecFileAsync(
|
|
[
|
|
'api',
|
|
'--paginate',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/labels`,
|
|
'--jq',
|
|
'.[].name'
|
|
],
|
|
ghOptions
|
|
)
|
|
return stdout
|
|
.trim()
|
|
.split('\n')
|
|
.filter((l) => l.length > 0)
|
|
} catch {
|
|
return []
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|
|
|
|
export async function listAssignableUsers(
|
|
repoPath: string,
|
|
preference?: IssueSourcePreference,
|
|
connectionId?: string | null,
|
|
localGitOptions: LocalGitExecOptions = {}
|
|
): Promise<GitHubAssignableUser[]> {
|
|
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
|
repoPath,
|
|
async () =>
|
|
(
|
|
await resolveIssueGitHubApiRepositorySource(
|
|
repoPath,
|
|
preference,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
).source,
|
|
connectionId,
|
|
localGitOptions
|
|
)
|
|
if (!ownerRepo) {
|
|
return []
|
|
}
|
|
await acquire()
|
|
try {
|
|
// Why: paginate through all assignable users — GraphQL's assignableUsers
|
|
// maxes out at 100 per page and large orgs/repos silently lose assignees
|
|
// beyond the first page. REST /assignees with --paginate walks every page;
|
|
// --jq collapses per-page arrays into NDJSON so we don't have to stitch
|
|
// JSON arrays that gh concatenates back-to-back.
|
|
const { stdout } = await ghExecFileAsync(
|
|
[
|
|
'api',
|
|
'--paginate',
|
|
`repos/${ownerRepo.owner}/${ownerRepo.repo}/assignees?per_page=100`,
|
|
'--jq',
|
|
'.[] | {login, avatar_url}'
|
|
],
|
|
ghOptions
|
|
)
|
|
type RESTAssignee = { login?: string; avatar_url?: string | null }
|
|
const users: GitHubAssignableUser[] = []
|
|
for (const line of stdout.split('\n')) {
|
|
const trimmed = line.trim()
|
|
if (!trimmed) {
|
|
continue
|
|
}
|
|
try {
|
|
const user = JSON.parse(trimmed) as RESTAssignee
|
|
if (user.login) {
|
|
users.push({
|
|
login: user.login,
|
|
name: null,
|
|
avatarUrl: user.avatar_url ?? ''
|
|
})
|
|
}
|
|
} catch {
|
|
// Skip malformed NDJSON lines defensively.
|
|
}
|
|
}
|
|
return users
|
|
} catch {
|
|
return []
|
|
} finally {
|
|
release()
|
|
}
|
|
}
|