mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 03:15:01 +00:00
refactor(github): organize concrete feature owners (#41601)
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import { githubBodyImageUrls, githubBodyMediaHeaders } from '../attachments/body-image-urls'
|
||||
import type { GitHubCommentResult, PRComment } from '../../../shared/github/comments/comment-types'
|
||||
import type { IssueSourcePreference } from '../../../shared/repo-types'
|
||||
import type { LocalGitExecOptions } from '../repositories/github-repository-identity'
|
||||
import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../shared/github/repositories/repository-identity'
|
||||
import {
|
||||
resolveGitHubRepoExecution,
|
||||
resolveIssueGitHubApiRepositorySource
|
||||
} from '../repositories/github-api-repository'
|
||||
import { acquire, release } from '../execution/github-operation-slots'
|
||||
import { classifyGhError } from '../api/gh-error-classification'
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import { codeHostFailure, classifiedFailure } from '../../../shared/code-host-failure-copy'
|
||||
|
||||
// An explicit target keeps replies bound to the conversation; otherwise use the selected source.
|
||||
export async function addIssueComment(
|
||||
repoPath: string,
|
||||
issueNumber: number,
|
||||
body: string,
|
||||
connectionId?: string | null,
|
||||
ownerRepoOverride?: OwnerRepo | null,
|
||||
localGitOptions: LocalGitExecOptions = {},
|
||||
preference?: IssueSourcePreference
|
||||
): Promise<GitHubCommentResult> {
|
||||
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
||||
repoPath,
|
||||
ownerRepoOverride ??
|
||||
(async () =>
|
||||
(
|
||||
await resolveIssueGitHubApiRepositorySource(
|
||||
repoPath,
|
||||
preference,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
).source),
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
if (!ownerRepo) {
|
||||
return codeHostFailure('github.repoUnresolved')
|
||||
}
|
||||
await acquire()
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
...githubBodyMediaHeaders(body),
|
||||
'-X',
|
||||
'POST',
|
||||
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}/comments`,
|
||||
'--input',
|
||||
'-'
|
||||
],
|
||||
{ ...ghOptions, stdin: JSON.stringify({ body }) }
|
||||
)
|
||||
const data: {
|
||||
id?: number
|
||||
node_id?: string | null
|
||||
user: { login: string; avatar_url: string; type?: string } | null
|
||||
body?: string
|
||||
body_html?: string | null
|
||||
created_at?: string
|
||||
html_url?: string
|
||||
} = JSON.parse(stdout)
|
||||
if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) {
|
||||
return codeHostFailure('github.unexpectedResponse')
|
||||
}
|
||||
const comment: PRComment = {
|
||||
id: data.id,
|
||||
reactionSubjectId: data.node_id?.trim() || undefined,
|
||||
author: data.user?.login ?? 'You',
|
||||
authorAvatarUrl: data.user?.avatar_url ?? '',
|
||||
body: data.body ?? body,
|
||||
bodyImageUrls: githubBodyImageUrls(data.body ?? body, data.body_html),
|
||||
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 classifiedFailure(classifyGhError(stderr))
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type {
|
||||
GitHubCreateIssueFields,
|
||||
GitHubCreateIssueResult
|
||||
} from '../../../shared/issue-mutation-types'
|
||||
import type { IssueSourcePreference } from '../../../shared/repo-types'
|
||||
import type { LocalGitExecOptions } from '../repositories/github-repository-identity'
|
||||
import {
|
||||
resolveGitHubRepoExecution,
|
||||
resolveIssueGitHubApiRepositorySource
|
||||
} from '../repositories/github-api-repository'
|
||||
import { acquire, release } from '../execution/github-operation-slots'
|
||||
import { extractExecError } from '../../git/command-runner/process-capture/exec-error'
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import { codeHostFailure } from '../../../shared/code-host-failure-copy'
|
||||
|
||||
function githubIssueErrorMessage(error: unknown): string {
|
||||
const { stderr, stdout } = extractExecError(error)
|
||||
return [stderr.trim(), stdout.trim()].filter(Boolean).join('\n')
|
||||
}
|
||||
|
||||
/** Explicit owner/repo preserves the Tasks-selected source independently of cwd remotes. */
|
||||
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 codeHostFailure('titleRequired')
|
||||
}
|
||||
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
||||
repoPath,
|
||||
async () =>
|
||||
(
|
||||
await resolveIssueGitHubApiRepositorySource(
|
||||
repoPath,
|
||||
preference,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
).source,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
if (!ownerRepo) {
|
||||
return codeHostFailure('github.repoUnresolved')
|
||||
}
|
||||
await acquire()
|
||||
try {
|
||||
const issuesEndpoint = `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues`
|
||||
// Why: stdin keeps large inline-image bodies off argv, which Windows caps at 32K chars.
|
||||
const createIssueRequest = (issueBody: string) =>
|
||||
ghExecFileAsync(['api', '-X', 'POST', issuesEndpoint, '--input', '-'], {
|
||||
...ghOptions,
|
||||
stdin: JSON.stringify({
|
||||
title: trimmedTitle,
|
||||
body: issueBody,
|
||||
...(fields?.labels?.length ? { labels: fields.labels } : {}),
|
||||
...(fields?.assignees?.length ? { assignees: fields.assignees } : {})
|
||||
})
|
||||
})
|
||||
|
||||
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 createIssueRequest(body)
|
||||
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 }
|
||||
}
|
||||
|
||||
// GitHub can accept a body on update that it rejects during creation; establish the issue first.
|
||||
const { stdout } = await createIssueRequest('')
|
||||
data = parseIssue(stdout)
|
||||
if (typeof data.number !== 'number') {
|
||||
return codeHostFailure('github.unexpectedResponse')
|
||||
}
|
||||
|
||||
try {
|
||||
await ghExecFileAsync(
|
||||
['api', '-X', 'PATCH', `${issuesEndpoint}/${data.number}`, '--input', '-'],
|
||||
{ ...ghOptions, stdin: JSON.stringify({ body }) }
|
||||
)
|
||||
} 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 codeHostFailure('github.unexpectedResponse')
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
number: data.number,
|
||||
url: String(data.html_url ?? data.url ?? '')
|
||||
}
|
||||
} catch (err) {
|
||||
return { ok: false, error: githubIssueErrorMessage(err) }
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { z } from 'zod'
|
||||
import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types'
|
||||
|
||||
export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $includeItem: Boolean!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
issue(number: $number) {
|
||||
number @include(if: $includeItem) title @include(if: $includeItem)
|
||||
state @include(if: $includeItem)
|
||||
url @include(if: $includeItem)
|
||||
updatedAt @include(if: $includeItem)
|
||||
author @include(if: $includeItem) { __typename login avatarUrl(size: 48) }
|
||||
labels(first: 100) @include(if: $includeItem) {
|
||||
nodes { name }
|
||||
pageInfo { hasNextPage }
|
||||
}
|
||||
body
|
||||
bodyHTML
|
||||
assignees(first: 50) {
|
||||
nodes { login avatarUrl(size: 48) ... on User { name } }
|
||||
pageInfo { hasNextPage }
|
||||
}
|
||||
participants(first: 100) {
|
||||
nodes { login avatarUrl(size: 48) ... on User { name } }
|
||||
}
|
||||
comments(first: 100) {
|
||||
pageInfo { hasNextPage }
|
||||
nodes {
|
||||
databaseId
|
||||
body
|
||||
bodyHTML
|
||||
createdAt
|
||||
url
|
||||
viewerDidAuthor
|
||||
author {
|
||||
login
|
||||
avatarUrl(size: 48)
|
||||
... on Bot { __typename }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
export const issueItemSchema = z.object({
|
||||
number: z.number().int().positive(),
|
||||
title: z.string(),
|
||||
state: z.enum(['OPEN', 'CLOSED']),
|
||||
url: z.string(),
|
||||
updatedAt: z.string(),
|
||||
author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string() }).nullable(),
|
||||
assignees: z.object({
|
||||
nodes: z.array(z.object({ login: z.string().min(1) })),
|
||||
pageInfo: z.object({ hasNextPage: z.literal(false) })
|
||||
}),
|
||||
labels: z.object({
|
||||
nodes: z.array(z.object({ name: z.string() })),
|
||||
pageInfo: z.object({ hasNextPage: z.literal(false) })
|
||||
})
|
||||
})
|
||||
|
||||
export type GraphQLIssueDetailsResponse = {
|
||||
data?: {
|
||||
repository?: {
|
||||
issue?: {
|
||||
body?: string | null
|
||||
bodyHTML?: unknown
|
||||
assignees?: { nodes?: (Partial<GitHubAssignableUser> | null)[] | null }
|
||||
participants?: { nodes?: GitHubAssignableUser[] }
|
||||
comments?: {
|
||||
pageInfo?: { hasNextPage: boolean }
|
||||
nodes?: ({
|
||||
databaseId?: number | null
|
||||
body?: string | null
|
||||
bodyHTML?: unknown
|
||||
createdAt?: string | null
|
||||
url?: string | null
|
||||
viewerDidAuthor?: boolean | null
|
||||
author?: {
|
||||
login?: string | null
|
||||
avatarUrl?: string | null
|
||||
__typename?: string
|
||||
} | null
|
||||
} | null)[]
|
||||
}
|
||||
} | null
|
||||
} | null
|
||||
}
|
||||
errors?: { message?: string; path?: unknown }[]
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { GhAccountBinding } from '../../../shared/github/accounts/account-binding'
|
||||
import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types'
|
||||
import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity'
|
||||
import type { IssueSourcePreference } from '../../../shared/repo-types'
|
||||
import type { LocalGitExecOptions } from '../repositories/github-repository-identity'
|
||||
import {
|
||||
resolveGitHubRepoExecution,
|
||||
resolveIssueGitHubApiRepositorySource
|
||||
} from '../repositories/github-api-repository'
|
||||
import { acquire, release } from '../execution/github-operation-slots'
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
|
||||
export async function listLabels(
|
||||
repoPath: string,
|
||||
preference?: IssueSourcePreference,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {},
|
||||
repositoryOverride?: GitHubOwnerRepo | null,
|
||||
expectedGhAccount?: GhAccountBinding | null
|
||||
): Promise<string[]> {
|
||||
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
||||
repoPath,
|
||||
repositoryOverride ??
|
||||
(async () =>
|
||||
(
|
||||
await resolveIssueGitHubApiRepositorySource(
|
||||
repoPath,
|
||||
preference,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
).source),
|
||||
connectionId,
|
||||
localGitOptions,
|
||||
expectedGhAccount
|
||||
)
|
||||
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 = {},
|
||||
repositoryOverride?: GitHubOwnerRepo | null,
|
||||
expectedGhAccount?: GhAccountBinding | null
|
||||
): Promise<GitHubAssignableUser[]> {
|
||||
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
||||
repoPath,
|
||||
repositoryOverride ??
|
||||
(async () =>
|
||||
(
|
||||
await resolveIssueGitHubApiRepositorySource(
|
||||
repoPath,
|
||||
preference,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
).source),
|
||||
connectionId,
|
||||
localGitOptions,
|
||||
expectedGhAccount
|
||||
)
|
||||
if (!ownerRepo) {
|
||||
return []
|
||||
}
|
||||
await acquire()
|
||||
try {
|
||||
// REST pagination covers all assignees; jq emits NDJSON instead of concatenated page arrays.
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import type {
|
||||
GitHubIssueTimelineItem,
|
||||
GitHubIssueTimelineTarget
|
||||
} from '../../../shared/github/comments/comment-types'
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity'
|
||||
import type { GitHubRepoExecOptions } from '../repositories/github-api-repository'
|
||||
import { githubHostExecOptions } from '../repositories/github-repository-host'
|
||||
import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit'
|
||||
|
||||
const MAX_ISSUE_TIMELINE_ITEMS = 300
|
||||
const GITHUB_REST_PAGE_SIZE = 100
|
||||
|
||||
type RestTimelineUser = {
|
||||
login?: string | null
|
||||
avatar_url?: string | null
|
||||
}
|
||||
|
||||
type RestTimelineIssue = {
|
||||
number?: number | null
|
||||
title?: string | null
|
||||
html_url?: string | null
|
||||
repository?: {
|
||||
name?: string | null
|
||||
owner?: { login?: string | null } | null
|
||||
} | null
|
||||
pull_request?: unknown
|
||||
}
|
||||
|
||||
type RestTimelineEvent = {
|
||||
id?: number | string | null
|
||||
node_id?: string | null
|
||||
event?: string | null
|
||||
actor?: RestTimelineUser | null
|
||||
user?: RestTimelineUser | null
|
||||
assignee?: RestTimelineUser | null
|
||||
created_at?: string | null
|
||||
source?: { issue?: RestTimelineIssue | null } | null
|
||||
closer?: RestTimelineIssue | null
|
||||
state_reason?: string | null
|
||||
project_card?: {
|
||||
column_name?: string | null
|
||||
previous_column_name?: string | null
|
||||
project_url?: string | null
|
||||
} | null
|
||||
project?: { name?: string | null } | null
|
||||
project_column_name?: string | null
|
||||
previous_column_name?: string | null
|
||||
}
|
||||
|
||||
function isSupportedTimelineEvent(
|
||||
eventName: string | null | undefined
|
||||
): eventName is GitHubIssueTimelineItem['event'] {
|
||||
return (
|
||||
eventName === 'assigned' ||
|
||||
eventName === 'unassigned' ||
|
||||
eventName === 'mentioned' ||
|
||||
eventName === 'cross-referenced' ||
|
||||
eventName === 'closed' ||
|
||||
eventName === 'reopened' ||
|
||||
eventName === 'moved_columns_in_project'
|
||||
)
|
||||
}
|
||||
|
||||
function mapTimelineTarget(
|
||||
issue: RestTimelineIssue | null | undefined
|
||||
): GitHubIssueTimelineTarget | undefined {
|
||||
if (!issue || typeof issue.number !== 'number' || !issue.html_url) {
|
||||
return undefined
|
||||
}
|
||||
const owner = issue.repository?.owner?.login
|
||||
const repo = issue.repository?.name
|
||||
return {
|
||||
type: issue.pull_request ? 'pr' : 'issue',
|
||||
number: issue.number,
|
||||
title: issue.title ?? '',
|
||||
url: issue.html_url,
|
||||
repository: owner && repo ? `${owner}/${repo}` : undefined
|
||||
}
|
||||
}
|
||||
|
||||
function getTimelineActor(event: RestTimelineEvent): { login: string; avatarUrl: string } {
|
||||
const actor = event.actor ?? event.user
|
||||
return {
|
||||
login: actor?.login ?? 'ghost',
|
||||
avatarUrl: actor?.avatar_url ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
function mapRestTimelineEvent(event: RestTimelineEvent): GitHubIssueTimelineItem | null {
|
||||
const eventName = event.event
|
||||
if (!isSupportedTimelineEvent(eventName) || !event.created_at) {
|
||||
return null
|
||||
}
|
||||
const actor = getTimelineActor(event)
|
||||
const id = String(event.node_id ?? event.id ?? `${eventName}:${event.created_at}`)
|
||||
const base = {
|
||||
id,
|
||||
event: eventName,
|
||||
actor: actor.login,
|
||||
actorAvatarUrl: actor.avatarUrl,
|
||||
createdAt: event.created_at
|
||||
}
|
||||
if (eventName === 'assigned' || eventName === 'unassigned') {
|
||||
return { ...base, assignee: event.assignee?.login ?? undefined }
|
||||
}
|
||||
if (eventName === 'mentioned' || eventName === 'cross-referenced') {
|
||||
return { ...base, source: mapTimelineTarget(event.source?.issue) }
|
||||
}
|
||||
if (eventName === 'closed') {
|
||||
return {
|
||||
...base,
|
||||
stateReason: event.state_reason ?? null,
|
||||
closer: mapTimelineTarget(event.closer ?? event.source?.issue)
|
||||
}
|
||||
}
|
||||
if (eventName === 'moved_columns_in_project') {
|
||||
return {
|
||||
...base,
|
||||
previousColumnName:
|
||||
event.previous_column_name ?? event.project_card?.previous_column_name ?? null,
|
||||
columnName: event.project_column_name ?? event.project_card?.column_name ?? null,
|
||||
projectName: event.project?.name ?? null
|
||||
}
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
function parseRestTimelineEventLines(stdout: string, strict = false): RestTimelineEvent[] {
|
||||
const events: RestTimelineEvent[] = []
|
||||
for (const line of stdout.split('\n')) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as unknown
|
||||
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
|
||||
events.push(parsed)
|
||||
}
|
||||
} catch {
|
||||
if (strict) {
|
||||
throw new Error('GitHub timeline unavailable')
|
||||
}
|
||||
// Timeline activity is auxiliary to ordinary issue details.
|
||||
}
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
export async function getIssueTimelineItems(
|
||||
repository: GitHubApiRepository,
|
||||
issueNumber: number,
|
||||
ghOptions: GitHubRepoExecOptions,
|
||||
fresh = false
|
||||
): Promise<GitHubIssueTimelineItem[]> {
|
||||
try {
|
||||
const items: GitHubIssueTimelineItem[] = []
|
||||
for (let page = 1; items.length < MAX_ISSUE_TIMELINE_ITEMS; page += 1) {
|
||||
if (repositoryRateLimitGuard(repository, 'core', ghOptions).blocked) {
|
||||
if (fresh) {
|
||||
throw new Error('GitHub timeline unavailable')
|
||||
}
|
||||
return items
|
||||
}
|
||||
noteRepositoryRateLimitSpend(repository, 'core', 1, ghOptions)
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
...(fresh ? [] : ['--cache', '60s']),
|
||||
`repos/${repository.owner}/${repository.repo}/issues/${issueNumber}/timeline?per_page=${GITHUB_REST_PAGE_SIZE}&page=${page}`,
|
||||
'--jq',
|
||||
'.[] | @json'
|
||||
],
|
||||
{ ...ghOptions, ...githubHostExecOptions(repository) }
|
||||
)
|
||||
const pageEvents = parseRestTimelineEventLines(stdout, fresh)
|
||||
for (const event of pageEvents) {
|
||||
const item = mapRestTimelineEvent(event)
|
||||
if (!item) {
|
||||
continue
|
||||
}
|
||||
items.push(item)
|
||||
if (items.length === MAX_ISSUE_TIMELINE_ITEMS) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if (pageEvents.length < GITHUB_REST_PAGE_SIZE) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return items
|
||||
} catch (error) {
|
||||
if (fresh) {
|
||||
throw error
|
||||
}
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { GitHubIssueUpdate } from '../../../shared/issue-mutation-types'
|
||||
import type { IssueSourcePreference } from '../../../shared/repo-types'
|
||||
import type { LocalGitExecOptions } from '../repositories/github-repository-identity'
|
||||
import {
|
||||
resolveGitHubRepoExecution,
|
||||
resolveIssueGitHubApiRepositorySource
|
||||
} from '../repositories/github-api-repository'
|
||||
import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity'
|
||||
import { acquire, release } from '../execution/github-operation-slots'
|
||||
import { classifyGhError } from '../api/gh-error-classification'
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import { codeHostFailure, combinedClassifiedFailure } from '../../../shared/code-host-failure-copy'
|
||||
import type { ClassifiedError } from '../../../shared/classified-error'
|
||||
import { githubBodyImageUrls, githubBodyMediaHeaders } from '../attachments/body-image-urls'
|
||||
|
||||
export async function updateIssue(
|
||||
repoPath: string,
|
||||
issueNumber: number,
|
||||
updates: GitHubIssueUpdate,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {},
|
||||
preference?: IssueSourcePreference,
|
||||
ownerRepoOverride?: GitHubApiRepository | null
|
||||
): Promise<{ ok: true; bodyImageUrls?: Record<string, string> } | { ok: false; error: string }> {
|
||||
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
|
||||
repoPath,
|
||||
ownerRepoOverride ??
|
||||
(async () =>
|
||||
(
|
||||
await resolveIssueGitHubApiRepositorySource(
|
||||
repoPath,
|
||||
preference,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
).source),
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
if (!ownerRepo) {
|
||||
return codeHostFailure('github.repoUnresolved')
|
||||
}
|
||||
|
||||
const repo = `${ownerRepo.owner}/${ownerRepo.repo}`
|
||||
const errors: ClassifiedError[] = []
|
||||
let bodyImageUrls: Record<string, string> | undefined
|
||||
|
||||
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) {
|
||||
// Why: gh exits 0 when the issue is already in the target state, so any failure is real.
|
||||
const stderr = err instanceof Error ? err.message : String(err)
|
||||
errors.push(classifyGhError(stderr))
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.body !== undefined) {
|
||||
await acquire()
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'-X',
|
||||
'PATCH',
|
||||
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}`,
|
||||
...githubBodyMediaHeaders(updates.body),
|
||||
'--input',
|
||||
'-'
|
||||
],
|
||||
{ ...ghOptions, stdin: JSON.stringify({ body: updates.body }) }
|
||||
)
|
||||
try {
|
||||
const response: { body?: string; body_html?: string } = JSON.parse(stdout)
|
||||
if (response?.body === updates.body) {
|
||||
bodyImageUrls = githubBodyImageUrls(response.body, response.body_html)
|
||||
}
|
||||
} catch {
|
||||
// Optional display data cannot turn an accepted edit into a failed write.
|
||||
}
|
||||
} catch (err) {
|
||||
const stderr = err instanceof Error ? err.message : String(err)
|
||||
errors.push(classifyGhError(stderr))
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
return combinedClassifiedFailure(errors)
|
||||
}
|
||||
return { ok: true, bodyImageUrls }
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../repositories/github-repository-identity'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const mocks = vi.hoisted(() => ({ exec: vi.fn(), guard: vi.fn() }))
|
||||
vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: mocks.exec
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
ghRepoExecOptions: () => ({}),
|
||||
githubRepoContext: () => ({})
|
||||
}))
|
||||
vi.mock('../api/rate-limit', () => ({
|
||||
repositoryRateLimitGuard: mocks.guard,
|
||||
noteRepositoryRateLimitSpend: vi.fn()
|
||||
}))
|
||||
import { getIssueBodyAndComments, getIssueDetailsViaGraphQL } from './issue-work-item-details'
|
||||
const repository = { owner: 'acme', repo: 'widgets' }
|
||||
|
||||
describe('explicit task refresh conversation reads', () => {
|
||||
beforeEach(() => {
|
||||
mocks.exec.mockReset()
|
||||
mocks.guard.mockReset()
|
||||
mocks.guard.mockReturnValue({ blocked: false })
|
||||
})
|
||||
it('bypasses body, comments and timeline caches and reads every comments page', async () => {
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: args.some((arg) => arg.includes('/comments?'))
|
||||
? JSON.stringify([
|
||||
[{ id: 1, user: null, body: 'first', created_at: '', html_url: '' }],
|
||||
[{ id: 2, user: null, body: 'second', created_at: '', html_url: '' }]
|
||||
])
|
||||
: args.some((arg) => arg.includes('/timeline?'))
|
||||
? ''
|
||||
: JSON.stringify({ body: 'current', assignees: [] })
|
||||
}))
|
||||
const result = await getIssueBodyAndComments('/repo', 42, repository, null, {}, true)
|
||||
expect(result.body).toBe('current')
|
||||
expect(result.comments.map((comment) => comment.body)).toEqual(['first', 'second'])
|
||||
for (const [args] of mocks.exec.mock.calls.filter(([args]) =>
|
||||
args.some((arg: string) => arg.startsWith('repos/'))
|
||||
)) {
|
||||
expect(args).not.toContain('--cache')
|
||||
}
|
||||
expect(
|
||||
mocks.exec.mock.calls.find(([args]) =>
|
||||
args.some((arg: string) => arg.includes('/comments?'))
|
||||
)?.[0]
|
||||
).toEqual(expect.arrayContaining(['--paginate', '--slurp']))
|
||||
})
|
||||
it('marks only the comments the reading gh account wrote', async () => {
|
||||
const comment = (id: number, login: string) => ({
|
||||
id,
|
||||
user: { login, avatar_url: '' },
|
||||
body: 'LGTM',
|
||||
created_at: '',
|
||||
html_url: ''
|
||||
})
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: args.includes('user')
|
||||
? 'Me\n'
|
||||
: args.some((arg) => arg.includes('/comments?'))
|
||||
? JSON.stringify([[comment(1, 'alice')], [comment(2, 'me')]])
|
||||
: args.some((arg) => arg.includes('/timeline?'))
|
||||
? ''
|
||||
: JSON.stringify({ body: 'current' })
|
||||
}))
|
||||
const result = await getIssueBodyAndComments('/repo', 42, repository, null, {}, true)
|
||||
expect(result.comments.map((c) => [c.author, c.viewerDidAuthor])).toEqual([
|
||||
['alice', undefined],
|
||||
['me', true]
|
||||
])
|
||||
})
|
||||
|
||||
it('retains ordinary fallback behavior but does not report an explicit rate-limited read as success', async () => {
|
||||
mocks.guard.mockReturnValue({ blocked: true })
|
||||
expect(await getIssueBodyAndComments('/repo', 42, repository)).toEqual({
|
||||
body: '',
|
||||
comments: [],
|
||||
assignees: [],
|
||||
timelineItems: []
|
||||
})
|
||||
await expect(getIssueBodyAndComments('/repo', 42, repository, null, {}, true)).rejects.toThrow()
|
||||
expect(mocks.exec).not.toHaveBeenCalled()
|
||||
})
|
||||
it('falls back from incomplete GraphQL conversations and malformed timelines', async () => {
|
||||
mocks.exec.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
issue: { body: 'new', comments: { nodes: [], pageInfo: { hasNextPage: true } } }
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
expect(
|
||||
await getIssueDetailsViaGraphQL('/repo', 42, repository, null, {}, false, true)
|
||||
).toBeNull()
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: args.some((arg) => arg.includes('/timeline?'))
|
||||
? 'not-json'
|
||||
: args.some((arg) => arg.includes('/comments?'))
|
||||
? '[]'
|
||||
: '{"body":"new"}'
|
||||
}))
|
||||
await expect(getIssueBodyAndComments('/repo', 42, repository, null, {}, true)).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
it('pairs issue and comment image sources through collapsed and REST detail reads', async () => {
|
||||
mocks.exec.mockReset()
|
||||
mocks.guard.mockReturnValue({ blocked: false })
|
||||
const body =
|
||||
''
|
||||
const html =
|
||||
'<img src="https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST">'
|
||||
mocks.exec.mockImplementation(async (args: string[]) => ({
|
||||
stdout: JSON.stringify(
|
||||
args.includes('graphql')
|
||||
? {
|
||||
data: {
|
||||
repository: {
|
||||
issue: {
|
||||
body,
|
||||
bodyHTML: html,
|
||||
comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
: args.some((arg) => arg.includes('/timeline?'))
|
||||
? []
|
||||
: args.some((arg) => arg.includes('/comments?'))
|
||||
? [{ id: 1, user: null, body, body_html: html }]
|
||||
: { body, body_html: html }
|
||||
)
|
||||
}))
|
||||
const collapsed = await getIssueDetailsViaGraphQL('/repo', 42, repository)
|
||||
const rest = await getIssueBodyAndComments('/repo', 42, repository)
|
||||
for (const details of [collapsed!, rest]) {
|
||||
expect(details.body).toBe(body)
|
||||
expect(details.bodyImageUrls).toEqual({
|
||||
'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488':
|
||||
'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST'
|
||||
})
|
||||
expect(details.comments[0].bodyImageUrls).toEqual(details.bodyImageUrls)
|
||||
}
|
||||
for (const [args] of mocks.exec.mock.calls.filter(([args]) =>
|
||||
args.some((arg: string) => /\/issues\/42(?:$|\/comments)/.test(arg))
|
||||
)) {
|
||||
expect(args).toContain('Accept: application/vnd.github.full+json')
|
||||
expect(args).not.toContain('--cache')
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['optional HTML', 'required body', 'pathless', 'rejection without errors'] as const)(
|
||||
'admits rejected issue stdout only for available optional HTML failures (%s)',
|
||||
async (input) => {
|
||||
mocks.exec.mockReset()
|
||||
mocks.guard.mockReturnValue({ blocked: false })
|
||||
const body =
|
||||
''
|
||||
const html =
|
||||
'<img src="https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST">'
|
||||
mocks.exec.mockRejectedValueOnce(
|
||||
Object.assign(new Error('GraphQL failed'), {
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
issue: {
|
||||
body,
|
||||
bodyHTML: html,
|
||||
comments: {
|
||||
pageInfo: { hasNextPage: false },
|
||||
nodes: [{ databaseId: 1, body, bodyHTML: html }]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
errors:
|
||||
input === 'rejection without errors'
|
||||
? undefined
|
||||
: [
|
||||
{
|
||||
path:
|
||||
input === 'pathless'
|
||||
? undefined
|
||||
: ['repository', 'issue', input === 'required body' ? 'body' : 'bodyHTML']
|
||||
}
|
||||
]
|
||||
})
|
||||
})
|
||||
)
|
||||
mocks.exec.mockResolvedValueOnce({ stdout: '[]' })
|
||||
const result = await getIssueDetailsViaGraphQL('/repo', 42, repository, null, {}, false, true)
|
||||
if (input !== 'optional HTML') {
|
||||
expect(result).toBeNull()
|
||||
expect(mocks.exec).toHaveBeenCalledTimes(1)
|
||||
return
|
||||
}
|
||||
expect(result?.body).toBe(body)
|
||||
expect(result?.bodyImageUrls).toBeUndefined()
|
||||
expect(result?.comments[0].bodyImageUrls).toEqual({
|
||||
'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488':
|
||||
'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST'
|
||||
})
|
||||
expect(mocks.exec).toHaveBeenCalledTimes(2)
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,292 @@
|
||||
import {
|
||||
GITHUB_BODY_MEDIA_TYPE,
|
||||
githubBodyImageUrls,
|
||||
removeFailedGitHubBodyHtml
|
||||
} from '../attachments/body-image-urls'
|
||||
import { extractExecError } from '../../git/command-runner/process-capture/exec-error'
|
||||
import type {
|
||||
GitHubIssueTimelineItem,
|
||||
PRComment
|
||||
} from '../../../shared/github/comments/comment-types'
|
||||
import type { GitHubAssignableUser } from '../../../shared/github/pull-requests/pull-request-types'
|
||||
import {
|
||||
ISSUE_DETAILS_QUERY,
|
||||
issueItemSchema,
|
||||
type GraphQLIssueDetailsResponse
|
||||
} from './issue-details-query'
|
||||
import { mapIssueWorkItem } from '../client/map/work-item'
|
||||
import { restIssueActor } from '../client/map/issue-actor'
|
||||
import type { MainWorkItem } from '../client/map/work-item-field-coercion'
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import {
|
||||
ghRepoExecOptions,
|
||||
githubRepoContext,
|
||||
type LocalGitExecOptions
|
||||
} from '../repositories/github-repository-identity'
|
||||
|
||||
import { githubHostExecOptions } from '../repositories/github-repository-host'
|
||||
import type { GitHubRepositoryIdentity as GitHubApiRepository } from '../../../shared/github/repositories/repository-identity'
|
||||
import { getIssueTimelineItems } from './issue-timeline'
|
||||
import { readViewerLogin } from '../client/fetch/authenticated-viewer'
|
||||
import { viewerAuthorship } from '../../source-control/comment-viewer-authorship'
|
||||
import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../api/rate-limit'
|
||||
|
||||
export type CollapsedIssueDetails = {
|
||||
item?: MainWorkItem
|
||||
body: string
|
||||
bodyImageUrls?: Record<string, string>
|
||||
comments: PRComment[]
|
||||
assignees: string[]
|
||||
assigneeUsers: GitHubAssignableUser[]
|
||||
participants: GitHubAssignableUser[]
|
||||
timelineItems: GitHubIssueTimelineItem[]
|
||||
}
|
||||
|
||||
export async function getIssueDetailsViaGraphQL(
|
||||
repoPath: string,
|
||||
issueNumber: number,
|
||||
repository: GitHubApiRepository | null,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {},
|
||||
includeItem = false,
|
||||
fresh = false
|
||||
): Promise<CollapsedIssueDetails | null> {
|
||||
const ghOptions = {
|
||||
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
|
||||
...githubHostExecOptions(repository)
|
||||
}
|
||||
if (!repository) {
|
||||
return null
|
||||
}
|
||||
if (repositoryRateLimitGuard(repository, 'graphql', ghOptions).blocked) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions)
|
||||
let stdout: string
|
||||
let rejected = false
|
||||
try {
|
||||
;({ stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'graphql',
|
||||
'-f',
|
||||
`query=${ISSUE_DETAILS_QUERY}`,
|
||||
'-f',
|
||||
`owner=${repository.owner}`,
|
||||
'-f',
|
||||
`repo=${repository.repo}`,
|
||||
'-F',
|
||||
`number=${issueNumber}`,
|
||||
'-F',
|
||||
`includeItem=${includeItem}`
|
||||
],
|
||||
ghOptions
|
||||
))
|
||||
} catch (error) {
|
||||
stdout = extractExecError(error).stdout
|
||||
rejected = true
|
||||
}
|
||||
const parsed: GraphQLIssueDetailsResponse = JSON.parse(stdout)
|
||||
const errors = removeFailedGitHubBodyHtml(parsed.data, parsed.errors)
|
||||
if (errors?.length || (rejected && !parsed.errors?.length)) {
|
||||
return null
|
||||
}
|
||||
const issue = parsed.data?.repository?.issue
|
||||
if (!issue) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
fresh &&
|
||||
(typeof issue.body !== 'string' ||
|
||||
!Array.isArray(issue.comments?.nodes) ||
|
||||
issue.comments?.pageInfo?.hasNextPage !== false)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const itemData = includeItem ? issueItemSchema.safeParse(issue) : undefined
|
||||
if (itemData?.success && itemData.data.number !== issueNumber) {
|
||||
return null
|
||||
}
|
||||
const comments: PRComment[] = (issue.comments?.nodes ?? [])
|
||||
.filter(
|
||||
(comment): comment is NonNullable<typeof comment> => typeof comment?.databaseId === 'number'
|
||||
)
|
||||
.map((comment) => ({
|
||||
id: comment.databaseId as number,
|
||||
author: comment.author?.login ?? 'ghost',
|
||||
authorAvatarUrl: comment.author?.avatarUrl ?? '',
|
||||
body: comment.body ?? '',
|
||||
bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML),
|
||||
createdAt: comment.createdAt ?? '',
|
||||
url: comment.url ?? '',
|
||||
isBot: comment.author?.__typename === 'Bot',
|
||||
...(comment.viewerDidAuthor === true ? { viewerDidAuthor: true } : {})
|
||||
}))
|
||||
const assigneeUsers: GitHubAssignableUser[] = (issue.assignees?.nodes ?? [])
|
||||
.filter((assignee): assignee is { login: string; avatarUrl?: string; name?: string | null } =>
|
||||
Boolean(assignee?.login)
|
||||
)
|
||||
.map((assignee) => ({
|
||||
login: assignee.login,
|
||||
name: assignee.name ?? null,
|
||||
avatarUrl: assignee.avatarUrl ?? ''
|
||||
}))
|
||||
const participants: GitHubAssignableUser[] = (issue.participants?.nodes ?? [])
|
||||
.filter((user) => Boolean(user.login))
|
||||
.map((user) => ({
|
||||
login: user.login,
|
||||
name: user.name ?? null,
|
||||
avatarUrl: user.avatarUrl ?? ''
|
||||
}))
|
||||
const details: CollapsedIssueDetails = {
|
||||
...(itemData?.success
|
||||
? {
|
||||
item: mapIssueWorkItem({
|
||||
...itemData.data,
|
||||
state: itemData.data.state.toLowerCase(),
|
||||
user: restIssueActor(itemData.data.author),
|
||||
labels: itemData.data.labels.nodes,
|
||||
assignees: assigneeUsers
|
||||
})
|
||||
}
|
||||
: {}),
|
||||
body: issue.body ?? '',
|
||||
bodyImageUrls: githubBodyImageUrls(issue.body, issue.bodyHTML),
|
||||
comments,
|
||||
assignees: assigneeUsers.map((assignee) => assignee.login),
|
||||
assigneeUsers,
|
||||
participants,
|
||||
timelineItems: await getIssueTimelineItems(repository, issueNumber, ghOptions, fresh)
|
||||
}
|
||||
return details
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function getIssueBodyAndComments(
|
||||
repoPath: string,
|
||||
issueNumber: number,
|
||||
repository: GitHubApiRepository | null,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {},
|
||||
fresh = false
|
||||
): Promise<
|
||||
Pick<CollapsedIssueDetails, 'body' | 'bodyImageUrls' | 'comments' | 'assignees' | 'timelineItems'>
|
||||
> {
|
||||
const ghOptions = {
|
||||
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
|
||||
...githubHostExecOptions(repository)
|
||||
}
|
||||
try {
|
||||
if (repository) {
|
||||
if (repositoryRateLimitGuard(repository, 'core', ghOptions).blocked) {
|
||||
if (fresh) {
|
||||
throw new Error('GitHub details unavailable')
|
||||
}
|
||||
return { body: '', comments: [], assignees: [], timelineItems: [] }
|
||||
}
|
||||
noteRepositoryRateLimitSpend(repository, 'core', 3, ghOptions)
|
||||
const [issueResult, commentsResult, timelineItems, viewerLogin] = await Promise.all([
|
||||
ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'-H',
|
||||
GITHUB_BODY_MEDIA_TYPE,
|
||||
`repos/${repository.owner}/${repository.repo}/issues/${issueNumber}`
|
||||
],
|
||||
ghOptions
|
||||
),
|
||||
ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'-H',
|
||||
GITHUB_BODY_MEDIA_TYPE,
|
||||
...(fresh ? ['--paginate', '--slurp'] : []),
|
||||
`repos/${repository.owner}/${repository.repo}/issues/${issueNumber}/comments?per_page=100`
|
||||
],
|
||||
ghOptions
|
||||
),
|
||||
getIssueTimelineItems(repository, issueNumber, ghOptions, fresh),
|
||||
readViewerLogin(ghOptions)
|
||||
])
|
||||
const issue: {
|
||||
body?: string | null
|
||||
body_html?: unknown
|
||||
assignees?: { login: string }[]
|
||||
} = JSON.parse(issueResult.stdout)
|
||||
type RESTComment = {
|
||||
id: number
|
||||
user: { login: string; avatar_url: string; type?: string } | null
|
||||
body: string
|
||||
body_html?: unknown
|
||||
created_at: string
|
||||
html_url: string
|
||||
}
|
||||
if (fresh && !('body' in issue)) {
|
||||
throw new Error('GitHub details unavailable')
|
||||
}
|
||||
// A slurped (paginated) read nests one array per page; an ordinary read is one page.
|
||||
const parsedComments: RESTComment[][] | RESTComment[] = JSON.parse(commentsResult.stdout)
|
||||
const comments = parsedComments.flat().map((comment): PRComment => ({
|
||||
id: comment.id,
|
||||
author: comment.user?.login ?? 'ghost',
|
||||
authorAvatarUrl: comment.user?.avatar_url ?? '',
|
||||
body: comment.body ?? '',
|
||||
bodyImageUrls: githubBodyImageUrls(comment.body, comment.body_html),
|
||||
createdAt: comment.created_at,
|
||||
url: comment.html_url,
|
||||
isBot: comment.user?.type === 'Bot',
|
||||
...viewerAuthorship(comment.user?.login, viewerLogin)
|
||||
}))
|
||||
const details = {
|
||||
body: issue.body ?? '',
|
||||
bodyImageUrls: githubBodyImageUrls(issue.body, issue.body_html),
|
||||
comments,
|
||||
assignees: (issue.assignees ?? []).map((assignee) => assignee.login),
|
||||
timelineItems
|
||||
}
|
||||
return details
|
||||
}
|
||||
if (connectionId) {
|
||||
// A connection-backed lookup must not use ambient local GH_REPO/GH_HOST.
|
||||
return { body: '', comments: [], assignees: [], timelineItems: [] }
|
||||
}
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['issue', 'view', String(issueNumber), '--json', 'body,comments,assignees'],
|
||||
ghOptions
|
||||
)
|
||||
const data: {
|
||||
body?: string
|
||||
comments?: {
|
||||
author: { login: string }
|
||||
body: string
|
||||
createdAt: string
|
||||
url: string
|
||||
viewerDidAuthor?: boolean
|
||||
}[]
|
||||
assignees?: { login: string }[]
|
||||
} = JSON.parse(stdout)
|
||||
const comments = (data.comments ?? []).map((comment, index): PRComment => ({
|
||||
id: index,
|
||||
author: comment.author?.login ?? 'ghost',
|
||||
authorAvatarUrl: '',
|
||||
body: comment.body ?? '',
|
||||
createdAt: comment.createdAt,
|
||||
url: comment.url ?? '',
|
||||
...(comment.viewerDidAuthor === true ? { viewerDidAuthor: true } : {})
|
||||
}))
|
||||
return {
|
||||
body: data.body ?? '',
|
||||
comments,
|
||||
assignees: (data.assignees ?? []).map((assignee) => assignee.login),
|
||||
timelineItems: []
|
||||
}
|
||||
} catch (error) {
|
||||
if (fresh) {
|
||||
throw error
|
||||
}
|
||||
return { body: '', comments: [], assignees: [], timelineItems: [] }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import type * as GhExecFileModule from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import type * as GithubOwnerRepoSelectionModule from '../repositories/github-owner-repo-selection'
|
||||
import type * as GithubOperationSlotsModule from '../execution/github-operation-slots'
|
||||
import type * as GithubEnterpriseRepositoryModule from '../repositories/github-enterprise-repository'
|
||||
import type * as GithubApiRepositoryModule from '../repositories/github-api-repository'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getIssueOwnerRepoMock,
|
||||
resolveIssueSourceMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
} = vi.hoisted(() => ({
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
getIssueOwnerRepoMock: vi.fn(),
|
||||
resolveIssueSourceMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async () => {
|
||||
const actual = await vi.importActual<typeof GhExecFileModule>(
|
||||
'../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../repositories/github-owner-repo-selection', async () => {
|
||||
const actual = await vi.importActual<typeof GithubOwnerRepoSelectionModule>(
|
||||
'../repositories/github-owner-repo-selection'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
getOwnerRepo: getIssueOwnerRepoMock,
|
||||
resolveIssueSource: resolveIssueSourceMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../execution/github-operation-slots', async () => {
|
||||
const actual = await vi.importActual<typeof GithubOperationSlotsModule>(
|
||||
'../execution/github-operation-slots'
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
acquire: acquireMock,
|
||||
release: releaseMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../repositories/github-enterprise-repository', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubEnterpriseRepositoryModule>()),
|
||||
isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true)
|
||||
}))
|
||||
|
||||
vi.mock('../repositories/github-api-repository', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof GithubApiRepositoryModule>()
|
||||
const withDotComHost = <T extends { host?: string } | null | undefined>(repo: T) =>
|
||||
repo ? { host: 'github.com' as const, ...repo } : repo
|
||||
return {
|
||||
...actual,
|
||||
getIssueGitHubApiRepository: async (
|
||||
repoPath: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: unknown
|
||||
) => withDotComHost(await getIssueOwnerRepoMock(repoPath, connectionId, localGitOptions)),
|
||||
resolveIssueGitHubApiRepositorySource: async (
|
||||
repoPath: string,
|
||||
preference: unknown,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: unknown
|
||||
) => {
|
||||
const result = await resolveIssueSourceMock(
|
||||
repoPath,
|
||||
preference,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
return {
|
||||
...result,
|
||||
source: withDotComHost(result?.source)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
import { createIssue } from './issue-create'
|
||||
import { updateIssue } from './issue-update'
|
||||
|
||||
import { _resetOriginGitHubApiRepositoryCache } from '../repositories/github-api-repository-remote-probe'
|
||||
|
||||
beforeEach(() => {
|
||||
_resetOriginGitHubApiRepositoryCache()
|
||||
})
|
||||
|
||||
describe('issue source operations', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
getIssueOwnerRepoMock.mockReset()
|
||||
resolveIssueSourceMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
// Share the preference-aware resolver with the issue-owner fixtures.
|
||||
resolveIssueSourceMock.mockImplementation(async () => ({
|
||||
source: await getIssueOwnerRepoMock(),
|
||||
fellBack: false
|
||||
}))
|
||||
})
|
||||
|
||||
it('reports partial success when oversized-body patch fails', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock
|
||||
.mockRejectedValueOnce(new Error('body is too long (maximum is 65536 characters)'))
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 928,
|
||||
html_url: 'https://github.com/stablyai/orca/issues/928'
|
||||
})
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('HTTP 500: update failed'))
|
||||
|
||||
await expect(createIssue('/repo-root', 'Partial issue', 'data:image')).resolves.toEqual({
|
||||
ok: true,
|
||||
number: 928,
|
||||
url: 'https://github.com/stablyai/orca/issues/928',
|
||||
bodySaveWarning:
|
||||
'Issue https://github.com/stablyai/orca/issues/928 was created, but saving its body failed: HTTP 500: update failed'
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the accepted issue body representation through a compound metadata edit', async () => {
|
||||
const body =
|
||||
''
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
body,
|
||||
body_html:
|
||||
'<img src="https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST">'
|
||||
})
|
||||
})
|
||||
.mockResolvedValueOnce({ stdout: '' })
|
||||
await expect(updateIssue('/repo-root', 924, { body, title: 'Updated' })).resolves.toEqual({
|
||||
ok: true,
|
||||
bodyImageUrls: {
|
||||
'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488':
|
||||
'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST'
|
||||
}
|
||||
})
|
||||
expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain(
|
||||
'Accept: application/vnd.github.full+json'
|
||||
)
|
||||
expect(ghExecFileAsyncMock.mock.calls[0][1].stdin).toBe(JSON.stringify({ body }))
|
||||
})
|
||||
|
||||
it.each([
|
||||
'',
|
||||
'not JSON',
|
||||
JSON.stringify({
|
||||
body: 'different ',
|
||||
body_html:
|
||||
'<img src="https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST">'
|
||||
})
|
||||
])(
|
||||
'keeps an accepted issue edit successful without a usable paired response (%s)',
|
||||
async (stdout) => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout })
|
||||
await expect(
|
||||
updateIssue('/repo-root', 924, {
|
||||
body: ''
|
||||
})
|
||||
).resolves.toEqual({
|
||||
ok: true,
|
||||
bodyImageUrls: undefined
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
it('reports a failed close whose gh error mentions "already"', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
|
||||
ghExecFileAsyncMock.mockRejectedValueOnce(
|
||||
new Error('GraphQL: API rate limit already exceeded for user ID 1.')
|
||||
)
|
||||
|
||||
await expect(updateIssue('/repo-root', 924, { state: 'closed' })).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: 'GitHub rate limit hit. Try again in a few minutes.'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { ClassifiedError } from '../../../shared/classified-error'
|
||||
import type { IssueInfo } from '../../../shared/github/pull-requests/pull-request-types'
|
||||
import type { IssueSourcePreference } from '../../../shared/repo-types'
|
||||
import { mapIssueInfo } from '../api/github-read-response'
|
||||
import type { LocalGitExecOptions } from '../repositories/github-repository-identity'
|
||||
import {
|
||||
getIssueGitHubApiRepository,
|
||||
resolveGitHubRepoExecution,
|
||||
resolveIssueGitHubApiRepositorySource
|
||||
} from '../repositories/github-api-repository'
|
||||
// prettier-ignore
|
||||
import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import { acquire, release } from '../execution/github-operation-slots'
|
||||
import { classifyListIssuesError } from '../api/gh-error-classification'
|
||||
|
||||
// Keep successful-empty and failed listings distinguishable; fallback toasts belong to the Tasks envelope.
|
||||
export type IssueListResult = {
|
||||
items: IssueInfo[]
|
||||
error?: ClassifiedError
|
||||
}
|
||||
|
||||
/** Linked issue numbers keep heuristic source resolution; changing list preference must not retarget existing links. */
|
||||
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
|
||||
)
|
||||
// Without local cwd, unresolved connection-backed requests could target gh's default repository.
|
||||
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)
|
||||
}
|
||||
// Local compatibility path relies on gh repository discovery.
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['issue', 'view', String(issueNumber), '--json', 'number,title,state,url,labels,body'],
|
||||
ghOptions
|
||||
)
|
||||
const data = JSON.parse(stdout)
|
||||
return mapIssueInfo(data)
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
/** Return classified failures separately so unavailable repositories cannot look like empty backlogs. */
|
||||
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
|
||||
)
|
||||
// Refuse unresolved remote identities rather than listing gh's default repository.
|
||||
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>[]
|
||||
// GitHub REST issues includes PRs; exclude them from this issue-only result.
|
||||
return {
|
||||
items: data
|
||||
.filter((d) => !('pull_request' in d))
|
||||
.map((d) => mapIssueInfo(d as Parameters<typeof mapIssueInfo>[0]))
|
||||
}
|
||||
}
|
||||
// Local compatibility path relies on gh repository discovery.
|
||||
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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user