Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(gitlab): submit review comments on context lines (#6348)
Tarasd94fbda34439
diff --git a/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts b/apps/server/src/pullRequest/BitbucketPullRequestApi.test.tsindex 4120cf55e..8945ecc5e 100644--- a/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts+++ b/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts@@ -776,7 +776,13 @@ layer("BitbucketPullRequestApi.layer", (it) => {number: 7,verdict: "request-changes",body: "Two things.",- comments: [{ path: "src/a.ts", line: 12, side: "left", body: "why remove?" }],+ comments: [+ {+ path: "src/a.ts",+ position: { kind: "deleted", oldLine: 12 },+ body: "why remove?",+ },+ ],});expect(callAt(0).url).toContain("/pullrequests/7/comments");diff --git a/apps/server/src/pullRequest/BitbucketPullRequestApi.ts b/apps/server/src/pullRequest/BitbucketPullRequestApi.tsindex a2c57bfc5..5b3149b0d 100644--- a/apps/server/src/pullRequest/BitbucketPullRequestApi.ts+++ b/apps/server/src/pullRequest/BitbucketPullRequestApi.ts@@ -12,6 +12,7 @@ import type {PullRequestMergeMethod,PullRequestMergeability,PullRequestReviewCommentDraft,+ PullRequestReviewPosition,PullRequestReviewThread,PullRequestReviewVerdict,PullRequestReviewerCandidateList,@@ -364,6 +365,19 @@ function mergeStrategy(method: PullRequestMergeMethod | undefined): string {}}+function bitbucketReviewPosition(+ position: PullRequestReviewPosition,+): { readonly from: number } | { readonly to: number } {+ switch (position.kind) {+ case "added":+ return { to: position.newLine };+ case "deleted":+ return { from: position.oldLine };+ case "context":+ return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };+ }+}+export const make = Effect.gen(function* () {const bitbucket = yield* BitbucketApi.BitbucketApi;@@ -794,7 +808,7 @@ export const make = Effect.gen(function* () {content: { raw: comment.body },inline: {path: comment.path,- ...(comment.side === "left" ? { from: comment.line } : { to: comment.line }),+ ...bitbucketReviewPosition(comment.position),},}),}),diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.test.tsindex 848c4cd5e..d1af03db9 100644--- a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts@@ -1624,7 +1624,7 @@ layer("GitHubPullRequestCli.layer", (it) => {number: 7,verdict: "approve",body: "Looks right.",- comments: [{ path: "src/a.ts", line: 4, side: "right", body: "nit" }],+ comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 4 }, body: "nit" }],});expect(callAt(0).args).toEqual([diff --git a/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts b/apps/server/src/pullRequest/GitLabPullRequestCli.test.tsindex c33e01c2d..014d91a02 100644--- a/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts+++ b/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts@@ -1018,7 +1018,12 @@ layer("GitLabPullRequestCli.layer", (it) => {verdict: "approve",body: "Looks right.",comments: [- { path: "src/b.ts", oldPath: "src/a.ts", line: 4, side: "left", body: "why remove?" },+ {+ path: "src/b.ts",+ oldPath: "src/a.ts",+ position: { kind: "deleted", oldLine: 4 },+ body: "why remove?",+ },],});@@ -1197,7 +1202,7 @@ layer("GitLabPullRequestCli.layer", (it) => {number: 7,verdict: "comment",body: "",- comments: [{ path: "src/a.ts", line: 4, side: "right", body: "nit" }],+ comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 4 }, body: "nit" }],}),);diff --git a/apps/server/src/pullRequest/GitLabPullRequestCli.ts b/apps/server/src/pullRequest/GitLabPullRequestCli.tsindex 17c23bf86..9f968dddb 100644--- a/apps/server/src/pullRequest/GitLabPullRequestCli.ts+++ b/apps/server/src/pullRequest/GitLabPullRequestCli.ts@@ -14,6 +14,7 @@ import type {PullRequestReaction,PullRequestReactionContent,PullRequestReviewCommentDraft,+ PullRequestReviewPosition,PullRequestReviewThread,PullRequestReviewVerdict,PullRequestReviewerCandidateList,@@ -400,6 +401,22 @@ function projectPath(repository: string): string {return encodeURIComponent(repository.trim());}+function gitLabReviewPositionLines(+ position: PullRequestReviewPosition,+):+ | { readonly new_line: number }+ | { readonly old_line: number }+ | { readonly old_line: number; readonly new_line: number } {+ switch (position.kind) {+ case "added":+ return { new_line: position.newLine };+ case "deleted":+ return { old_line: position.oldLine };+ case "context":+ return { old_line: position.oldLine, new_line: position.newLine };+ }+}+function stateParam(state: PullRequestListState): string {// GitLab's `closed` already excludes merged merge requests, so no extra filter is needed,// and it spans every state under `all`.@@ -1324,9 +1341,7 @@ export const make = Effect.gen(function* () {// draft carries the name the file had before the change.old_path: comment.oldPath ?? comment.path,new_path: comment.path,- ...(comment.side === "left"- ? { old_line: comment.line }- : { new_line: comment.line }),+ ...gitLabReviewPositionLines(comment.position),},}),}),diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 243cfe06c..456a5023b 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -1534,7 +1534,7 @@ it.effect("refuses line comments on a host that takes only a summary", () =>number: 1,verdict: "comment",body: "",- comments: [{ path: "src/a.ts", line: 1, side: "right", body: "nit" }],+ comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 1 }, body: "nit" }],}),);diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.tsindex a3c3524a6..946394dcd 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts@@ -1147,8 +1147,16 @@ describe("review submission payload", () => {verdict: "request-changes",body: "Two things.",comments: [- { path: "src/a.ts", line: 12, side: "right", body: "rename this" },- { path: "src/b.ts", line: 3, side: "left", body: "why remove?" },+ {+ path: "src/a.ts",+ position: { kind: "added", newLine: 12 },+ body: "rename this",+ },+ {+ path: "src/b.ts",+ position: { kind: "deleted", oldLine: 3 },+ body: "why remove?",+ },],}),) as Record<string, unknown>;diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.tsindex e113b87d8..7b9ff9d41 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts@@ -17,6 +17,7 @@ import type {PullRequestReactionContent,PullRequestReviewCommentDraft,PullRequestReviewDecision,+ PullRequestReviewPosition,PullRequestReviewThread,PullRequestReviewVerdict,PullRequestReviewerCandidate,@@ -933,6 +934,22 @@ export const REVIEW_DISMISSALS_GRAPHQL_QUERY = `query($owner: String!, $name: St}}`;+function gitHubReviewPosition(position: PullRequestReviewPosition): {+ readonly line: number;+ readonly side: "LEFT" | "RIGHT";+} {+ switch (position.kind) {+ case "added":+ return { line: position.newLine, side: "RIGHT" };+ case "deleted":+ return { line: position.oldLine, side: "LEFT" };+ case "context":+ return position.side === "left"+ ? { line: position.oldLine, side: "LEFT" }+ : { line: position.newLine, side: "RIGHT" };+ }+}+/** The whole review as one request body, which is how GitHub keeps it invisible until sent. */export function buildReviewSubmissionJson(input: {readonly verdict: PullRequestReviewVerdict;@@ -944,8 +961,7 @@ export function buildReviewSubmissionJson(input: {body: input.body,comments: input.comments.map((comment) => ({path: comment.path,- line: comment.line,- side: comment.side === "left" ? ("LEFT" as const) : ("RIGHT" as const),+ ...gitHubReviewPosition(comment.position),body: comment.body,})),});diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex 71f3ffc7f..776a4d671 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -6,6 +6,7 @@ import type {PullRequestDiffSide,PullRequestOmittedFileStat,PullRequestRef,+ PullRequestReviewPosition,PullRequestReviewThread,} from "@t3tools/contracts";import {@@ -43,7 +44,11 @@ import {} from "~/lib/diffRendering";import { cn } from "~/lib/utils";import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents";-import { buildDiffReviewComment, type ReviewCommentContext } from "~/reviewCommentContext";+import {+ buildDiffReviewComment,+ resolveDiffReviewPosition,+ type ReviewCommentContext,+} from "~/reviewCommentContext";import { pullRequestEnvironment } from "~/state/pullRequests";import { useEnvironmentQuery } from "~/state/query";import { useAtomCommand } from "~/state/use-atom-command";@@ -129,8 +134,7 @@ interface DraftAnchor {readonly path: string;/** What the file was called before the change, for the hosts that resolve a position by both. */readonly oldPath: string | null;- readonly line: number;- readonly side: PullRequestDiffSide;+ readonly position: PullRequestReviewPosition;/** The whole selection, which the comment collapses to one line but a question keeps. */readonly range: SelectedLineRange;}@@ -148,8 +152,21 @@ function toViewerSide(side: PullRequestDiffSide) {return side === "left" ? ("deletions" as const) : ("additions" as const);}-function fromViewerSide(side: string | undefined): PullRequestDiffSide {- return side === "deletions" ? "left" : "right";+function getReviewPositionAnchor(position: PullRequestReviewPosition): {+ line: number;+ side: PullRequestDiffSide;+} {+ switch (position.kind) {+ case "added":+ return { line: position.newLine, side: "right" };+ case "deleted":+ return { line: position.oldLine, side: "left" };+ case "context":+ return {+ line: position.side === "left" ? position.oldLine : position.newLine,+ side: position.side,+ };+ }}/**@@ -442,10 +459,14 @@ export function PullRequestCodeTab({if (commit === null) {for (const comment of pendingComments) {if (comment.path !== path) continue;- groupAt(comment.side, comment.line).pending.push(comment);+ const anchor = getReviewPositionAnchor(comment.position);+ groupAt(anchor.side, anchor.line).pending.push(comment);}}- if (draft?.fileKey === fileKey) groupAt(draft.side, draft.line).draft = true;+ if (draft?.fileKey === fileKey) {+ const anchor = getReviewPositionAnchor(draft.position);+ groupAt(anchor.side, anchor.line).draft = true;+ }const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles);@@ -594,12 +615,13 @@ export function PullRequestCodeTab({// that silently lost its first line on the other hosts would be worse than one line.const path = resolveFileDiffPath(file);const previousPath = resolveFileDiffPreviousPath(file);+ const position = resolveDiffReviewPosition(file, range.end, range.endSide ?? range.side);+ if (position === null) return;setDraft({fileKey: item.id,path,oldPath: previousPath === path ? null : previousPath,- line: range.end,- side: fromViewerSide(range.endSide ?? range.side),+ position,range,});},@@ -842,7 +864,7 @@ export function PullRequestCodeTab({{annotation.metadata.draft && draft ? (<DiffCommentAnnotationkind="draft"- rangeLabel={`${draft.path}:${draft.line}`}+ rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}text=""submitLabel="Add to review"{...(onAskAboutSelection@@ -864,8 +886,7 @@ export function PullRequestCodeTab({id: nextPendingReviewCommentId(),path: draft.path,...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }),- line: draft.line,- side: draft.side,+ position: draft.position,body,});setDraft(null);diff --git a/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts b/apps/web/src/components/pullRequest/pullRequestReviewStore.test.tsindex c35b58809..abbcab162 100644--- a/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";import { type PendingReviewComment, usePullRequestReviewStore } from "./pullRequestReviewStore";function comment(id: string, body = id): PendingReviewComment {- return { id, body, path: "src/app.ts", line: 1, side: "right" };+ return { id, body, path: "src/app.ts", position: { kind: "added", newLine: 1 } };}describe("pull request review drafts", () => {diff --git a/apps/web/src/components/pullRequest/pullRequestReviewStore.ts b/apps/web/src/components/pullRequest/pullRequestReviewStore.tsindex 8e207c252..41906a710 100644--- a/apps/web/src/components/pullRequest/pullRequestReviewStore.ts+++ b/apps/web/src/components/pullRequest/pullRequestReviewStore.ts@@ -6,17 +6,10 @@* hosts that have no pending review of their own. That also means a draft lives only as long* as the tab does, which is why this is deliberately not persisted.*/-import type { ProjectId, PullRequestDiffSide, PullRequestRef } from "@t3tools/contracts";+import type { ProjectId, PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts";import { create } from "zustand";-export interface PendingReviewComment {- readonly id: string;- readonly path: string;- /** The line in the file the comment's side names: the new file on the right, the old on the left. */- readonly line: number;- readonly side: PullRequestDiffSide;- readonly body: string;-}+export type PendingReviewComment = PullRequestReviewCommentDraft & { readonly id: string };/*** A counter rather than anything derived from the comment: two remarks on one line can be thediff --git a/apps/web/src/reviewCommentContext.ts b/apps/web/src/reviewCommentContext.tsindex 7ce319973..41f75eb38 100644--- a/apps/web/src/reviewCommentContext.ts+++ b/apps/web/src/reviewCommentContext.ts@@ -1,6 +1,15 @@import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";+import type { PullRequestReviewPosition } from "@t3tools/contracts";import * as Schema from "effect/Schema";+const ReviewCommentSelectionSchema = Schema.Struct({+ start: Schema.Number,+ side: Schema.Literals(["additions", "deletions"]),+ end: Schema.Number,+ endSide: Schema.Literals(["additions", "deletions"]),+});+type ReviewCommentSelection = typeof ReviewCommentSelectionSchema.Type;+export const ReviewCommentContextSchema = Schema.Struct({id: Schema.String,sectionId: Schema.String,@@ -12,6 +21,7 @@ export const ReviewCommentContextSchema = Schema.Struct({text: Schema.String,diff: Schema.String,fenceLanguage: Schema.optional(Schema.String),+ selection: Schema.optional(ReviewCommentSelectionSchema),});export interface ReviewCommentContext {@@ -25,6 +35,7 @@ export interface ReviewCommentContext {readonly text: string;readonly diff: string;readonly fenceLanguage?: string | undefined;+ readonly selection?: ReviewCommentSelection | undefined;}interface DiffReviewLine {@@ -267,10 +278,44 @@ function stripTrailingNewline(value: string): string {return value.endsWith("\n") ? value.slice(0, -1) : value;}-function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffReviewLine> {+function buildDiffReviewLines(+ fileDiff: FileDiffMetadata,+ includeExpandedContext: boolean,+ slice?: { readonly startIndex: number; readonly endIndex: number },+): ReadonlyArray<DiffReviewLine> {const rows: DiffReviewLine[] = [];+ let rowIndex = 0;+ let oldContextStart = 1;+ let newContextStart = 1;+ const pushRow = (row: DiffReviewLine) => {+ if (!slice || (rowIndex >= slice.startIndex && rowIndex <= slice.endIndex)) {+ rows.push(row);+ }+ rowIndex += 1;+ };+ const pushContextGap = (oldStart: number, newStart: number, lineCount: number) => {+ const count = Math.max(0, lineCount);+ const firstOffset = slice ? Math.max(0, slice.startIndex - rowIndex) : 0;+ const lastOffset = slice ? Math.min(count - 1, slice.endIndex - rowIndex) : count - 1;+ for (let offset = firstOffset; offset <= lastOffset; offset += 1) {+ rows.push({+ change: "context",+ oldLineNumber: oldStart + offset,+ newLineNumber: newStart + offset,+ content: stripTrailingNewline(fileDiff.additionLines[newStart + offset - 1] ?? ""),+ });+ }+ rowIndex += count;+ };for (const hunk of fileDiff.hunks) {+ if (includeExpandedContext) {+ const oldHunkStart = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);+ const newHunkStart = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);+ const contextLines = Math.min(oldHunkStart - oldContextStart, newHunkStart - newContextStart);+ pushContextGap(oldContextStart, newContextStart, contextLines);+ }+let oldLineNumber = hunk.deletionStart;let newLineNumber = hunk.additionStart;let deletionLineIndex = hunk.deletionLineIndex;@@ -279,7 +324,7 @@ function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffRevfor (const segment of hunk.hunkContent) {if (segment.type === "context") {for (let index = 0; index < segment.lines; index += 1) {- rows.push({+ pushRow({change: "context",oldLineNumber,newLineNumber,@@ -298,7 +343,7 @@ function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffRev}for (let index = 0; index < segment.deletions; index += 1) {- rows.push({+ pushRow({change: "delete",oldLineNumber,newLineNumber: null,@@ -309,7 +354,7 @@ function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffRev}for (let index = 0; index < segment.additions; index += 1) {- rows.push({+ pushRow({change: "add",oldLineNumber: null,newLineNumber,@@ -319,6 +364,19 @@ function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffRevadditionLineIndex += 1;}}++ oldContextStart = hunk.deletionStart + hunk.deletionCount;+ newContextStart = hunk.additionStart + hunk.additionCount;+ if (hunk.deletionCount === 0) oldContextStart += 1;+ if (hunk.additionCount === 0) newContextStart += 1;+ }++ if (includeExpandedContext) {+ const trailingLines = Math.min(+ fileDiff.deletionLines.length - oldContextStart + 1,+ fileDiff.additionLines.length - newContextStart + 1,+ );+ pushContextGap(oldContextStart, newContextStart, trailingLines);}return rows;@@ -343,9 +401,20 @@ export function restoreDiffReviewCommentRange(fileDiff: FileDiffMetadata,comment: ReviewCommentContext,): SelectedLineRange | null {- const lines = buildDiffReviewLines(fileDiff);- const startLine = lines[comment.startIndex];- const endLine = lines[comment.endIndex];+ if (comment.selection) return comment.selection;++ const includeExpandedContext = !fileDiff.isPartial;+ const startLine = buildDiffReviewLines(fileDiff, includeExpandedContext, {+ startIndex: comment.startIndex,+ endIndex: comment.startIndex,+ })[0];+ const endLine =+ comment.endIndex === comment.startIndex+ ? startLine+ : buildDiffReviewLines(fileDiff, includeExpandedContext, {+ startIndex: comment.endIndex,+ endIndex: comment.endIndex,+ })[0];if (!startLine || !endLine) return null;const start = getDiffReviewSelectionPoint(startLine);const end = getDiffReviewSelectionPoint(endLine);@@ -359,15 +428,118 @@ export function restoreDiffReviewCommentRange(}function findDiffReviewLineIndex(- lines: ReadonlyArray<DiffReviewLine>,+ fileDiff: FileDiffMetadata,lineNumber: number,side: SelectionSide | undefined,+ includeExpandedContext = !fileDiff.isPartial,): number {- const preferredKey = side === "deletions" ? "oldLineNumber" : "newLineNumber";- const preferredIndex = lines.findIndex((line) => line[preferredKey] === lineNumber);- if (preferredIndex >= 0) return preferredIndex;- const fallbackKey = preferredKey === "oldLineNumber" ? "newLineNumber" : "oldLineNumber";- return lines.findIndex((line) => line[fallbackKey] === lineNumber);+ const findOnSide = (selectedSide: "left" | "right") => {+ let rowIndex = 0;+ let oldContextStart = 1;+ let newContextStart = 1;+ const findContextIndex = (oldStart: number, newStart: number, lineCount: number) => {+ const count = Math.max(0, lineCount);+ const selectedStart = selectedSide === "left" ? oldStart : newStart;+ const offset = lineNumber - selectedStart;+ return offset >= 0 && offset < count ? rowIndex + offset : -1;+ };++ for (const hunk of fileDiff.hunks) {+ if (includeExpandedContext) {+ const oldContextEnd = hunk.deletionStart + (hunk.deletionCount === 0 ? 1 : 0);+ const newContextEnd = hunk.additionStart + (hunk.additionCount === 0 ? 1 : 0);+ const contextLines = Math.min(+ oldContextEnd - oldContextStart,+ newContextEnd - newContextStart,+ );+ const contextIndex = findContextIndex(oldContextStart, newContextStart, contextLines);+ if (contextIndex >= 0) return contextIndex;+ rowIndex += Math.max(0, contextLines);+ }++ let oldLineNumber = hunk.deletionStart;+ let newLineNumber = hunk.additionStart;+ for (const segment of hunk.hunkContent) {+ if (segment.type === "context") {+ const contextIndex = findContextIndex(oldLineNumber, newLineNumber, segment.lines);+ if (contextIndex >= 0) return contextIndex;+ rowIndex += segment.lines;+ oldLineNumber += segment.lines;+ newLineNumber += segment.lines;+ continue;+ }++ if (+ selectedSide === "left" &&+ lineNumber >= oldLineNumber &&+ lineNumber < oldLineNumber + segment.deletions+ ) {+ return rowIndex + lineNumber - oldLineNumber;+ }+ rowIndex += segment.deletions;+ oldLineNumber += segment.deletions;++ if (+ selectedSide === "right" &&+ lineNumber >= newLineNumber &&+ lineNumber < newLineNumber + segment.additions+ ) {+ return rowIndex + lineNumber - newLineNumber;+ }+ rowIndex += segment.additions;+ newLineNumber += segment.additions;+ }++ oldContextStart = hunk.deletionStart + hunk.deletionCount;+ newContextStart = hunk.additionStart + hunk.additionCount;+ if (hunk.deletionCount === 0) oldContextStart += 1;+ if (hunk.additionCount === 0) newContextStart += 1;+ }++ if (!includeExpandedContext) return -1;+ const trailingLines = Math.min(+ fileDiff.deletionLines.length - oldContextStart + 1,+ fileDiff.additionLines.length - newContextStart + 1,+ );+ return findContextIndex(oldContextStart, newContextStart, trailingLines);+ };++ const selectedSide = side === "deletions" ? "left" : "right";+ const preferredIndex = findOnSide(selectedSide);+ return preferredIndex >= 0+ ? preferredIndex+ : findOnSide(selectedSide === "left" ? "right" : "left");+}++/** Resolve the host-facing coordinates of a line selected in the diff viewer. */+export function resolveDiffReviewPosition(+ fileDiff: FileDiffMetadata,+ lineNumber: number,+ side: SelectionSide | undefined,+): PullRequestReviewPosition | null {+ const lineIndex = findDiffReviewLineIndex(fileDiff, lineNumber, side);+ if (lineIndex < 0) return null;+ const line = buildDiffReviewLines(fileDiff, !fileDiff.isPartial, {+ startIndex: lineIndex,+ endIndex: lineIndex,+ })[0];+ if (line === undefined) return null;++ switch (line.change) {+ case "add":+ return line.newLineNumber === null ? null : { kind: "added", newLine: line.newLineNumber };+ case "delete":+ return line.oldLineNumber === null ? null : { kind: "deleted", oldLine: line.oldLineNumber };+ case "context":+ return line.oldLineNumber === null || line.newLineNumber === null+ ? null+ : {+ kind: "context",+ oldLine: line.oldLineNumber,+ newLine: line.newLineNumber,+ side: side === "deletions" ? "left" : "right",+ };+ }}function getDiffRange(@@ -416,18 +588,27 @@ export function buildDiffReviewComment(input: {range: SelectedLineRange;text: string;}): ReviewCommentContext | null {- const lines = buildDiffReviewLines(input.fileDiff);- const startIndex = findDiffReviewLineIndex(lines, input.range.start, input.range.side);+ const includeExpandedContext = !input.fileDiff.isPartial;+ const startIndex = findDiffReviewLineIndex(+ input.fileDiff,+ input.range.start,+ input.range.side,+ includeExpandedContext,+ );const endIndex = findDiffReviewLineIndex(- lines,+ input.fileDiff,input.range.end,input.range.endSide ?? input.range.side,+ includeExpandedContext,);if (startIndex < 0 || endIndex < 0) return null;const normalizedStartIndex = Math.min(startIndex, endIndex);const normalizedEndIndex = Math.max(startIndex, endIndex);- const selectedLines = lines.slice(normalizedStartIndex, normalizedEndIndex + 1);+ const selectedLines = buildDiffReviewLines(input.fileDiff, includeExpandedContext, {+ startIndex: normalizedStartIndex,+ endIndex: normalizedEndIndex,+ });const oldRange = getDiffRange(selectedLines, "oldLineNumber");const newRange = getDiffRange(selectedLines, "newLineNumber");@@ -445,6 +626,12 @@ export function buildDiffReviewComment(input: {...selectedLines.map((line) => `${getDiffChangeMarker(line.change)}${line.content}`),].join("\n"),fenceLanguage: "diff",+ selection: {+ start: input.range.start,+ side: input.range.side ?? "additions",+ end: input.range.end,+ endSide: input.range.endSide ?? input.range.side ?? "additions",+ },};}diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex d1b2ba705..dea49ea8f 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -856,6 +856,26 @@ export const PullRequestCommentUpdateInput = Schema.Struct({});export type PullRequestCommentUpdateInput = typeof PullRequestCommentUpdateInput.Type;+/** The coordinates of one line in a pull request diff. */+export const PullRequestReviewPosition = Schema.Union([+ Schema.Struct({+ kind: Schema.Literal("added"),+ newLine: PositiveInt,+ }),+ Schema.Struct({+ kind: Schema.Literal("deleted"),+ oldLine: PositiveInt,+ }),+ Schema.Struct({+ kind: Schema.Literal("context"),+ oldLine: PositiveInt,+ newLine: PositiveInt,+ /** Which copy of an unchanged line the reviewer selected in a split diff. */+ side: PullRequestDiffSide,+ }),+]);+export type PullRequestReviewPosition = typeof PullRequestReviewPosition.Type;+/** One remark in a review that has not been sent yet, anchored to a line of the diff. */export const PullRequestReviewCommentDraft = Schema.Struct({path: TrimmedNonEmptyString,@@ -865,8 +885,7 @@ export const PullRequestReviewCommentDraft = Schema.Struct({* the hosts that address a comment by one path ignore this.*/oldPath: Schema.optional(TrimmedNonEmptyString),- line: PositiveInt,- side: PullRequestDiffSide,+ position: PullRequestReviewPosition,body: CommentBody,});export type PullRequestReviewCommentDraft = typeof PullRequestReviewCommentDraft.Type;