'
+const expectedMap = {
+ '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'
+}
+beforeEach(() => {
+ mocks.exec.mockReset()
+ mocks.graphql.mockReset()
+})
+
+it('gets PR metadata images in its existing uncached full-media read', async () => {
+ mocks.exec.mockResolvedValueOnce({
+ stdout: JSON.stringify({ body, body_html: html, head: { sha: 'head' } })
+ })
+ const metadata = await getPRMetadata('/repo', 7, { owner: 'acme', repo: 'widgets' })
+ expect(metadata).toMatchObject({ body, headSha: 'head', bodyImageUrls: expectedMap })
+ expect(mocks.exec).toHaveBeenCalledTimes(1)
+ expect(mocks.exec.mock.calls[0][0]).toEqual([
+ 'api',
+ '-H',
+ 'Accept: application/vnd.github.full+json',
+ 'repos/acme/widgets/pulls/7'
+ ])
+})
+
+it.each(['issue', 'pr'] as const)(
+ 'gets slug %s body and comment images in one existing read',
+ async (type) => {
+ mocks.graphql.mockResolvedValueOnce({
+ ok: true,
+ data: {
+ repository: {
+ [type === 'issue' ? 'issue' : 'pullRequest']: {
+ id: 'ITEM',
+ body,
+ bodyHTML: html,
+ comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] }
+ }
+ }
+ }
+ })
+ const result = await getWorkItemDetailsBySlug({
+ owner: 'acme',
+ repo: 'widgets',
+ number: 7,
+ type
+ })
+ expect(result.ok && result.details.body).toBe(body)
+ expect(result.ok && result.details.bodyImageUrls).toEqual(expectedMap)
+ expect(result.ok && result.details.comments[0].bodyImageUrls).toEqual(expectedMap)
+ expect(mocks.graphql).toHaveBeenCalledTimes(1)
+ expect(mocks.exec).not.toHaveBeenCalled()
+ }
+)
+
+it.each(['issue', 'pr'] as const)(
+ 'recovers available slug %s data without trusting failed HTML',
+ async (type) => {
+ const root = type === 'issue' ? 'issue' : 'pullRequest'
+ mocks.graphql.mockResolvedValueOnce({
+ ok: false,
+ error: { type: 'unknown', message: 'field error' },
+ raw: {
+ stdout: JSON.stringify({
+ data: {
+ repository: {
+ [root]: {
+ id: 'ITEM',
+ body,
+ bodyHTML: html,
+ comments: {
+ nodes: [
+ { databaseId: 1, body, bodyHTML: html },
+ { databaseId: 2, body, bodyHTML: html }
+ ]
+ }
+ }
+ }
+ },
+ errors: [
+ { path: ['repository', root, 'bodyHTML'] },
+ { path: ['repository', root, 'comments', 'nodes', 0, 'bodyHTML'] }
+ ]
+ }),
+ stderr: ''
+ }
+ })
+ const result = await getWorkItemDetailsBySlug({
+ owner: 'acme',
+ repo: 'widgets',
+ number: 7,
+ type
+ })
+ expect(result.ok && result.details.body).toBe(body)
+ expect(result.ok && result.details.bodyImageUrls).toBeUndefined()
+ expect(result.ok && result.details.comments[0].bodyImageUrls).toBeUndefined()
+ expect(result.ok && result.details.comments[1].bodyImageUrls).toEqual(expectedMap)
+ expect(mocks.graphql).toHaveBeenCalledTimes(1)
+ expect(mocks.exec).not.toHaveBeenCalled()
+ }
+)
+
+it.each(['null parent', 'required field', 'pathless'] as const)(
+ 'keeps the original slug failure for %s',
+ async (input) => {
+ const error = { type: 'unknown', message: 'original failure' }
+ mocks.graphql.mockResolvedValueOnce({
+ ok: false,
+ error,
+ raw: {
+ stderr: '',
+ stdout: JSON.stringify({
+ data: {
+ repository: { issue: input === 'null parent' ? null : { body, bodyHTML: html } }
+ },
+ errors: [
+ {
+ path:
+ input === 'pathless'
+ ? undefined
+ : ['repository', 'issue', input === 'required field' ? 'body' : 'bodyHTML']
+ }
+ ]
+ })
+ }
+ })
+ await expect(
+ getWorkItemDetailsBySlug({ owner: 'acme', repo: 'widgets', number: 7, type: 'issue' })
+ ).resolves.toEqual({ ok: false, error: { type: 'unknown', message: 'original failure' } })
+ }
+)
diff --git a/src/main/github/body-image-urls.test.ts b/src/main/github/body-image-urls.test.ts
new file mode 100644
index 00000000000..a9cb4b32f46
--- /dev/null
+++ b/src/main/github/body-image-urls.test.ts
@@ -0,0 +1,138 @@
+import type * as HtmlParser from 'hast-util-from-html-isomorphic'
+import type { Root, RootContent } from 'hast'
+import { describe, expect, it, vi } from 'vitest'
+const traversal = vi.hoisted(() => ({ enabled: false, parses: 0, children: 0, fail: false }))
+vi.mock('hast-util-from-html-isomorphic', async (load) => {
+ const actual = await load

https://private-user-images.githubusercontent.com/1/dd11040a-fb66-4289-927f-547b16dfc488.png`
+ expect(githubBodyImageUrls(body, html)).toEqual({
+ 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': signed,
+ 'https://github.enterprise/team/repo/assets/42/ab11040a-fb66-4289-927f-547b16dfc488':
+ 'https://github.enterprise/storage/ab11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST'
+ })
+ expect(githubBodyImageUrls(body, undefined)).toBeUndefined()
+ expect(githubBodyImageUrls(``, `
'
+ )
+ ).toBeUndefined()
+ })
+
+ it('bounds candidate validation and indexed lookups at N and 10N', () => {
+ for (const n of [100, 1000]) {
+ const ids = Array.from(
+ { length: n },
+ (_, i) => `ce11040a-fb66-4289-927f-${String(i).padStart(12, '0')}`
+ )
+ const body = ids
+ .map((id) => ``)
+ .join('\n')
+ const html = ids
+ .map(
+ (id) =>
+ `
`
+ )
+ .join('\n')
+ traversal.enabled = true
+ traversal.parses = 0
+ traversal.children = 0
+ const pathname = vi.spyOn(URL.prototype, 'pathname', 'get')
+ const originalGet = Map.prototype.get
+ let lookups = 0
+ Map.prototype.get = function (this: Map
',
+ path: 'file.ts'
+ }))
+ const threads = Array.from({ length: n / 100 }, (_, i) => ({
+ id: `THREAD_${i}`,
+ isResolved: false,
+ line: 1,
+ startLine: null,
+ originalLine: 1,
+ originalStartLine: null,
+ comments: { nodes: imageComments.slice(i * 100, (i + 1) * 100) }
+ }))
+ ghExecFileAsyncMock.mockResolvedValueOnce(
+ response({
+ comments: { nodes: [comment] },
+ reviews: { nodes: [] },
+ reviewThreads: { nodes: threads }
+ })
+ )
+ const result = await getPRComments('/repo', 7, { ...options, noCache: true })
+ // One request owns all selected bodies, independent of their image population.
+ expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
+ expect(result.filter((c) => c.path === 'file.ts')).toHaveLength(n)
+ if (n === 0) {
+ return
+ }
+ expect(result.find((c) => c.id === 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(result.find((c) => c.id === 0)?.body).toBe(body)
+ }
+ )
+
+ it.each([false, true])(
+ 'holds the existing permit until the paired command settles (reject: %s)',
+ async (reject) => {
+ let settle!: (result: { stdout: string }) => void
+ let fail!: (error: Error) => void
+ const pending = new Promise<{ stdout: string }>((resolve, reject) => {
+ settle = resolve
+ fail = reject
+ })
+ let started!: () => void
+ const commandStarted = new Promise
'
+ const partial = response(
+ {
+ comments: { nodes: [{ ...comment, body, bodyHTML: html }] },
+ reviews: { nodes: [] },
+ reviewThreads: {
+ nodes: [
+ {
+ id: 'THREAD',
+ isResolved: false,
+ line: 1,
+ startLine: null,
+ originalLine: 1,
+ originalStartLine: null,
+ comments: {
+ nodes: [
+ { ...comment, databaseId: 11, body, bodyHTML: html, path: 'file.ts' },
+ { ...comment, databaseId: 12, body, bodyHTML: html, path: 'file.ts' }
+ ]
+ }
+ }
+ ]
+ }
+ },
+ [
+ { path: ['repository', 'pullRequest', 'comments', 'nodes', 0, 'bodyHTML'] },
+ {
+ path: [
+ 'repository',
+ 'pullRequest',
+ 'reviewThreads',
+ 'nodes',
+ 0,
+ 'comments',
+ 'nodes',
+ 0,
+ 'bodyHTML'
+ ]
+ }
+ ]
+ )
+ ghExecFileAsyncMock.mockRejectedValueOnce(Object.assign(new Error('GraphQL error'), partial))
+ const result = await getPRComments('/repo', 7, { ...options, noCache: true })
+ expect(result.map((c) => c.body)).toEqual([body, body, body])
+ expect(result.find((c) => c.id === 10)?.bodyImageUrls).toBeUndefined()
+ expect(result.find((c) => c.id === 11)?.bodyImageUrls).toBeUndefined()
+ expect(result.find((c) => c.id === 12)?.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(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/src/main/github/client/create/add-pr-review-comment.ts b/src/main/github/client/create/add-pr-review-comment.ts
index 6b2f4016c66..25d298241ad 100644
--- a/src/main/github/client/create/add-pr-review-comment.ts
+++ b/src/main/github/client/create/add-pr-review-comment.ts
@@ -1,3 +1,4 @@
+import { githubBodyMediaHeaders } from '../../body-image-urls'
import type {
GitHubCommentResult,
GitHubPRReviewCommentInput
@@ -31,6 +32,7 @@ export async function addPRReviewComment(
try {
const fields = [
'api',
+ ...githubBodyMediaHeaders(args.body),
'-X',
'POST',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${args.prNumber}/comments`,
@@ -97,6 +99,7 @@ export async function addPRReviewCommentReply(
const { stdout } = await ghExecFileAsync(
[
'api',
+ ...githubBodyMediaHeaders(body),
'-X',
'POST',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${prNumber}/comments/${commentId}/replies`,
diff --git a/src/main/github/client/fetch/get-pr-comments.ts b/src/main/github/client/fetch/get-pr-comments.ts
index 8401c219dbd..be44913966c 100644
--- a/src/main/github/client/fetch/get-pr-comments.ts
+++ b/src/main/github/client/fetch/get-pr-comments.ts
@@ -1,3 +1,4 @@
+import { GITHUB_BODY_MEDIA_TYPE } from '../../body-image-urls'
import type { PRComment } from '../../../../shared/github/comment-types'
import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe'
import { extractExecError } from '../../../git/exec-error'
@@ -31,8 +32,6 @@ async function readPRComments(
let restBudgetFailed = false
try {
if (ownerRepo) {
- // Explicit refresh bypasses the polling cache.
- const cacheArgs = options?.noCache ? [] : ['--cache', '60s']
const base = `repos/${ownerRepo.owner}/${ownerRepo.repo}`
// Retain successful comment sources when another endpoint fails.
@@ -60,9 +59,9 @@ async function readPRComments(
)
} catch (error) {
// gh exits nonzero for partial GraphQL errors; keep the successful sources.
- const { stdout } = extractExecError(error)
+ const { stdout, stderr } = extractExecError(error)
threadsResult = stdout ? { stdout } : null
- console.warn('Failed to fetch review threads:', error)
+ console.warn('Failed to fetch review threads:', stderr)
}
}
@@ -85,12 +84,12 @@ async function readPRComments(
try {
noteRepositoryRateLimitSpend(ownerRepo, 'core', reviews ? 1 : 2, ghOptions)
const [{ stdout }, viewerLogin] = await Promise.all([
- ghExecFileAsync(['api', ...cacheArgs, endpoint], ghOptions),
+ ghExecFileAsync(['api', '-H', GITHUB_BODY_MEDIA_TYPE, endpoint], ghOptions),
reviews ? null : readViewerLogin(ghOptions)
])
return parseRestPRComments(stdout, reviews, viewerLogin)
} catch (error) {
- console.warn('Failed to fetch PR conversation fallback:', error)
+ console.warn('Failed to fetch PR conversation fallback:', extractExecError(error).stderr)
return []
}
}
diff --git a/src/main/github/client/fetch/pr-conversation-response.ts b/src/main/github/client/fetch/pr-conversation-response.ts
index 7dfbac2e82a..1593a486f82 100644
--- a/src/main/github/client/fetch/pr-conversation-response.ts
+++ b/src/main/github/client/fetch/pr-conversation-response.ts
@@ -1,3 +1,4 @@
+import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../../body-image-urls'
import type { Nodes } from 'mdast'
import { z } from 'zod'
import remarkParse from 'remark-parse'
@@ -14,6 +15,7 @@ const commentSchema = z.object({
.object({ __typename: z.string().optional(), login: z.string(), avatarUrl: z.string() })
.nullable(),
body: z.string().nullish(),
+ bodyHTML: z.unknown().optional(),
createdAt: z.string(),
submittedAt: z.string().nullish(),
url: z.string(),
@@ -82,11 +84,12 @@ function hasDatabaseId
'
+ })
+ })
+ const result = await addIssueComment('/repo', 42, body)
+ expect(mocks.exec.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json')
+ expect(mocks.exec.mock.calls[0][1].stdin).toBe(JSON.stringify({ body }))
+ expect(result.ok && result.comment.body).toBe(body)
+ expect(result.ok && result.comment.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'
+ })
+})
+
+it.each(['review', 'reply'])(
+ 'returns paired image sources immediately for %s posts',
+ async (kind) => {
+ mocks.exec.mockClear()
+ const body =
+ ''
+ mocks.exec.mockResolvedValue({
+ stdout: JSON.stringify({
+ id: 1,
+ body,
+ user: null,
+ body_html:
+ '
'
+ })
+ })
+ const result =
+ kind === 'review'
+ ? await addPRReviewComment({
+ repoPath: '/repo',
+ prNumber: 7,
+ body,
+ commitId: 'head',
+ path: 'file.ts',
+ line: 1
+ })
+ : await addPRReviewCommentReply('/repo', 7, 1, body)
+ expect(result.ok && result.comment.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.mock.calls[0][0]).toContain(
+ 'body='
+ )
+ }
+)
diff --git a/src/main/github/issue-comment.ts b/src/main/github/issue-comment.ts
index 88f5f642c63..7f3c2a11f98 100644
--- a/src/main/github/issue-comment.ts
+++ b/src/main/github/issue-comment.ts
@@ -1,3 +1,4 @@
+import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls'
import type { GitHubCommentResult, PRComment } from '../../shared/github/comment-types'
import type { IssueSourcePreference } from '../../shared/repo-types'
import type { LocalGitExecOptions, OwnerRepo } from './gh-utils'
@@ -41,6 +42,7 @@ export async function addIssueComment(
const { stdout } = await ghExecFileAsync(
[
'api',
+ ...githubBodyMediaHeaders(body),
'-X',
'POST',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}/comments`,
@@ -49,14 +51,15 @@ export async function addIssueComment(
],
{ ...ghOptions, stdin: JSON.stringify({ body }) }
)
- const data = JSON.parse(stdout) as {
+ 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')
}
@@ -66,6 +69,7 @@ export async function addIssueComment(
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'
diff --git a/src/main/github/issue-details-query.ts b/src/main/github/issue-details-query.ts
index e22da93d914..5d6921884f0 100644
--- a/src/main/github/issue-details-query.ts
+++ b/src/main/github/issue-details-query.ts
@@ -14,6 +14,7 @@ export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $numb
pageInfo { hasNextPage }
}
body
+ bodyHTML
assignees(first: 50) {
nodes { login avatarUrl(size: 48) ... on User { name } }
pageInfo { hasNextPage }
@@ -26,6 +27,7 @@ export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $numb
nodes {
databaseId
body
+ bodyHTML
createdAt
url
viewerDidAuthor
@@ -62,13 +64,15 @@ export type GraphQLIssueDetailsResponse = {
repository?: {
issue?: {
body?: string | null
+ bodyHTML?: unknown
assignees?: { nodes?: (Partial
'
+ 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 =
+ '
'
+ 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)
+ }
+)
diff --git a/src/main/github/issue-work-item-details.ts b/src/main/github/issue-work-item-details.ts
index e12b34ba0f9..7b44631ac7a 100644
--- a/src/main/github/issue-work-item-details.ts
+++ b/src/main/github/issue-work-item-details.ts
@@ -1,3 +1,9 @@
+import {
+ GITHUB_BODY_MEDIA_TYPE,
+ githubBodyImageUrls,
+ removeFailedGitHubBodyHtml
+} from './body-image-urls'
+import { extractExecError } from '../git/exec-error'
import type { GitHubIssueTimelineItem, PRComment } from '../../shared/github/comment-types'
import type { GitHubAssignableUser } from '../../shared/github/pull-request-types'
import {
@@ -19,6 +25,7 @@ import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-l
export type CollapsedIssueDetails = {
item?: MainWorkItem
body: string
+ bodyImageUrls?: Record
'
+ })
+ })
+ .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:
+ '
'
+ })
+ ])(
+ '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(
diff --git a/src/main/github/project-view/body-image-mutations.test.ts b/src/main/github/project-view/body-image-mutations.test.ts
new file mode 100644
index 00000000000..53c0925b77f
--- /dev/null
+++ b/src/main/github/project-view/body-image-mutations.test.ts
@@ -0,0 +1,170 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const {
+ acquireMock,
+ ghExecFileAsyncMock,
+ noteRepositoryRateLimitSpendMock,
+ projectHostAuthenticationErrorMock,
+ repositoryRateLimitGuardMock,
+ releaseMock,
+ runGraphqlMock,
+ runRestMock
+} = vi.hoisted(() => ({
+ acquireMock: vi.fn(),
+ ghExecFileAsyncMock: vi.fn(),
+ noteRepositoryRateLimitSpendMock: vi.fn(),
+ projectHostAuthenticationErrorMock: vi.fn(),
+ repositoryRateLimitGuardMock: vi.fn(),
+ releaseMock: vi.fn(),
+ runGraphqlMock: vi.fn(),
+ runRestMock: vi.fn()
+}))
+
+vi.mock('./internals', () => ({
+ acquire: acquireMock,
+ release: releaseMock,
+ extractExecError: (err: unknown) => ({
+ stderr: err instanceof Error ? err.message : String(err),
+ stdout: ''
+ }),
+ ghExecFileAsync: ghExecFileAsyncMock,
+ rateLimitGuard: () => ({ blocked: false }),
+ noteRateLimitSpend: vi.fn(),
+ repositoryRateLimitGuard: repositoryRateLimitGuardMock,
+ noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock,
+ projectHostAuthenticationError: projectHostAuthenticationErrorMock,
+ projectGhExecOptions: (host?: string) => ({ host: host ?? 'github.com' }),
+ classifyProjectError: (stderr: string) => ({ type: 'unknown', message: stderr }),
+ rateLimitedError: () => ({ type: 'rate_limited', message: 'rate limited' }),
+ runGraphql: runGraphqlMock,
+ runRest: runRestMock,
+ validateSlugArgs: (owner: string, repo: string) =>
+ owner && repo ? { ok: true } : { ok: false, error: { type: 'validation_error' } },
+ assertPositiveInt: (value: number, name: string) =>
+ Number.isInteger(value) && value > 0
+ ? { ok: true, value }
+ : { ok: false, error: { type: 'validation_error', message: `${name} invalid` } }
+}))
+
+import { updateIssueBySlug } from './mutations'
+import { updatePullRequestBySlug } from './pull-request-mutation'
+import { addIssueCommentBySlug } from './issue-comment-mutations'
+
+describe('Project accepted body representations', () => {
+ beforeEach(() => {
+ acquireMock.mockReset().mockResolvedValue(undefined)
+ ghExecFileAsyncMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' })
+ noteRepositoryRateLimitSpendMock.mockReset()
+ projectHostAuthenticationErrorMock.mockReset().mockResolvedValue(null)
+ repositoryRateLimitGuardMock.mockReset().mockReturnValue({ blocked: false })
+ releaseMock.mockReset()
+ runRestMock.mockReset().mockResolvedValue({ ok: true, data: {} })
+ })
+
+ it.each([updateIssueBySlug, updatePullRequestBySlug])(
+ 'returns paired image sources after a body edit',
+ async (update) => {
+ const body =
+ ''
+ runRestMock.mockResolvedValueOnce({
+ ok: true,
+ data: {
+ body,
+ body_html:
+ '
'
+ }
+ })
+ const result = await update({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } })
+ expect(result).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(runRestMock.mock.calls[0][0]).toContain(`body=${body}`)
+ expect(runRestMock.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json')
+ }
+ )
+
+ it('returns the paired source for a newly posted Project comment', async () => {
+ const body =
+ ''
+ runRestMock.mockResolvedValueOnce({
+ ok: true,
+ data: {
+ id: 1,
+ body,
+ body_html:
+ '
'
+ }
+ })
+ const result = await addIssueCommentBySlug({ owner: 'acme', repo: 'widgets', number: 12, body })
+ expect(result.ok && result.comment.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'
+ })
+ })
+
+ it('does not attach a Project issue map from a different accepted body snapshot', async () => {
+ const body =
+ ''
+ runRestMock.mockResolvedValueOnce({
+ ok: true,
+ data: {
+ body: `${body}\nchanged elsewhere`,
+ body_html:
+ '
'
+ }
+ })
+ await expect(
+ updateIssueBySlug({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } })
+ ).resolves.toEqual({ ok: true, bodyImageUrls: undefined })
+ })
+
+ it('keeps an accepted PR body save successful without an optional representation', async () => {
+ runRestMock.mockResolvedValueOnce({ ok: true, data: null })
+ await expect(
+ updatePullRequestBySlug({
+ owner: 'acme',
+ repo: 'widgets',
+ number: 12,
+ updates: {
+ body: ''
+ }
+ })
+ ).resolves.toEqual({ ok: true, bodyImageUrls: undefined })
+ })
+
+ it.each([null, true])(
+ 'finishes a Project compound save with unusable optional HTML (%s)',
+ async (html) => {
+ const body =
+ ''
+ runRestMock.mockResolvedValueOnce({
+ ok: true,
+ data: html === null ? null : { body, body_html: html }
+ })
+ await expect(
+ updateIssueBySlug({
+ owner: 'acme',
+ repo: 'widgets',
+ number: 12,
+ updates: { body, addLabels: ['saved-label'] }
+ })
+ ).resolves.toEqual({ ok: true, bodyImageUrls: undefined })
+ expect(runRestMock).toHaveBeenCalledWith(
+ [
+ '-X',
+ 'POST',
+ 'repos/acme/widgets/issues/12/labels',
+ '--raw-field',
+ 'labels[]=saved-label'
+ ],
+ undefined,
+ 'core',
+ { host: 'github.com' }
+ )
+ }
+ )
+})
diff --git a/src/main/github/project-view/issue-comment-mutations.ts b/src/main/github/project-view/issue-comment-mutations.ts
index fa16455e66d..61dd68d32b9 100644
--- a/src/main/github/project-view/issue-comment-mutations.ts
+++ b/src/main/github/project-view/issue-comment-mutations.ts
@@ -1,3 +1,4 @@
+import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls'
import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals'
import type { PRComment } from '../../../shared/github/comment-types'
import type {
@@ -14,6 +15,7 @@ type RawIssueCommentResponse = {
id?: number
user?: { login?: string; avatar_url?: string; type?: string } | null
body?: string
+ body_html?: string | null
created_at?: string
html_url?: string
}
@@ -24,6 +26,7 @@ function mapIssueComment(data: RawIssueCommentResponse, fallbackBody: string): P
author: data.user?.login ?? 'You',
authorAvatarUrl: data.user?.avatar_url ?? '',
body: data.body ?? fallbackBody,
+ bodyImageUrls: githubBodyImageUrls(data.body ?? fallbackBody, data.body_html),
createdAt: data.created_at ?? new Date().toISOString(),
url: data.html_url ?? '',
isBot: data.user?.type === 'Bot'
@@ -55,6 +58,7 @@ export async function addIssueCommentBySlug(
[
'-X',
'POST',
+ ...githubBodyMediaHeaders(args.body),
`repos/${args.owner}/${args.repo}/issues/${args.number}/comments`,
'--raw-field',
`body=${args.body}`
diff --git a/src/main/github/project-view/mutations.ts b/src/main/github/project-view/mutations.ts
index 7388f7a3f99..4c31ac3a522 100644
--- a/src/main/github/project-view/mutations.ts
+++ b/src/main/github/project-view/mutations.ts
@@ -1,3 +1,4 @@
+import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls'
import {
acquire,
assertPositiveInt,
@@ -46,15 +47,16 @@ export async function updateIssueBySlug(
return stateResult
}
const { title, body } = args.updates
+ let bodyImageUrls: Record