diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 23daba961e0..673eb8847e7 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -32,6 +32,7 @@ const BUNDLED_MAIN_DEPENDENCIES = new Set([ 'unified', 'remark-parse', 'remark-gfm', + 'hast-util-from-html-isomorphic', // Windows NSIS copies app.asar before external resources; bootstrap must not race resources/node_modules. 'zod' ]) diff --git a/src/main/github/body-image-read-adapters.test.ts b/src/main/github/body-image-read-adapters.test.ts new file mode 100644 index 00000000000..8dcd75701bc --- /dev/null +++ b/src/main/github/body-image-read-adapters.test.ts @@ -0,0 +1,154 @@ +import { beforeEach, expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ exec: vi.fn(), graphql: vi.fn() })) +vi.mock('./gh-utils', () => ({ + ghExecFileAsync: mocks.exec, + ghRepoExecOptions: () => ({}), + githubRepoContext: () => ({}) +})) +vi.mock('./rate-limit', () => ({ + repositoryRateLimitGuard: () => ({ blocked: false }), + noteRepositoryRateLimitSpend: () => {} +})) +vi.mock('./project-view/internals', () => ({ + assertPositiveInt: () => ({ ok: true }), + validateSlugArgs: () => ({ ok: true }), + projectGhExecOptions: () => ({}), + runGraphql: mocks.graphql +})) +import { getPRMetadata } from './pull-request-file-data' +import { getWorkItemDetailsBySlug } from './project-view/work-item-details' + +const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' +const html = + '' +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() + return { + ...actual, + fromHtmlIsomorphic: (...args: Parameters) => { + if (traversal.fail) { + throw new Error('Optional image HTML could not be parsed') + } + const tree = actual.fromHtmlIsomorphic(...args) + if (!traversal.enabled) { + return tree + } + traversal.parses++ + const pending: (Root | RootContent)[] = [tree] + while (pending.length) { + const node = pending.pop()! + if (!('children' in node)) { + continue + } + const children = node.children + pending.push(...children) + Object.defineProperty(node, 'children', { + get: () => { + traversal.children++ + return children + } + }) + } + return tree + } + } +}) +import { githubBodyImageUrls } from './body-image-urls' + +const original = 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488' +const signed = + 'https://private-user-images.githubusercontent.com/1/2-ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST&download=1' + +describe('GitHub body image sources', () => { + it.each([ + { body: `![shot](${original})`, html: true }, + { body: true, html: `` } + ])('ignores unusable optional representations ($body, $html)', ({ body, html }) => { + expect(githubBodyImageUrls(body, html)).toBeUndefined() + }) + + it('skips HTML parsing when the Markdown has no attachment candidates', () => { + traversal.enabled = true + traversal.parses = 0 + try { + expect(githubBodyImageUrls('A plain comment', ``)).toBeUndefined() + expect(traversal.parses).toBe(0) + } finally { + traversal.enabled = false + } + }) + + it('leaves the optional map absent if HTML extraction fails', () => { + traversal.fail = true + try { + expect(githubBodyImageUrls(`![shot](${original})`, ``)).toBeUndefined() + } finally { + traversal.fail = false + } + }) + + it('matches rendered images to canonical assets without changing editable Markdown', () => { + const body = `![shot](${original})\n\n![missing](https://github.com/user-attachments/assets/cc11040a-fb66-4289-927f-547b16dfc488)\n\`https://github.com/user-attachments/assets/dd11040a-fb66-4289-927f-547b16dfc488\`` + const html = `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(`![public](${original})`, ``)).toBeUndefined() + expect( + githubBodyImageUrls( + body, + '' + ) + ).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) => `![shot](https://github.com/user-attachments/assets/${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, key: unknown) { + if (typeof key === 'string' && key.startsWith('ce11040a-')) { + lookups++ + } + return originalGet.call(this, key) + } + try { + const result = githubBodyImageUrls(body, html) + expect(Object.keys(result ?? {})).toHaveLength(n) + // Each candidate and original is checked once, then each original gets one indexed lookup. + expect(pathname.mock.calls.length).toBeLessThanOrEqual(3 * n) + expect(lookups).toBe(n) + expect(traversal.parses).toBe(1) + expect(traversal.children).toBeLessThanOrEqual(n + 1) + expect( + result?.[ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-000000000000' + ] + ).toBe( + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-000000000000.png?jwt=TEST' + ) + } finally { + traversal.enabled = false + Map.prototype.get = originalGet + pathname.mockRestore() + } + } + }) +}) diff --git a/src/main/github/body-image-urls.ts b/src/main/github/body-image-urls.ts new file mode 100644 index 00000000000..c81f9a7952e --- /dev/null +++ b/src/main/github/body-image-urls.ts @@ -0,0 +1,144 @@ +import { fromHtmlIsomorphic } from 'hast-util-from-html-isomorphic' +import type { Root, RootContent } from 'hast' + +const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' +const githubBodyAssetPath = new RegExp(`/assets/(?:\\d+/)?(${UUID})$`, 'i') + +export function githubBodyImageCandidates(body: string): Map { + const originals = new Map() + for (const match of body.matchAll(/https:\/\/[^\s<>"'`()[\]]+/g)) { + if (!match[0].includes('/assets/')) { + continue + } + try { + const url = new URL(match[0]) + if (githubBodyAssetPath.test(url.pathname)) { + originals.set(match[0], url) + } + } catch { + // An invalid Markdown URL cannot identify an attachment. + } + } + return originals +} + +const imageId = new RegExp(UUID, 'i') +export const GITHUB_BODY_MEDIA_TYPE = 'Accept: application/vnd.github.full+json' + +type GitHubBodyHtmlObject = Record + +function isGitHubBodyHtmlObject(value: unknown): value is GitHubBodyHtmlObject { + return value !== null && typeof value === 'object' +} + +export function removeFailedGitHubBodyHtml( + data: unknown, + errors: T[] | undefined +): T[] | undefined { + const isIndex = (value: unknown): boolean => + typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 + return errors?.filter((error) => { + if (!error || typeof error !== 'object' || !('path' in error)) { + return true + } + const path = error.path + if ( + !Array.isArray(path) || + path[0] !== 'repository' || + (path[1] !== 'issue' && path[1] !== 'pullRequest') || + path.at(-1) !== 'bodyHTML' + ) { + return true + } + const owned = + path.length === 3 || + (path.length === 6 && + (path[2] === 'comments' || (path[1] === 'pullRequest' && path[2] === 'reviews')) && + path[3] === 'nodes' && + isIndex(path[4])) || + (path.length === 9 && + path[1] === 'pullRequest' && + path[2] === 'reviewThreads' && + path[3] === 'nodes' && + isIndex(path[4]) && + path[5] === 'comments' && + path[6] === 'nodes' && + isIndex(path[7])) + if (!owned) { + return true + } + let target = data + for (const part of path.slice(0, -1)) { + if (!isGitHubBodyHtmlObject(target) || (typeof part === 'number' && !Array.isArray(target))) { + return true + } + target = target[part] + } + if (!isGitHubBodyHtmlObject(target) || typeof target.body !== 'string') { + return true + } + delete target.bodyHTML + return false + }) +} + +export function githubBodyMediaHeaders(body: string): string[] { + return githubBodyImageCandidates(body).size ? ['-H', GITHUB_BODY_MEDIA_TYPE] : [] +} + +/** Keep short-lived display URLs separate from editable Markdown and persisted item metadata. */ +export function githubBodyImageUrls( + body: unknown, + html: unknown +): Record | undefined { + if (typeof body !== 'string' || typeof html !== 'string' || !html) { + return undefined + } + try { + const originals = githubBodyImageCandidates(body) + if (!originals.size) { + return undefined + } + + const signed = new Map() + const pending: (Root | RootContent)[] = [fromHtmlIsomorphic(html, { fragment: true })] + while (pending.length) { + const node = pending.pop()! + if ('children' in node) { + pending.push(...node.children) + } + if (node.type !== 'element' || node.tagName !== 'img') { + continue + } + const src = node.properties.src + if (typeof src !== 'string') { + continue + } + try { + const url = new URL(src) + const id = url.pathname.match(imageId)?.[0].toLowerCase() + if (id && url.protocol === 'https:') { + signed.set(id, url) + } + } catch { + // Relative or malformed HTML sources do not supply a signed attachment URL. + } + } + + const result: Record = {} + for (const [original, url] of originals) { + const id = url.pathname.match(githubBodyAssetPath)![1].toLowerCase() + const display = signed.get(id) + if ( + display && + display.href !== original && + (display.hostname.endsWith('.githubusercontent.com') || display.host === url.host) + ) { + result[original] = display.href + } + } + return Object.keys(result).length ? result : undefined + } catch { + return undefined + } +} diff --git a/src/main/github/client-pr-conversation-requests.test.ts b/src/main/github/client-pr-conversation-requests.test.ts index 65a657cc6e5..84d729a97ec 100644 --- a/src/main/github/client-pr-conversation-requests.test.ts +++ b/src/main/github/client-pr-conversation-requests.test.ts @@ -98,6 +98,8 @@ describe('PR conversation request reuse', () => { expect(comments.map((c) => c.body)).toEqual(['Conversation', 'Review summary']) expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual([ 'api', + '-H', + 'Accept: application/vnd.github.full+json', 'repos/acme/widgets/pulls/7/reviews?per_page=100' ]) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) @@ -159,4 +161,144 @@ describe('PR conversation request reuse', () => { ['me', true] ]) }) + it.each([0, 100, 1000])( + 'gets image maps in the existing conversation request (%s bodies)', + async (n) => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const imageComments = Array.from({ length: n }, (_, i) => ({ + ...comment, + id: `IMAGE_${i}`, + databaseId: i, + body, + bodyHTML: + '', + 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((resolve) => { + started = resolve + }) + ghExecFileAsyncMock.mockImplementationOnce(() => { + started() + return pending + }) + const read = getPRComments('/repo', 7, { ...options, noCache: true }) + await commandStarted + expect(clientMocks.acquireMock).toHaveBeenCalledTimes(1) + expect(clientMocks.releaseMock).not.toHaveBeenCalled() + const raw = response({ + comments: { nodes: [comment] }, + reviews: { nodes: [] }, + reviewThreads: { nodes: [] } + }) + if (reject) { + fail(Object.assign(new Error('Partial GraphQL response'), raw)) + } else { + settle(raw) + } + const result = await read + expect(result).toMatchObject([{ body: 'Conversation' }]) + expect(clientMocks.releaseMock).toHaveBeenCalledTimes(1) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(result[0].bodyImageUrls).toBeUndefined() + } + ) + + it('keeps usable raw fields and siblings when optional HTML errors, without a fallback request', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + 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( function mapGraphQLComment( comment: z.infer & { databaseId: number } ): PRComment { - return { + const mapped: PRComment = { id: comment.databaseId, author: comment.author?.login ?? 'ghost', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body ?? '', + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: comment.submittedAt ?? comment.createdAt, url: comment.url, isBot: comment.author?.__typename === 'Bot', @@ -94,6 +97,7 @@ function mapGraphQLComment( reactionSubjectId: comment.id, reactions: mapGraphQLReactionGroups(comment.reactionGroups) } + return mapped } const reviewMarkdown = unified().use(remarkParse) @@ -123,10 +127,11 @@ export function parsePRConversationResponse(stdout: string): { reviewComments: PRComment[] } { const envelope = envelopeSchema.parse(JSON.parse(stdout)) + const errors = removeFailedGitHubBodyHtml(envelope.data, envelope.errors) const pr = envelope.data?.repository?.pullRequest const failed = (source: string): boolean => Boolean( - envelope.errors?.some( + errors?.some( (error) => !error.path?.length || !error.path.includes('pullRequest') || error.path[2] === source ) @@ -149,19 +154,20 @@ export function parsePRConversationResponse(stdout: string): { reviewComments: threads.success ? threads.data.nodes.flatMap((thread) => thread - ? thread.comments.nodes.filter(hasDatabaseId).map((c) => ({ - ...mapGraphQLComment(c), - // Left-side threads count old-file lines, which the shared tail numbering cannot place. - ...(c === thread.comments.nodes[0] && thread.diffSide !== 'LEFT' - ? rootDiffHunk(thread.rootHunk) - : {}), - path: c.path, - threadId: thread.id, - isResolved: thread.isResolved, - isOutdated: thread.line == null, - line: thread.line ?? thread.originalLine ?? undefined, - startLine: thread.startLine ?? thread.originalStartLine ?? undefined - })) + ? thread.comments.nodes.filter(hasDatabaseId).map((c) => + Object.assign(mapGraphQLComment(c), { + // Left-side threads count old-file lines, which the shared tail numbering cannot place. + ...(c === thread.comments.nodes[0] && thread.diffSide !== 'LEFT' + ? rootDiffHunk(thread.rootHunk) + : {}), + path: c.path, + threadId: thread.id, + isResolved: thread.isResolved, + isOutdated: thread.line == null, + line: thread.line ?? thread.originalLine ?? undefined, + startLine: thread.startLine ?? thread.originalStartLine ?? undefined + }) + ) : [] ) : [] @@ -181,6 +187,7 @@ const restCommentSchema = z.object({ .object({ login: z.string(), avatar_url: z.string(), type: z.string().optional() }) .nullable(), body: z.string().nullish(), + body_html: z.unknown().optional(), created_at: z.string().optional(), submitted_at: z.string().nullish(), html_url: z.string() @@ -200,6 +207,7 @@ export function parseRestPRComments( author: c.user?.login ?? 'ghost', authorAvatarUrl: c.user?.avatar_url ?? '', body: c.body ?? '', + bodyImageUrls: githubBodyImageUrls(c.body, c.body_html), createdAt: (reviews ? c.submitted_at : c.created_at) ?? '', url: c.html_url, isBot: c.user?.type === 'Bot', diff --git a/src/main/github/client/fetch/pr-review-threads-query.ts b/src/main/github/client/fetch/pr-review-threads-query.ts index d2ba6450133..0e608c43974 100644 --- a/src/main/github/client/fetch/pr-review-threads-query.ts +++ b/src/main/github/client/fetch/pr-review-threads-query.ts @@ -23,6 +23,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt url viewerDidAuthor @@ -44,6 +45,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt url viewerDidAuthor @@ -62,6 +64,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt submittedAt url diff --git a/src/main/github/client/map/review-comment-response.ts b/src/main/github/client/map/review-comment-response.ts index f13a69f3632..f17f653ba0e 100644 --- a/src/main/github/client/map/review-comment-response.ts +++ b/src/main/github/client/map/review-comment-response.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls } from '../../body-image-urls' import type { PRComment } from '../../../../shared/github/comment-types' export function mapReviewCommentResponse( data: { @@ -5,6 +6,7 @@ export function mapReviewCommentResponse( 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 path?: string @@ -22,6 +24,7 @@ export function mapReviewCommentResponse( 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-comment-image.test.ts b/src/main/github/issue-comment-image.test.ts new file mode 100644 index 00000000000..c22f437bd88 --- /dev/null +++ b/src/main/github/issue-comment-image.test.ts @@ -0,0 +1,74 @@ +import { expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ exec: vi.fn() })) +vi.mock('./gh-utils', () => ({ + ghExecFileAsync: mocks.exec, + acquire: async () => {}, + release: () => {}, + classifyGhError: () => ({ type: 'unknown' }) +})) +vi.mock('./github-api-repository', () => ({ + resolveGitHubRepoExecution: async () => ({ + ownerRepo: { owner: 'acme', repo: 'widgets' }, + ghOptions: {} + }) +})) +import { addIssueComment } from './issue-comment' +import { addPRReviewComment, addPRReviewCommentReply } from './client/create/add-pr-review-comment' + +it('returns signed display sources immediately after posting the original Markdown', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + mocks.exec.mockResolvedValue({ + stdout: JSON.stringify({ + id: 1, + user: null, + body, + body_html: + '' + }) + }) + 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 = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + 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=![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + ) + } +) 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 | null)[] | null } participants?: { nodes?: GitHubAssignableUser[] } comments?: { pageInfo?: { hasNextPage: boolean } - nodes?: { + nodes?: ({ databaseId?: number | null body?: string | null + bodyHTML?: unknown createdAt?: string | null url?: string | null viewerDidAuthor?: boolean | null @@ -77,10 +81,10 @@ export type GraphQLIssueDetailsResponse = { avatarUrl?: string | null __typename?: string } | null - }[] + } | null)[] } } | null } | null } - errors?: { message?: string }[] + errors?: { message?: string; path?: unknown }[] } diff --git a/src/main/github/issue-update.ts b/src/main/github/issue-update.ts index fa72852bde7..4a5fbe0bb63 100644 --- a/src/main/github/issue-update.ts +++ b/src/main/github/issue-update.ts @@ -9,6 +9,7 @@ import { import { acquire, classifyGhError, ghExecFileAsync, release } from './gh-utils' import { codeHostFailure, combinedClassifiedFailure } from '../../shared/code-host-failure-copy' import type { ClassifiedError } from '../../shared/classified-error' +import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls' export async function updateIssue( repoPath: string, @@ -18,7 +19,7 @@ export async function updateIssue( localGitOptions: LocalGitExecOptions = {}, preference?: IssueSourcePreference, ownerRepoOverride?: GitHubApiRepository | null -): Promise<{ ok: true } | { ok: false; error: string }> { +): Promise<{ ok: true; bodyImageUrls?: Record } | { ok: false; error: string }> { const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, ownerRepoOverride ?? @@ -40,6 +41,7 @@ export async function updateIssue( const repo = `${ownerRepo.owner}/${ownerRepo.repo}` const errors: ClassifiedError[] = [] + let bodyImageUrls: Record | undefined if (updates.state) { await acquire() @@ -69,17 +71,26 @@ export async function updateIssue( if (updates.body !== undefined) { await acquire() try { - await ghExecFileAsync( + 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)) @@ -127,5 +138,5 @@ export async function updateIssue( if (errors.length > 0) { return combinedClassifiedFailure(errors) } - return { ok: true } + return { ok: true, bodyImageUrls } } diff --git a/src/main/github/issue-work-item-details-fresh.test.ts b/src/main/github/issue-work-item-details-fresh.test.ts index 9bdecc5b75b..8d735c87693 100644 --- a/src/main/github/issue-work-item-details-fresh.test.ts +++ b/src/main/github/issue-work-item-details-fresh.test.ts @@ -127,3 +127,104 @@ describe('explicit task refresh conversation reads', () => { 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 = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + 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 = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + 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 comments: PRComment[] assignees: string[] assigneeUsers: GitHubAssignableUser[] @@ -47,25 +54,33 @@ export async function getIssueDetailsViaGraphQL( } try { noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions) - const { 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 - ) - const parsed = JSON.parse(stdout) as GraphQLIssueDetailsResponse - if (parsed.errors && parsed.errors.length > 0) { + 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 @@ -85,12 +100,15 @@ export async function getIssueDetailsViaGraphQL( return null } const comments: PRComment[] = (issue.comments?.nodes ?? []) - .filter((comment) => typeof comment.databaseId === 'number') + .filter( + (comment): comment is NonNullable => 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', @@ -112,7 +130,7 @@ export async function getIssueDetailsViaGraphQL( name: user.name ?? null, avatarUrl: user.avatarUrl ?? '' })) - return { + const details: CollapsedIssueDetails = { ...(itemData?.success ? { item: mapIssueWorkItem({ @@ -125,12 +143,14 @@ export async function getIssueDetailsViaGraphQL( } : {}), 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 } @@ -143,7 +163,9 @@ export async function getIssueBodyAndComments( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {}, fresh = false -): Promise> { +): Promise< + Pick +> { const ghOptions = { ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), ...githubHostExecOptions(repository) @@ -161,7 +183,8 @@ export async function getIssueBodyAndComments( ghExecFileAsync( [ 'api', - ...(fresh ? [] : ['--cache', '60s']), + '-H', + GITHUB_BODY_MEDIA_TYPE, `repos/${repository.owner}/${repository.repo}/issues/${issueNumber}` ], ghOptions @@ -169,7 +192,8 @@ export async function getIssueBodyAndComments( ghExecFileAsync( [ 'api', - ...(fresh ? [] : ['--cache', '60s']), + '-H', + GITHUB_BODY_MEDIA_TYPE, ...(fresh ? ['--paginate', '--slurp'] : []), `repos/${repository.owner}/${repository.repo}/issues/${issueNumber}/comments?per_page=100` ], @@ -178,14 +202,16 @@ export async function getIssueBodyAndComments( getIssueTimelineItems(repository, issueNumber, ghOptions, fresh), readViewerLogin(ghOptions) ]) - const issue = JSON.parse(issueResult.stdout) as { + 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 } @@ -199,17 +225,20 @@ export async function getIssueBodyAndComments( 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) })) - return { + 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. diff --git a/src/main/github/issues.test.ts b/src/main/github/issues.test.ts index 55862e1f0a1..3beaf260cd7 100644 --- a/src/main/github/issues.test.ts +++ b/src/main/github/issues.test.ts @@ -216,6 +216,56 @@ describe('issue source operations', () => { ) }) + it('keeps the accepted issue body representation through a compound metadata edit', async () => { + const body = + '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + body, + body_html: + '' + }) + }) + .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 ![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)', + 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: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + }) + ).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 = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + 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 = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + 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 = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + 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: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + } + }) + ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) + }) + + it.each([null, true])( + 'finishes a Project compound save with unusable optional HTML (%s)', + async (html) => { + const body = + '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + 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 | undefined if (title !== undefined || body !== undefined) { const patchArgs = ['-X', 'PATCH', base] if (title !== undefined) { patchArgs.push('--raw-field', `title=${title}`) } if (body !== undefined) { - patchArgs.push('--raw-field', `body=${body}`) + patchArgs.push(...githubBodyMediaHeaders(body), '--raw-field', `body=${body}`) } - const result = await runRest( + const result = await runRest<{ body?: string; body_html?: string }>( patchArgs, undefined, 'core', @@ -63,12 +65,20 @@ export async function updateIssueBySlug( if (!result.ok) { return { ok: false, error: result.error } } + try { + if (body !== undefined && result.data?.body === body) { + bodyImageUrls = githubBodyImageUrls(body, result.data.body_html) + } + } catch { + // Optional display data cannot turn an accepted edit into a failed write. + } } const labelResult = await updateIssueLabels(args, base) if (!labelResult.ok) { return labelResult } - return updateIssueAssignees(args, base) + const assigneeResult = await updateIssueAssignees(args, base) + return assigneeResult.ok ? { ok: true, bodyImageUrls } : assigneeResult } function validateDuplicateUpdate(args: UpdateIssueBySlugArgs): GitHubProjectMutationResult | null { diff --git a/src/main/github/project-view/pull-request-mutation.ts b/src/main/github/project-view/pull-request-mutation.ts index 7a49d9cbf0e..def6756c126 100644 --- a/src/main/github/project-view/pull-request-mutation.ts +++ b/src/main/github/project-view/pull-request-mutation.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals' import type { GitHubProjectMutationResult } from '../../../shared/github/project-result-types' import type { UpdatePullRequestBySlugArgs } from '../../../shared/github/project-request-types' @@ -30,7 +31,11 @@ export async function updatePullRequestBySlug( fieldCount++ } if (args.updates.body !== undefined) { - patchArgs.push('--raw-field', `body=${args.updates.body}`) + patchArgs.push( + ...githubBodyMediaHeaders(args.updates.body), + '--raw-field', + `body=${args.updates.body}` + ) fieldCount++ } if (args.updates.state !== undefined) { @@ -40,11 +45,19 @@ export async function updatePullRequestBySlug( if (fieldCount === 0) { return { ok: true } } - const result = await runRest( + const result = await runRest<{ body?: string; body_html?: string }>( patchArgs, undefined, 'core', projectGhExecOptions(args.host) ) - return result.ok ? { ok: true } : { ok: false, error: result.error } + return result.ok + ? { + ok: true, + bodyImageUrls: + args.updates.body !== undefined + ? githubBodyImageUrls(result.data?.body ?? args.updates.body, result.data?.body_html) + : undefined + } + : { ok: false, error: result.error } } diff --git a/src/main/github/project-view/work-item-details.ts b/src/main/github/project-view/work-item-details.ts index e09a8a038cb..6323f722a13 100644 --- a/src/main/github/project-view/work-item-details.ts +++ b/src/main/github/project-view/work-item-details.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runGraphql, validateSlugArgs } from './internals' import type { PRComment } from '../../../shared/github/comment-types' import type { GitHubAssignableUser } from '../../../shared/github/pull-request-types' @@ -11,6 +12,7 @@ type RawComment = { databaseId?: number author?: { login?: string; avatarUrl?: string; __typename?: string } | null body?: string + bodyHTML?: unknown createdAt?: string url?: string } @@ -24,6 +26,7 @@ type RawWorkItemContent = { isDraft?: boolean updatedAt?: string body?: string + bodyHTML?: unknown headRefName?: string baseRefName?: string author?: { login?: string } | null @@ -33,6 +36,13 @@ type RawWorkItemContent = { comments?: { nodes?: (RawComment | null)[] } } +type RawWorkItemDetailsResponse = { + repository?: { + issue?: RawWorkItemContent | null + pullRequest?: RawWorkItemContent | null + } | null +} + export async function getWorkItemDetailsBySlug( args: ProjectWorkItemDetailsBySlugArgs ): Promise { @@ -51,49 +61,63 @@ export async function getWorkItemDetailsBySlug( } } const contentFragment = args.type === 'issue' ? ISSUE_FRAGMENT : PULL_REQUEST_FRAGMENT - const result = await runGraphql<{ - repository?: { - issue?: RawWorkItemContent | null - pullRequest?: RawWorkItemContent | null - } | null - }>( + const result = await runGraphql( `query($owner:String!, $repo:String!, $num:Int!) { repository(owner:$owner, name:$repo) { ${contentFragment} } }`, { owner: args.owner, repo: args.repo, num: args.number }, projectGhExecOptions(args.host) ) - if (!result.ok) { + let data: RawWorkItemDetailsResponse | undefined + if (result.ok) { + data = result.data + } else { + try { + const response: { data?: RawWorkItemDetailsResponse; errors?: unknown[] } = JSON.parse( + result.raw.stdout + ) + if ( + !response.errors?.length || + removeFailedGitHubBodyHtml(response.data, response.errors)?.length + ) { + return { ok: false, error: result.error } + } + data = response.data + } catch { + return { ok: false, error: result.error } + } + } + const raw = args.type === 'issue' ? data?.repository?.issue : data?.repository?.pullRequest + if (!result.ok && typeof raw?.body !== 'string') { return { ok: false, error: result.error } } - const raw = - args.type === 'issue' ? result.data.repository?.issue : result.data.repository?.pullRequest if (!raw) { return { ok: false, error: { type: 'not_found', message: 'Item not found.', reason: 'item_not_found' } } } - return { ok: true, details: mapWorkItemDetails(raw, args) } + const details = mapWorkItemDetails(raw, args) + return { ok: true, details } } const ISSUE_FRAGMENT = `issue(number:$num) { - id number title url state stateReason updatedAt body author { login } + id number title url state stateReason updatedAt body bodyHTML author { login } labels(first:50) { nodes { name } } assignees(first:50) { nodes { login } } participants(first:50) { nodes { login name avatarUrl } } comments(first:100) { - nodes { databaseId author { login avatarUrl __typename } body createdAt url } + nodes { databaseId author { login avatarUrl __typename } body bodyHTML createdAt url } } }` const PULL_REQUEST_FRAGMENT = `pullRequest(number:$num) { - id number title url state isDraft updatedAt headRefName baseRefName body author { login } + id number title url state isDraft updatedAt headRefName baseRefName body bodyHTML author { login } labels(first:50) { nodes { name } } assignees(first:50) { nodes { login } } participants(first:50) { nodes { login name avatarUrl } } comments(first:100) { - nodes { databaseId author { login avatarUrl __typename } body createdAt url } + nodes { databaseId author { login avatarUrl __typename } body bodyHTML createdAt url } } }` @@ -117,6 +141,7 @@ function mapWorkItemDetails( author: comment.author?.login ?? '', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body, + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: typeof comment.createdAt === 'string' ? comment.createdAt : '', url: typeof comment.url === 'string' ? comment.url : '', isBot: comment.author?.__typename === 'Bot' @@ -161,6 +186,7 @@ function mapWorkItemDetails( args.type === 'pr' && typeof raw.baseRefName === 'string' ? raw.baseRefName : undefined }, body: typeof raw.body === 'string' ? raw.body : '', + bodyImageUrls: githubBodyImageUrls(raw.body, raw.bodyHTML), comments, participants, assignees diff --git a/src/main/github/pull-request-file-data.ts b/src/main/github/pull-request-file-data.ts index d6c42f0b392..e4406581f91 100644 --- a/src/main/github/pull-request-file-data.ts +++ b/src/main/github/pull-request-file-data.ts @@ -1,3 +1,4 @@ +import { GITHUB_BODY_MEDIA_TYPE, githubBodyImageUrls } from './body-image-urls' import type { GitHubPRFile } from '../../shared/github/pull-request-types' import type { PRFileViewedStatesResult } from './pull-request-detail-context' import { ghExecFileAsync, ghRepoExecOptions, githubRepoContext } from './gh-utils' @@ -49,7 +50,12 @@ export async function getPRMetadata( repository: GitHubApiRepository | null, connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} -): Promise<{ body: string; headSha?: string; baseSha?: string }> { +): Promise<{ + body: string + bodyImageUrls?: Record + headSha?: string + baseSha?: string +}> { if (!repository) { return { body: '' } } @@ -63,19 +69,27 @@ export async function getPRMetadata( try { noteRepositoryRateLimitSpend(repository, 'core', 1, ghOptions) const { stdout } = await ghExecFileAsync( - ['api', '--cache', '60s', `repos/${repository.owner}/${repository.repo}/pulls/${prNumber}`], + [ + 'api', + '-H', + GITHUB_BODY_MEDIA_TYPE, + `repos/${repository.owner}/${repository.repo}/pulls/${prNumber}` + ], ghOptions ) - const data = JSON.parse(stdout) as { + const data: { body?: string | null + body_html?: unknown head?: { sha?: string } base?: { sha?: string } - } - return { + } = JSON.parse(stdout) + const metadata = { body: data.body ?? '', + bodyImageUrls: githubBodyImageUrls(data.body, data.body_html), ...(data.head?.sha ? { headSha: data.head.sha } : {}), ...(data.base?.sha ? { baseSha: data.base.sha } : {}) } + return metadata } catch { return { body: '' } } diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 4c94c58a912..3db15194c9e 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -156,29 +156,31 @@ export async function getWorkItemDetails( ...collapsed.assigneeUsers ]), body: collapsed.body, + bodyImageUrls: collapsed.bodyImageUrls, comments: collapsed.comments, assignees: item.assignees?.map((user) => user.login) ?? collapsed.assignees, participants: collapsed.participants, timelineItems: collapsed.timelineItems } } - const [{ body, comments, assignees, timelineItems }, participants] = await Promise.all([ - getIssueBodyAndComments( - repoPath, - item.number, - resolvedRepository, - connectionId, - localGitOptions, - canonical - ), - getWorkItemParticipants( - repoPath, - item, - resolvedRepository, - connectionId, - localGitOptions - ) - ]) + const [{ body, bodyImageUrls, comments, assignees, timelineItems }, participants] = + await Promise.all([ + getIssueBodyAndComments( + repoPath, + item.number, + resolvedRepository, + connectionId, + localGitOptions, + canonical + ), + getWorkItemParticipants( + repoPath, + item, + resolvedRepository, + connectionId, + localGitOptions + ) + ]) const mentionParticipants = await getMentionParticipants( repoPath, item, @@ -191,6 +193,7 @@ export async function getWorkItemDetails( return { item: enrichItemDisplayAvatars(item, mentionParticipants), body, + bodyImageUrls, comments, assignees: item.assignees?.map((user) => user.login) ?? assignees, participants: mentionParticipants, @@ -256,6 +259,7 @@ export async function getWorkItemDetails( mentionParticipants ), body: metadata.body, + bodyImageUrls: metadata.bodyImageUrls, comments, headSha: metadata.headSha, baseSha: metadata.baseSha, diff --git a/src/preload/api/gh-bridge-mutations-and-projects.ts b/src/preload/api/gh-bridge-mutations-and-projects.ts index f687a91f02d..a057485be6d 100644 --- a/src/preload/api/gh-bridge-mutations-and-projects.ts +++ b/src/preload/api/gh-bridge-mutations-and-projects.ts @@ -94,8 +94,9 @@ export const ghMutationsAndProjectsApi = { sourceContext?: TaskSourceContext | null number: number updates: unknown - }): Promise<{ ok: true } | { ok: false; error: string }> => - ipcRenderer.invoke('gh:updateIssue', args), + }): Promise< + { ok: true; bodyImageUrls?: Record } | { ok: false; error: string } + > => ipcRenderer.invoke('gh:updateIssue', args), addIssueComment: (args: { repoPath: string repoId?: string | null diff --git a/src/preload/api/github-work-item-api.ts b/src/preload/api/github-work-item-api.ts index 52c6a93314f..f4ce0fc4d66 100644 --- a/src/preload/api/github-work-item-api.ts +++ b/src/preload/api/github-work-item-api.ts @@ -120,7 +120,7 @@ export type GithubWorkItemApi = { updates: GitHubIssueUpdate ownerRepo?: GitHubOwnerRepo } - ) => Promise<{ ok: true } | { ok: false; error: string }> + ) => Promise<{ ok: true; bodyImageUrls?: Record } | { ok: false; error: string }> addIssueComment: ( args: GitHubRepoSelectorArgs & { number: number diff --git a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx b/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx index f7afff82f5b..eedfbceef48 100644 --- a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx +++ b/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx @@ -148,6 +148,7 @@ export function renderCommentCard( /> resolvedBodyDraft: string markdownGitHubRepo: GitHubOwnerRepo | null setBodyDraft: (value: string) => void @@ -136,6 +138,7 @@ export function ConversationTabDescription({ ) : body.trim() ? ( ({ update: vi.fn().mockResolvedValue(undefined) })) +vi.mock('@/components/github/github-work-item-edit-mutations', () => ({ + runWorkItemBodyUpdate: mocks.update +})) +vi.mock('@/store', () => ({ + useAppStore: { getState: () => ({ recordFeatureInteraction: () => {} }) } +})) +vi.mock('@/lib/pr-bot-author-overrides', () => ({ usePRBotAuthorOverrides: () => ({}) })) +vi.mock('./conversation-tab-activity', () => ({ ConversationTabActivity: () => null })) +vi.mock('./conversation-tab-pr-sidebar', () => ({ ConversationTabPRSidebar: () => null })) +vi.mock('./gh-comment-composer', () => ({ GHCommentComposer: () => null })) +vi.mock('@/components/github/GitHubMarkdownComposer', () => ({ + GitHubMarkdownComposer: ({ + value, + onChange + }: { + value: string + onChange: (value: string) => void + }) => ( +